Skip to main content

commonware_deployer/aws/
clean.rs

1//! `clean` subcommand for `ec2`
2
3use crate::aws::{
4    s3::{
5        self, delete_bucket_and_contents, delete_bucket_config, get_bucket_name,
6        is_no_such_bucket_error,
7    },
8    Error, MONITORING_REGION,
9};
10use aws_config::Region;
11use tracing::info;
12
13/// Deletes the shared S3 cache bucket and all its contents
14pub async fn clean() -> Result<(), Error> {
15    let bucket_name = get_bucket_name();
16    info!(bucket = bucket_name.as_str(), "cleaning S3 bucket");
17
18    // Create S3 client in the monitoring region (where bucket is located)
19    let s3_client = s3::create_client(Region::new(MONITORING_REGION)).await;
20
21    // Delete all objects and the bucket itself
22    match delete_bucket_and_contents(&s3_client, &bucket_name).await {
23        Ok(()) => {
24            info!(bucket = bucket_name.as_str(), "cleaned S3 bucket");
25        }
26        Err(e) => {
27            if is_no_such_bucket_error(&e) {
28                info!(
29                    bucket = bucket_name.as_str(),
30                    "bucket does not exist, nothing to clean"
31                );
32            } else {
33                return Err(e);
34            }
35        }
36    }
37
38    // Delete the config file so a new bucket name is generated on next use
39    delete_bucket_config();
40    info!(bucket = bucket_name.as_str(), "deleted bucket config");
41
42    Ok(())
43}