Commit 7e477cd9 authored by Doug's avatar Doug Committed by John DiSanti
Browse files

Updated AWS Config code examples (#597)

* Renamed config-helloword as show-resource-history; added delete-configuration-recorder, delete-delivery-channel, enable-config, list-configuration-recorders, list-delivery-channels, and list-resources code examples; all for AWS Config

* Updated AWS Config sync code example to use latest code style

* Updated AWS Config code examples based on feedback; uses latest code style

* Added config-helloworld.rs back to config code examples

* Updated Config code examples to use asynchronous Config

* Updated Config code examples to alpha 0.0.17 bits

* Updated Config hello world code example

* Added readme file for AWS Config code examples; updated internal docs in config-helloworld code example

* Added info about AWS Config code examples to SDK change log.

* Updated AWS Config code examples based on feedback.

* Fixed typos in AWS Config code examples

* Updated AWS Config code examples to include unit tests, readme, moved operations from main into separate function.

* Removed unit tests from AWS Config code examples.

* Remove `actix-rt` dependency
parent b48c415e
Loading
Loading
Loading
Loading
+1 −0
Original line number Diff line number Diff line
@@ -17,6 +17,7 @@ vNext (Month Day, Year)
- Updated Transcribe code example to take an audio file as a command-line option and added readme.
- Refactored API Gateway code example by moving operation out of main and into a separate function; added readme.
- Updated Auto Scaling code example to move operation from main to separate function; added readme.
- Updated AWS Config code examples to include a readme; added command-line options; added DeleteConfigurationRecorder, DeleteDeliveryChannel, ListConfigurationRecorders, ListDeliveryChannels, ListResources, ShowResourceHistory, and EnableConfig code examples.
- :tada: Add support for 6 new AWS services:
    - Wisdom
    - VoiceId
+1 −2
Original line number Diff line number Diff line
@@ -8,8 +8,7 @@ edition = "2018"

[dependencies]
aws-config = { path = "../../build/aws-sdk/aws-config" }
config = { package = "aws-sdk-config", path = "../../build/aws-sdk/config" }
aws-types = { path = "../../build/aws-sdk/aws-types" }
aws-sdk-config = { package = "aws-sdk-config", path = "../../build/aws-sdk/config" }
tokio = { version = "1", features = ["full"] }
structopt = { version = "0.3", default-features = false }
tracing-subscriber = "0.2.18"
+129 −0
Original line number Diff line number Diff line
# AWS SDK for Rust code examples for AWS Config

AWS Config 

## Purpose

These examples demonstrate how to perform several AWS Config operations using the alpha version of the AWS SDK for Rust.

## Prerequisites

You must have an AWS account, and have configured your default credentials and AWS Region as described in [https://github.com/awslabs/aws-sdk-rust](https://github.com/awslabs/aws-sdk-rust).

## Running the code

### config-helloworld

This example lists the configuration history for an AWS Config resource.

`cargo run --bin config-helloworld -- -resource_id RESOURCE-ID -resource_type RESOURCE-TYPE NAME [-r REGION] [-v]`

- _RESOURCE-ID_ is the ID of the AWS Config resource.
- _RESOURCE-TYPE_ is the type of the AWS Config resource, such as __AWS::EC2::SecurityGroup__.
- _REGION_ is the Region in which the client is created.
  If not supplied, uses the value of the __AWS_REGION__ environment variable.
  If the environment variable is not set, defaults to __us-west-2__.
- __-v__ displays additional information.

### delete-configuration-recorder

This example deletes an AWS Config configuration recorder.

`cargo run --bin delete-configuration-recorder -- -n NAME [-r REGION] [-v]`

- _NAME_ is the name of the configuration recorder to delete.
- _REGION_ is the Region in which the client is created.
  If not supplied, uses the value of the __AWS_REGION__ environment variable.
  If the environment variable is not set, defaults to __us-west-2__.
- __-v__ displays additional information.

### delete-delivery-channel

This example deletes an AWS Config delivery channel.

`cargo run --bin delete-delivery-channel -- -c CHANNEL [-r REGION] [-v]`

- _CHANNEL_ is the name of the channel to delete.
- _REGION_ is the Region in which the client is created.
  If not supplied, uses the value of the __AWS_REGION__ environment variable.
  If the environment variable is not set, defaults to __us-west-2__.
- __-v__ displays additional information.

### enable-config

This example enables AWS Config for a resource type, in the Region.

`cargo run --bin enable-config -- -b BUCKET -i IAM-ARN -k KMS-ARN -n NAME -p PREFIX -s SNS-ARN -t TYPE [-r REGION] [-v]`

- _BUCKET_ is the name of the Amazon bucket to which AWS Config delivers configuration snapshots and configuration history files.
- _IAM-ARN_ is the ARN of the IAM role that used to describe the AWS resources associated with the account.
- _KMS-ARN_ is the ARN of the KMS key that used to encrypt the data in the bucket.
- _NAME_ is the name of the configuration.
- _PREFIX_ is the  prefix for the bucket.
- _SNS-ARN_ is the  ARN of the Amazon SNS topic to which AWS Config sends notifications about configuration changes.
- _TYPE_ is the type of resource for AWS Config to support.
  If not supplied, defaults to `AWS::DynamoDB::Table` (DynamoDB tables).
- _REGION_ is the Region in which the client is created.
  If not supplied, uses the value of the __AWS_REGION__ environment variable.
  If the environment variable is not set, defaults to __us-west-2__.
- __-v__ displays additional information.

### list-configuration-recorders

This example lists the AWS Config configuration recorders in the Region.

`cargo run --bin list-configuration-recorders -- [-r REGION] [-v]`

- _REGION_ is the Region in which the client is created.
  If not supplied, uses the value of the __AWS_REGION__ environment variable.
  If the environment variable is not set, defaults to __us-west-2__.
- __-v__ displays additional information.

### list-delivery-channels

This example lists the AWS Config delivery channels in the Region.

`cargo run --bin list-delivery-channels -- [-r REGION] [-v]`

- _REGION_ is the Region in which the client is created.
  If not supplied, uses the value of the __AWS_REGION__ environment variable.
  If the environment variable is not set, defaults to __us-west-2__.
- __-v__ displays additional information.

### list-resources

This example lists your AWS Config resources, by resource type, in the Region.

`cargo run --bin list-resources -- [-r REGION] [-v]`

- _REGION_ is the Region in which the client is created.
  If not supplied, uses the value of the __AWS_REGION__ environment variable.
  If the environment variable is not set, defaults to __us-west-2__.
- __-v__ displays additional information.

### show-resource-history

This example displays the configuration history for a resource.

`cargo run --bin show-resource-history -- -i ID --resource-type RESOURCE-TYPE [-r REGION] [-v]`

- _ID_ is the ID of the resource.
- _RESOURCE-TYPE_ is the resource type, such as `AWS::EC2::SecurityGroup`.
- _REGION_ is the Region in which the client is created.
  If not supplied, uses the value of the __AWS_REGION__ environment variable.
  If the environment variable is not set, defaults to __us-west-2__.
- __-v__ displays additional information.

### Notes

- We recommend that you grant this code least privilege,
  or at most the minimum permissions required to perform the task.
  For more information, see
  [Grant Least Privilege](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege)
  in the AWS Identity and Access Management User Guide.
- This code has not been tested in all AWS Regions.
  Some AWS services are available only in specific
  [Regions](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services).
- Running this code might result in charges to your AWS account.

Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0
 No newline at end of file
+36 −22
Original line number Diff line number Diff line
@@ -4,14 +4,13 @@
 */

use aws_config::meta::region::RegionProviderChain;

use config::model::ResourceType;
use config::{Client, Error, Region};
use aws_sdk_config::model::ResourceType;
use aws_sdk_config::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;

#[derive(Debug, StructOpt)]
struct Opt {
    /// The default AWS Region.
    /// The AWS Region.
    #[structopt(short, long)]
    region: Option<String>,

@@ -28,12 +27,36 @@ struct Opt {
    verbose: bool,
}

/// Lists the configuration history for a resource
// Retrieves the configuration history for a resource.
async fn get_history(
    client: &aws_sdk_config::Client,
    id: &str,
    res: ResourceType,
) -> Result<(), aws_sdk_config::Error> {
    let rsp = client
        .get_resource_config_history()
        .resource_id(id)
        .resource_type(res)
        .send()
        .await?;

    println!("configuration history for {}:", id);

    for item in rsp.configuration_items.unwrap_or_default() {
        println!("item: {:?}", item);
    }

    Ok(())
}

/// Lists the configuration history for a resource in the Region.
///
/// NOTE: AWS Config must be enabled to discover resources
/// # Arguments
///
/// * `[-d DEFAULT-REGION]` - The Region in which the client is created.
/// * `-resource_id RESOURCE-ID` - The ID of the resource.
/// * `-resource_type RESOURCE-TYPE` - The type of resource, such as **AWS::EC2::SecurityGroup**.
/// * `[-r REGION]` - The AWS Region in which the client is created.
///   If not supplied, uses the value of the **AWS_REGION** environment variable.
///   If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display information.
@@ -50,20 +73,21 @@ async fn main() -> Result<(), Error> {
    let region_provider = RegionProviderChain::first_try(region.map(Region::new))
        .or_default_provider()
        .or_else(Region::new("us-west-2"));
    let shared_config = aws_config::from_env().region(region_provider).load().await;
    let client = Client::new(&shared_config);

    println!();

    if verbose {
        println!("Config client version: {}", config::PKG_VERSION);
        println!("Config client version: {}", PKG_VERSION);
        println!(
            "Region:               {:?}",
            shared_config.region().unwrap()
            "Region:                {}",
            region_provider.region().await.unwrap().as_ref()
        );
        println!();
    }

    let shared_config = aws_config::from_env().region(region_provider).load().await;
    let client = Client::new(&shared_config);

    // parse resource type from user input
    let parsed = ResourceType::from(resource_type.as_str());
    if matches!(parsed, ResourceType::Unknown(_)) {
@@ -73,16 +97,6 @@ async fn main() -> Result<(), Error> {
            ResourceType::values()
        )
    }
    let rsp = client
        .get_resource_config_history()
        .resource_id(&resource_id)
        .resource_type(parsed)
        .send()
        .await?;
    println!("configuration history for {}:", resource_id);
    for item in rsp.configuration_items.unwrap_or_default() {
        println!("item: {:?}", item);
    }

    Ok(())
    get_history(&client, &resource_id, parsed).await
}
+81 −0
Original line number Diff line number Diff line
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0.
 */

use aws_config::meta::region::RegionProviderChain;
use aws_sdk_config::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;

#[derive(Debug, StructOpt)]
struct Opt {
    /// The AWS Region.
    #[structopt(short, long)]
    region: Option<String>,

    /// The name of the configuration recorder to delete.
    #[structopt(short, long)]
    name: String,

    /// Whether to display additional information.
    #[structopt(short, long)]
    verbose: bool,
}

// Deletes a configuration recorder.
async fn delete_recorder(
    client: &aws_sdk_config::Client,
    name: &str,
) -> Result<(), aws_sdk_config::Error> {
    client
        .delete_configuration_recorder()
        .configuration_recorder_name(name)
        .send()
        .await?;

    println!("Done");

    println!();

    Ok(())
}

/// Deletes an AWS Config configuration recorder.
///
/// # Arguments
///
/// * `-n NAME` - The name of the configuration recorder to delete.
/// * `[-r REGION]` - The Region in which the client is created.
///   If not supplied, uses the value of the **AWS_REGION** environment variable.
///   If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display information.
#[tokio::main]
async fn main() -> Result<(), Error> {
    tracing_subscriber::fmt::init();
    let Opt {
        name,
        region,
        verbose,
    } = Opt::from_args();

    let region_provider = RegionProviderChain::first_try(region.map(Region::new))
        .or_default_provider()
        .or_else(Region::new("us-west-2"));
    println!();

    if verbose {
        println!("Config client version:  {}", PKG_VERSION);
        println!(
            "Region:                 {}",
            region_provider.region().await.unwrap().as_ref()
        );
        println!("Configuration recorder: {}", &name);

        println!();
    }

    let shared_config = aws_config::from_env().region(region_provider).load().await;
    let client = Client::new(&shared_config);

    delete_recorder(&client, &name).await
}
Loading