rusticity-core 0.1.6

Core AWS SDK integration for Rusticity
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
use crate::config::AwsConfig;
use anyhow::Result;

#[derive(Clone, Debug)]
pub struct Stack {
    pub name: String,
    pub stack_id: String,
    pub status: String,
    pub created_time: String,
    pub updated_time: String,
    pub deleted_time: String,
    pub drift_status: String,
    pub last_drift_check_time: String,
    pub status_reason: String,
    pub description: String,
}

pub struct CloudFormationClient {
    config: AwsConfig,
}

impl CloudFormationClient {
    pub fn new(config: AwsConfig) -> Self {
        Self { config }
    }

    pub async fn list_stacks(&self, include_nested: bool) -> Result<Vec<Stack>> {
        let client = self.config.cloudformation_client();

        let mut stacks = Vec::new();
        let mut next_token: Option<String> = None;

        loop {
            let mut request = client.list_stacks();
            if let Some(token) = next_token {
                request = request.next_token(token);
            }

            let response = request.send().await?;

            if let Some(stack_summaries) = response.stack_summaries {
                for stack in stack_summaries {
                    // Skip nested stacks if not requested
                    if !include_nested {
                        if let Some(root_id) = &stack.root_id {
                            if root_id != stack.stack_id.as_deref().unwrap_or("") {
                                continue;
                            }
                        }
                    }

                    stacks.push(Stack {
                        name: stack.stack_name.unwrap_or_default(),
                        stack_id: stack.stack_id.unwrap_or_default(),
                        status: stack
                            .stack_status
                            .map(|s| s.as_str().to_string())
                            .unwrap_or_default(),
                        created_time: stack
                            .creation_time
                            .map(|dt| {
                                let timestamp = dt.secs();
                                let datetime = chrono::DateTime::from_timestamp(timestamp, 0)
                                    .unwrap_or_default();
                                datetime.format("%Y-%m-%d %H:%M:%S (UTC)").to_string()
                            })
                            .unwrap_or_default(),
                        updated_time: stack
                            .last_updated_time
                            .map(|dt| {
                                let timestamp = dt.secs();
                                let datetime = chrono::DateTime::from_timestamp(timestamp, 0)
                                    .unwrap_or_default();
                                datetime.format("%Y-%m-%d %H:%M:%S (UTC)").to_string()
                            })
                            .unwrap_or_default(),
                        deleted_time: stack
                            .deletion_time
                            .map(|dt| {
                                let timestamp = dt.secs();
                                let datetime = chrono::DateTime::from_timestamp(timestamp, 0)
                                    .unwrap_or_default();
                                datetime.format("%Y-%m-%d %H:%M:%S (UTC)").to_string()
                            })
                            .unwrap_or_default(),
                        drift_status: stack
                            .drift_information
                            .as_ref()
                            .and_then(|d| d.stack_drift_status.as_ref())
                            .map(|s| format!("{:?}", s))
                            .unwrap_or_default(),
                        last_drift_check_time: stack
                            .drift_information
                            .and_then(|d| d.last_check_timestamp)
                            .map(|dt| {
                                let timestamp = dt.secs();
                                let datetime = chrono::DateTime::from_timestamp(timestamp, 0)
                                    .unwrap_or_default();
                                datetime.format("%Y-%m-%d %H:%M:%S (UTC)").to_string()
                            })
                            .unwrap_or_default(),
                        status_reason: stack.stack_status_reason.unwrap_or_default(),
                        description: stack.template_description.unwrap_or_default(),
                    });
                }
            }

            next_token = response.next_token;
            if next_token.is_none() {
                break;
            }
        }

        Ok(stacks)
    }

