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

Added EC2 code examples (#518)

* Added EC2 code examples

* Updated EC2 describe-instances example based on feedback

* Updated EC2 Cargo.toml and monitor-instances code example based on feedback

* Removed extra blank line in EC2 monitor-instances code example.

* Refactored EC2 describe-instances example to use set_instance_ids with Option(al) instance ID

* Updated EC2 code examples to use -r REGION; added new list-all-instance-events code example

* Updated EC2 list-all-instance-events code example based on feedback

* Updated S3 Cargo.toml file for code examples

* Fixed package use statements in EC2 code examples

* Tweaked EC2 hello world code example to trigger actions

* Updated EC2 code examples to use asynchronous Config

* Updated EC2 code examples after cargo fmt

* Removed references to ProvideRegion from EC2 code examples

* Updated EC2 code examples to alpha 0.0.17 bits

* Added readme file for EC2 code examples

* Updated EC2 code examples to include unit tests, readme; refactored operations from main into separate functions.

* Removed unit tests from EC2 code examples.
parent 0ad0f331
Loading
Loading
Loading
Loading
+1 −0
Original line number Diff line number Diff line
@@ -13,6 +13,7 @@ vNext (Month Day, Year)
- :tada: Add presigned request support and example for Polly SynthesizeSpeech (smithy-rs#735, aws-sdk-rust#139)
- :bug: Fix error when receiving `Cont` event from S3 SelectObjectContent (smithy-rs#736)
- :bug: Fix bug in event stream receiver that could cause the last events in the response stream to be lost when using S3 SelectObjectContent (smithy-rs#736)
- Updated EC2 code examples to include readme; refactored operations from main into separate functions.
- 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.
+5 −2
Original line number Diff line number Diff line
[package]
name = "ec2-code-examples"
version = "0.1.0"
authors = ["Russell Cohen <rcoh@amazon.com>"]
authors = ["Russell Cohen <rcoh@amazon.com>", "Doug Schwartz <dougsch@amazon.com>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

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

Amazon Elastic Compute Cloud (Amazon EC2) is a web service that provides resizable computing capacity—literally, servers in Amazon's data centers—that you use to build and host your software systems.

## Purpose

These examples demonstrate how to perform several Amazon EC2 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

### describe-instances

This example lists the state of one or all of your Amazon EC2 instances

`cargo run --bin describe-instances -- [-i INSTANCE-ID] [-d DEFAULT-REGION] [-v]`

- _INSTANCE-ID_ is the ID of an instance to describe.
  If this argument is not supplied, the state of all instances is shown.
- _DEFAULT-REGION_ is optional name of a region, such as __us-east-1__.
  If this value is not supplied, the region defaults to __us-west-2__.
- __-v__ display additional information.  

### ec2-helloworld

This example describes the AWS Regions that are enabled for your account.

`cargo run --bin ec2-helloworld -- [-d DEFAULT-REGION] [-v]`

  If this argument is not supplied, the state of all instances is shown.
- _DEFAULT-REGION_ is optional name of a region, such as __us-east-1__.
  If this value is not supplied, the region defaults to __us-west-2__.
- __-v__ display additional information.  

### list-all-instance-events

This example shows the scheduled events for the Amazon Elastic Compute Cloud (Amazon EC2) instances in the Region.

`cargo run --bin list-all-instance-events -- [-d DEFAULT-REGION] [-v]`

- _DEFAULT-REGION_ is optional name of a region, such as __us-east-1__.
  If this value is not supplied, the region defaults to __us-west-2__.
- __-v__ display additional information.  

### monitor-instance

This example enables monitoring on an Amazon EC2 instance.

`cargo run --bin monitor-instance -- -i INSTANCE-ID [-d DEFAULT-REGION] [-v]`

- _INSTANCE-ID_ is the ID of an instance to monitor.
  If this argument is not supplied, the state of all instances is shown.
- _DEFAULT-REGION_ is optional name of a region, such as __us-east-1__.
  If this value is not supplied, the region defaults to __us-west-2__.
- __-v__ display additional information.  

### reboot-instance

This example reboots an Amazon EC2 instance.

`cargo run --bin reboot-instance -- -i INSTANCE-ID [-d DEFAULT-REGION] [-v]`

- _INSTANCE-ID_ is the ID of an instance to reboot.
  If this argument is not supplied, the state of all instances is shown.
- _DEFAULT-REGION_ is optional name of a region, such as __us-east-1__.
  If this value is not supplied, the region defaults to __us-west-2__.
- __-v__ display additional information.  

### start-instance

This example starts an Amazon EC2 instance.

`cargo run --bin start-instance -- -i INSTANCE-ID [-d DEFAULT-REGION] [-v]`

- _INSTANCE-ID_ is the ID of an instance to start.
  If this argument is not supplied, the state of all instances is shown.
- _DEFAULT-REGION_ is optional name of a region, such as __us-east-1__.
  If this value is not supplied, the region defaults to __us-west-2__.
- __-v__ display additional information.  

### stop-instance

This example stops an Amazon EC2 instance.

`cargo run --bin stop-instance -- -i INSTANCE-ID [-d DEFAULT-REGION] [-v]`

- _INSTANCE-ID_ is the ID of an instance to stop.
  If this argument is not supplied, the state of all instances is shown.
- _DEFAULT-REGION_ is optional name of a region, such as __us-east-1__.
  If this value is not supplied, the region defaults to __us-west-2__.
- __-v__ display additional information.

### Running the unit tests

To run the unit tests, enter the following command:

`cargo test`

## 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
+98 −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_ec2::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;

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

    /// To get info about one instance.
    #[structopt(short, long)]
    instance_id: Option<String>,

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

// Lists the state of an instance.
async fn show_state(
    client: &aws_sdk_ec2::Client,
    ids: Vec<String>,
) -> Result<(), aws_sdk_ec2::Error> {
    let resp = client
        .describe_instances()
        .set_instance_ids(Some(ids))
        .send()
        .await?;

    for reservation in resp.reservations.unwrap_or_default() {
        for instance in reservation.instances.unwrap_or_default() {
            println!("Instance ID: {}", instance.instance_id.unwrap());
            println!("State:       {:?}", instance.state.unwrap().name.unwrap());
            println!();
        }
    }

    Ok(())
}

/// Lists the state of one or all of your Amazon EC2 instances.
/// # Arguments
///
/// * `[-i INSTANCE-ID]` - The ID of an instance.
/// * `[-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 additional information.
#[tokio::main]
async fn main() -> Result<(), Error> {
    tracing_subscriber::fmt::init();
    let Opt {
        region,
        instance_id,
        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!("EC2 client version: {}", PKG_VERSION);
        println!(
            "Region:             {}",
            region_provider.region().await.unwrap().as_ref()
        );

        if instance_id.is_some() {
            println!("Instance ID:        {:?}", instance_id);
        }

        println!();
    }

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

    let mut ids: Vec<String> = Vec::new();
    let id_opt: std::option::Option<std::vec::Vec<std::string::String>>;

    match instance_id {
        None => id_opt = None,
        Some(i) => {
            ids.push(i);
            id_opt = Some(ids);
        }
    }

    show_state(&client, id_opt.unwrap()).await
}
+50 −6
Original line number Diff line number Diff line
@@ -3,17 +3,61 @@
 * SPDX-License-Identifier: Apache-2.0.
 */

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

#[tokio::main]
async fn main() -> Result<(), aws_sdk_ec2::Error> {
    let shared_config = aws_config::load_from_env().await;
    let client = Client::new(&shared_config);
#[derive(Debug, StructOpt)]
struct Opt {
    /// The AWS Region.
    #[structopt(short, long)]
    region: Option<String>,

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

// Describes the regions.
async fn show_regions(client: &aws_sdk_ec2::Client) -> Result<(), aws_sdk_ec2::Error> {
    let rsp = client.describe_regions().send().await?;

    println!("Regions:");
    for region in rsp.regions.unwrap_or_default() {
        println!("region: {:#?}", region.region_name.unwrap());
        println!("  {}", region.region_name.unwrap());
    }

    Ok(())
}

/// Describes the AWS Regions that are enabled for your account.
/// # Arguments
///
/// * `[-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 additional information.
#[tokio::main]
async fn main() -> Result<(), Error> {
    tracing_subscriber::fmt::init();
    let Opt { 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!("EC2 client version: {}", PKG_VERSION);
        println!(
            "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);

    show_regions(&client).await
}
Loading