    pub async fn describe_stack(&self, stack_name: &str) -> Result<StackDetails> {
        let client = self.config.cloudformation_client();

        let response = client
            .describe_stacks()
            .stack_name(stack_name)
            .send()
            .await?;

        let stack = response
            .stacks()
            .first()
            .ok_or_else(|| anyhow::anyhow!("Stack not found"))?;

        Ok(StackDetails {
            detailed_status: String::new(),
            root_stack: stack.root_id().unwrap_or("").to_string(),
            parent_stack: stack.parent_id().unwrap_or("").to_string(),
            termination_protection: stack.enable_termination_protection().unwrap_or(false),
            iam_role: stack.role_arn().unwrap_or("").to_string(),
            tags: stack
                .tags()
                .iter()
                .map(|t| {
                    (
                        t.key().unwrap_or("").to_string(),
                        t.value().unwrap_or("").to_string(),
                    )
                })
                .collect(),
            stack_policy: String::new(),
            rollback_monitoring_time: String::new(),
            rollback_alarms: stack
                .rollback_configuration()
                .map(|rc| {
                    rc.rollback_triggers()
                        .iter()
                        .map(|t| t.arn().unwrap_or("").to_string())
                        .collect()
                })
                .unwrap_or_default(),
            notification_arns: stack
                .notification_arns()
                .iter()
                .map(|s| s.to_string())
                .collect(),
        })
    }
}

#[derive(Debug, Clone)]
pub struct StackDetails {
    pub detailed_status: String,
    pub root_stack: String,
    pub parent_stack: String,
    pub termination_protection: bool,
    pub iam_role: String,
    pub tags: Vec<(String, String)>,
    pub stack_policy: String,
    pub rollback_monitoring_time: String,
    pub rollback_alarms: Vec<String>,
    pub notification_arns: Vec<String>,
}

impl CloudFormationClient {
    pub async fn get_template(&self, stack_name: &str) -> Result<String> {
        let client = self.config.cloudformation_client();
        let response = client.get_template().stack_name(stack_name).send().await?;

        Ok(response.template_body().unwrap_or("").to_string())
    }

    pub async fn get_stack_parameters(&self, stack_name: &str) -> Result<Vec<StackParameter>> {
        let client = self.config.cloudformation_client();
        let response = client
            .describe_stacks()
            .stack_name(stack_name)
            .send()
            .await?;

        let stack = response
            .stacks()
            .first()
            .ok_or_else(|| anyhow::anyhow!("Stack not found"))?;

        let mut parameters = Vec::new();
        for param in stack.parameters() {
            parameters.push(StackParameter {
                key: param.parameter_key().unwrap_or("").to_string(),
                value: param.parameter_value().unwrap_or("").to_string(),
                resolved_value: param.resolved_value().unwrap_or("").to_string(),
            });
        }

        Ok(parameters)
    }

    pub async fn get_stack_outputs(&self, stack_name: &str) -> Result<Vec<StackOutput>> {
        let client = self.config.cloudformation_client();
        let response = client
            .describe_stacks()
            .stack_name(stack_name)
            .send()
            .await?;

        let stack = response
            .stacks()
            .first()
            .ok_or_else(|| anyhow::anyhow!("Stack not found"))?;

        let mut outputs = Vec::new();
        for output in stack.outputs() {
            outputs.push(StackOutput {
                key: output.output_key().unwrap_or("").to_string(),
                value: output.output_value().unwrap_or("").to_string(),
                description: output.description().unwrap_or("").to_string(),
                export_name: output.export_name().unwrap_or("").to_string(),
            });
        }

        outputs.sort_by(|a, b| a.key.cmp(&b.key));

        Ok(outputs)
    }

    pub async fn get_stack_resources(&self, stack_name: &str) -> Result<Vec<StackResource>> {
        let client = self.config.cloudformation_client();
        let response = client
            .describe_stack_resources()
            .stack_name(stack_name)
            .send()
            .await?;

        let mut resources = Vec::new();
        for resource in response.stack_resources() {
            resources.push(StackResource {
                logical_id: resource.logical_resource_id().unwrap_or("").to_string(),
                physical_id: resource.physical_resource_id().unwrap_or("").to_string(),
                resource_type: resource.resource_type().unwrap_or("").to_string(),
                status: resource
                    .resource_status()
                    .map(|s| s.as_str())
                    .unwrap_or("")
                    .to_string(),
                module_info: resource
                    .module_info()
                    .and_then(|m| m.logical_id_hierarchy())
                    .unwrap_or("")
                    .to_string(),
            });
        }

        resources.sort_by(|a, b| a.logical_id.cmp(&b.logical_id));

        Ok(resources)
    }

    pub async fn list_stack_events(&self, stack_name: &str) -> Result<Vec<StackEvent>> {
        let client = self.config.cloudformation_client();
        let mut events = Vec::new();
        let mut next_token: Option<String> = None;

        loop {
            let mut req = client.describe_stack_events().stack_name(stack_name);
            if let Some(ref token) = next_token {
                req = req.next_token(token);
            }
            let response = req.send().await?;

            for e in response.stack_events() {
                events.push(StackEvent {
                    event_id: e.event_id().unwrap_or("").to_string(),
                    timestamp: e
                        .timestamp()
                        .map(|t| {
                            t.fmt(aws_smithy_types::date_time::Format::DateTime)
                                .unwrap_or_default()
                        })
                        .unwrap_or_default(),
                    logical_id: e.logical_resource_id().unwrap_or("").to_string(),
                    status: e
                        .resource_status()
                        .map(|s| s.as_str())
                        .unwrap_or("")
                        .to_string(),
                    detailed_status: String::new(),
                    status_reason: e.resource_status_reason().unwrap_or("").to_string(),
                    hook_invocation_count: String::new(),
                    resource_type: e.resource_type().unwrap_or("").to_string(),
                    physical_id: e.physical_resource_id().unwrap_or("").to_string(),
                    client_request_token: e.client_request_token().unwrap_or("").to_string(),
                    operation_id: String::new(),
                });
            }

            next_token = response.next_token().map(|s| s.to_string());
            if next_token.is_none() {
                break;
            }
        }

        // Already sorted newest-first by the API, keep that order
        Ok(events)
    }

    pub async fn list_change_sets(&self, stack_name: &str) -> Result<Vec<StackChangeSet>> {
        let client = self.config.cloudformation_client();
        let mut change_sets = Vec::new();
        let mut next_token: Option<String> = None;

        loop {
            let mut req = client.list_change_sets().stack_name(stack_name);
            if let Some(ref token) = next_token {
                req = req.next_token(token);
            }
            let response = req.send().await?;

            for cs in response.summaries() {
                let created_time = cs
                    .creation_time()
                    .map(|t| {
                        t.fmt(aws_smithy_types::date_time::Format::DateTime)
                            .unwrap_or_default()
                    })
                    .unwrap_or_default();

                change_sets.push(StackChangeSet {
                    name: cs.change_set_name().unwrap_or("").to_string(),
                    change_set_id: cs.change_set_id().unwrap_or("").to_string(),
                    created_time,
                    status: cs.status().map(|s| s.as_str()).unwrap_or("").to_string(),
                    description: cs.description().unwrap_or("").to_string(),
                    root_change_set_id: cs.root_change_set_id().unwrap_or("").to_string(),
                    parent_change_set_id: cs.parent_change_set_id().unwrap_or("").to_string(),
                });
            }

            next_token = response.next_token().map(|s| s.to_string());
            if next_token.is_none() {
                break;
            }
        }

        Ok(change_sets)
    }
}

#[derive(Debug, Clone)]
pub struct StackParameter {
    pub key: String,
    pub value: String,
    pub resolved_value: String,
}

#[derive(Debug, Clone)]
pub struct StackOutput {
    pub key: String,
    pub value: String,
    pub description: String,
    pub export_name: String,
}

#[derive(Debug, Clone)]
pub struct StackResource {
    pub logical_id: String,
    pub physical_id: String,
    pub resource_type: String,
    pub status: String,
    pub module_info: String,
}

#[derive(Debug, Clone)]
pub struct StackEvent {
    pub event_id: String,
    pub timestamp: String,
    pub logical_id: String,
    pub status: String,
    pub detailed_status: String,
    pub status_reason: String,
    pub hook_invocation_count: String,
    pub resource_type: String,
    pub physical_id: String,
    pub client_request_token: String,
    pub operation_id: String,
}

#[derive(Debug, Clone)]
pub struct StackChangeSet {
    pub name: String,
    pub change_set_id: String,
    pub created_time: String,
    pub status: String,
    pub description: String,
    pub root_change_set_id: String,
    pub parent_change_set_id: String,
}