### Amazon MSK Getting Started Tutorial Script Source: https://docs.aws.amazon.com/code-library/latest/ug/bash_2_kafka_code_examples.md This Bash script automates the setup and execution of the Amazon MSK Getting Started tutorial, covering cluster creation, IAM permissions, client setup, topic management, and resource cleanup. ```bash #!/bin/bash # Amazon MSK Getting Started Tutorial Script - Version 8 # This script automates the steps in the Amazon MSK Getting Started tutorial ``` -------------------------------- ### Getting Started with Virtual Machines Source: https://docs.aws.amazon.com/code-library/latest/ug/ec2_code_examples.md Example for launching an EC2 instance. ```bash aws ec2 run-instances --image-id ami-0abcdef1234567890 --instance-type t2.micro --count 1 --subnet-id subnet-0123456789abcdef0 --security-group-ids sg-0123456789abcdef0 ``` -------------------------------- ### CloudFront Getting Started Tutorial Script Source: https://docs.aws.amazon.com/cli/latest/userguide/bash_cloudfront_code_examples.html This Bash script automates the setup for the CloudFront Getting Started Tutorial. It creates an S3 bucket, uploads content, sets up a CloudFront distribution with OAC, and includes error handling and logging. ```bash #!/bin/bash # CloudFront Getting Started Tutorial Script # This script creates an S3 bucket, uploads sample content, creates a CloudFront distribution with OAC, # and demonstrates how to access content through CloudFront. set -euo pipefail # Set up logging LOG_FILE="cloudfront-tutorial.log" exec > >(tee -a "$LOG_FILE") 2>&1 echo "Starting CloudFront Getting Started Tutorial at $(date)" # Function to handle errors handle_error() { echo "ERROR: $1" >&2 echo "Resources created before error:" if [ -n "${BUCKET_NAME:-}" ]; then echo "- S3 Bucket: $BUCKET_NAME" fi if [ -n "${OAC_ID:-}" ]; then echo "- CloudFront Origin Access Control: $OAC_ID" fi if [ -n "${DISTRIBUTION_ID:-}" ]; then echo "- CloudFront Distribution: $DISTRIBUTION_ID" fi echo "Attempting to clean up resources..." cleanup exit 1 } ``` -------------------------------- ### Get Started with Software Marketplace Purchasing Source: https://docs.aws.amazon.com/code-library/latest/ug/ec2_code_examples.md Example for purchasing software from the AWS Marketplace. ```bash aws marketplace-catalog list-categories --catalog-name AWSMarketplace --filter "Name=productType,Value=SaaS" ``` -------------------------------- ### Getting Started with Load Balancing Source: https://docs.aws.amazon.com/code-library/latest/ug/ec2_code_examples.md Example for creating an Application Load Balancer using AWS. ```bash aws elbv2 create-load-balancer --name my-load-balancer --subnets subnet-0123456789abcdef0 subnet-0fedcba9876543210 --scheme internet-facing --type application ``` -------------------------------- ### DynamoDB Getting Started Tutorial Script (Bash) Source: https://docs.aws.amazon.com/code-library/latest/ug/dynamodb_example_dynamodb_GettingStarted_070_section.md This Bash script demonstrates fundamental Amazon DynamoDB operations. It includes setup for logging and validation of the AWS CLI installation. ```bash #!/bin/bash # DynamoDB Getting Started Tutorial Script # This script demonstrates basic operations with Amazon DynamoDB: # - Creating a table # - Writing data to the table # - Reading data from the table # - Updating data in the table # - Querying data in the table # - Deleting the table (cleanup) set -uo pipefail # Set up logging with secure permissions LOG_DIR="${XDG_STATE_HOME:-.}/dynamodb-tutorial-logs" mkdir -p "$LOG_DIR" LOG_FILE="$LOG_DIR/dynamodb-tutorial-$(date +%Y%m%d-%H%M%S).log" chmod 700 "$LOG_DIR" touch "$LOG_FILE" chmod 600 "$LOG_FILE" exec > >(tee -a "$LOG_FILE") 2>&1 echo "Starting DynamoDB Getting Started Tutorial at $(date)" echo "Logging to $LOG_FILE" # Validate AWS CLI is configured if ! command -v aws &> /dev/null; then echo "ERROR: AWS CLI is not installed or not in PATH" exit 1 fi ``` -------------------------------- ### Getting Started with Managed Streaming Source: https://docs.aws.amazon.com/code-library/latest/ug/ec2_code_examples.md Example for creating a Kafka cluster using Amazon MSK. ```bash aws kafka create-cluster --cluster-name my-msk-cluster --broker-node-group-info "{"InstanceType":"kafka.t3.small","NodeCount":3,"ZonedSaferoute":true,"SubnetIds":["subnet-0123456789abcdef0","subnet-0fedcba9876543210"]}" --kafka-version "2.8.1" --encryption-info "{"EncryptionInTransit":{"ClientBroker":"TLS"}}" ``` -------------------------------- ### EMR Getting Started Tutorial Script Source: https://docs.aws.amazon.com/cli/latest/userguide/bash_emr_code_examples.html This comprehensive Bash script automates the setup and cleanup for an Amazon EMR Getting Started tutorial. It includes error handling, logging, resource creation (S3 bucket, EMR cluster), and cleanup. ```bash #!/bin/bash # EMR Getting Started Tutorial Script # This script automates the steps in the Amazon EMR Getting Started tutorial set -euo pipefail # Security: Set strict mode and trap errors trap 'handle_error "Script interrupted or command failed"' ERR # Set up logging with secure permissions LOG_FILE="emr-tutorial.log" touch "$LOG_FILE" chmod 600 "$LOG_FILE" exec > >(tee -a "$LOG_FILE") 2>&1 echo "Starting Amazon EMR Getting Started Tutorial Script" echo "Logging to $LOG_FILE" # Function to handle errors handle_error() { echo "ERROR: $1" echo "Resources created so far:" if [ -n "${BUCKET_NAME:-}" ]; then echo "- S3 Bucket: $BUCKET_NAME"; fi if [ -n "${CLUSTER_ID:-}" ]; then echo "- EMR Cluster: $CLUSTER_ID"; fi echo "Attempting to clean up resources..." cleanup exit 1 } # Function to clean up resources cleanup() { echo "" echo "===========================================" echo "CLEANUP IN PROGRESS" echo "===========================================" echo "Starting cleanup process..." # Terminate EMR cluster if it exists if [ -n "${CLUSTER_ID:-}" ]; then echo "Terminating EMR cluster: $CLUSTER_ID" aws emr terminate-clusters --cluster-ids "$CLUSTER_ID" 2>/dev/null || true echo "Waiting for cluster to terminate..." aws emr wait cluster-terminated --cluster-id "$CLUSTER_ID" 2>/dev/null || true echo "Cluster terminated successfully." fi # Delete S3 bucket and contents if it exists and is not shared if [ -n "${BUCKET_NAME:-}" ] && [ "${BUCKET_IS_SHARED:-false}" != "true" ]; then echo "Deleting S3 bucket contents: $BUCKET_NAME" aws s3 rm "s3://$BUCKET_NAME" --recursive 2>/dev/null || true echo "Deleting S3 bucket: $BUCKET_NAME" aws s3 rb "s3://$BUCKET_NAME" 2>/dev/null || true fi # Remove temporary key pair file if created by this script if [ -f "${KEY_NAME_FILE:-}" ]; then rm -f "$KEY_NAME_FILE" echo "Removed temporary key pair file." fi echo "Cleanup completed." } # Validate AWS CLI is installed and configured if ! command -v aws &> /dev/null; then handle_error "AWS CLI is not installed" fi # Test AWS credentials if ! aws sts get-caller-identity > /dev/null 2>&1; then handle_error "AWS credentials are not configured or invalid" fi # Generate a random identifier for S3 bucket RANDOM_ID=$(openssl rand -hex 6) # Check for shared prereq bucket PREREQ_BUCKET=$(aws cloudformation describe-stacks --stack-name tutorial-prereqs-bucket \ --query 'Stacks[0].Outputs[?OutputKey==`BucketName`].OutputValue' --output text 2>/dev/null || true) if [ -n "$PREREQ_BUCKET" ] && [ "$PREREQ_BUCKET" != "None" ]; then BUCKET_NAME="$PREREQ_BUCKET" BUCKET_IS_SHARED=true echo "Using shared bucket: $BUCKET_NAME" else BUCKET_IS_SHARED=false BUCKET_NAME="emr-${RANDOM_ID}" fi echo "Using bucket name: $BUCKET_NAME" # Create S3 bucket with security best practices echo "Creating S3 bucket: $BUCKET_NAME" aws s3 mb "s3://$BUCKET_NAME" --region "${AWS_REGION:-us-east-1}" || handle_error "Failed to create S3 bucket" # Tag the bucket aws s3api put-bucket-tagging --bucket "$BUCKET_NAME" \ --tagging 'TagSet=[{Key=project,Value=doc-smith},{Key=tutorial,Value=emr-gs}]' # Enable bucket versioning for safety aws s3api put-bucket-versioning --bucket "$BUCKET_NAME" --versioning-configuration Status=Enabled || true ``` -------------------------------- ### Get Started with Elastic Load Balancing Source: https://docs.aws.amazon.com/code-library/latest/ug/javascript_3_elastic-load-balancing-v2_code_examples.md This example demonstrates how to initialize the ElasticLoadBalancingV2Client and list available load balancers. It's a good starting point for interacting with the service. ```javascript import { ElasticLoadBalancingV2Client, DescribeLoadBalancersCommand, } from "@aws-sdk/client-elastic-load-balancing-v2"; export async function main() { const client = new ElasticLoadBalancingV2Client({}); const { LoadBalancers } = await client.send( new DescribeLoadBalancersCommand({}), ); const loadBalancersList = LoadBalancers.map( (lb) => `• ${lb.LoadBalancerName}: ${lb.DNSName}`, ).join("\n"); console.log( "Hello, Elastic Load Balancing! Let's list some of your load balancers:\n", loadBalancersList, ); } // Call function if run directly import { fileURLToPath } from "node:url"; if (process.argv[1] === fileURLToPath(import.meta.url)) { main(); } ``` -------------------------------- ### Getting Started with Document Databases Source: https://docs.aws.amazon.com/code-library/latest/ug/ec2_code_examples.md Example for creating an Amazon DocumentDB cluster. ```bash aws docdb create-db-cluster --db-cluster-identifier my-docdb-cluster --engine docdb --master-username admin --master-user-password mypassword --db-subnet-group-name my-db-subnet-group ``` -------------------------------- ### RDS Get Started Example Setup (Kotlin) Source: https://docs.aws.amazon.com/code-library/latest/ug/rds_example_rds_Scenario_GetStartedInstances_section.md Provides setup instructions and usage requirements for a comprehensive Kotlin example that interacts with Amazon RDS. This includes prerequisites like AWS credentials, Secrets Manager setup, and command-line arguments. ```kotlin /** Before running this code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html This example requires an AWS Secrets Manager secret that contains the database credentials. If you do not create a secret, this example will not work. For more details, see: https://docs.aws.amazon.com/secretsmanager/latest/userguide/integrating_how-services-use-secrets_RS.html This example performs the following tasks: 1. Returns a list of the available DB engines by invoking the DescribeDbEngineVersions method. 2. Selects an engine family and create a custom DB parameter group by invoking the createDBParameterGroup method. 3. Gets the parameter groups by invoking the DescribeDbParameterGroups method. 4. Gets parameters in the group by invoking the DescribeDbParameters method. 5. Modifies both the auto_increment_offset and auto_increment_increment parameters by invoking the modifyDbParameterGroup method. 6. Gets and displays the updated parameters. 7. Gets a list of allowed engine versions by invoking the describeDbEngineVersions method. 8. Gets a list of micro instance classes available for the selected engine. 9. Creates an Amazon Relational Database Service (Amazon RDS) database instance that contains a MySQL database and uses the parameter group. 10. Waits for DB instance to be ready and prints out the connection endpoint value. 11. Creates a snapshot of the DB instance. 12. Waits for the DB snapshot to be ready. 13. Deletes the DB instance. 14. Deletes the parameter group. */ var sleepTime: Long = 20 suspend fun main(args: Array) { val usage = """ Usage: ``` -------------------------------- ### Hello AWS Glue - Ruby Source: https://docs.aws.amazon.com/code-library/latest/ug/ruby_3_glue_code_examples.md This code example demonstrates how to get started with AWS Glue using the SDK for Ruby. It includes setup instructions and is part of a larger example in the AWS Code Examples Repository. ```ruby require 'aws-sdk-glue' require 'logger' # GlueManager is a class responsible for managing AWS Glue operations # such as listing all Glue jobs in the current AWS account. class GlueManager def initialize(client) @client = client @logger = Logger.new($stdout) end ``` -------------------------------- ### DynamoDB Hello World Example (C++) Source: https://docs.aws.amazon.com/code-library/latest/ug/cpp_1_dynamodb_code_examples.md A basic C++ code example to get started with DynamoDB using the AWS SDK for C++. It demonstrates essential operations and requires setup as described in the AWS Code Examples Repository. ```cmake cmake_minimum_required(VERSION 3.10) project(hello_dynamodb) find_package(aws-sdk-cpp REQUIRED) add_executable(hello_dynamodb main.cpp) target_link_libraries(hello_dynamodb PRIVATE aws-sdk-cpp::dynamodb) ``` -------------------------------- ### MSK Tutorial Script Setup Source: https://docs.aws.amazon.com/code-library/latest/ug/bash_2_sts_code_examples.md Initializes logging and sets up the main script execution with error handling. ```bash # Project: /websites/aws_amazon # Content: # Amazon MSK Getting Started Tutorial Script - Version 8 # This script automates the steps in the Amazon MSK Getting Started tutorial # It creates an MSK cluster, sets up IAM permissions, creates a client machine, # and configures the client to interact with the cluster # Set up logging LOG_FILE="msk_tutorial_$(date +%Y%m%d_%H%M%S).log" exec > >(tee -a "$LOG_FILE") 2>&1 echo "Starting Amazon MSK Getting Started Tutorial Script - Version 8" echo "Logging to $LOG_FILE" echo "============================================== " ``` -------------------------------- ### PHP Auto Scaling Getting Started Example Setup Source: https://docs.aws.amazon.com/code-library/latest/ug/auto-scaling_example_auto-scaling_Scenario_GroupsAndInstances_section.md Initializes the AWS SDK for PHP for Auto Scaling operations. This code sets up client arguments and generates a unique ID for example resources. ```php namespace AutoScaling; use Aws\AutoScaling\AutoScalingClient; use Aws\CloudWatch\CloudWatchClient; use Aws\Ec2\Ec2Client; use AwsUtilities\AWSServiceClass; use AwsUtilities\RunnableExample; class GettingStartedWithAutoScaling implements RunnableExample { protected Ec2Client $ec2Client; protected AutoScalingClient $autoScalingClient; protected AutoScalingService $autoScalingService; protected CloudWatchClient $cloudWatchClient; protected string $templateName; protected string $autoScalingGroupName; protected array $role; public function runExample() { echo("\n"); echo("--------------------------------------\n"); print("Welcome to the Amazon EC2 Auto Scaling getting started demo using PHP!\n"); echo("--------------------------------------\n"); $clientArgs = [ 'region' => 'us-west-2', 'version' => 'latest', 'profile' => 'default', ]; $uniqid = uniqid(); ``` -------------------------------- ### Instructions for Connecting and Setting Up Client Source: https://docs.aws.amazon.com/cli/latest/userguide/bash_sts_code_examples.html Provides step-by-step instructions for connecting to the EC2 instance, uploading the setup script, running it, and sourcing the environment setup script to configure the Kafka client. ```bash # Instructions for connecting to the instance and setting up the client echo "NEXT STEPS:" echo "1. Connect to your EC2 instance:" echo " ssh -i $KEY_FILE ec2-user@$CLIENT_DNS" echo "" echo "2. Upload the setup script to your instance:" echo " scp -i $KEY_FILE setup_client.sh ec2-user@$CLIENT_DNS:~/ " echo "3. Run the setup script on your instance:" echo " ssh -i $KEY_FILE ec2-user@$CLIENT_DNS 'chmod +x ~/setup_client.sh && ~/setup_client.sh'" echo "" echo "4. Source the environment setup script:" echo " source ~/setup_env.sh" echo "" ``` -------------------------------- ### Hello Amazon SQS Source: https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/service_code_examples_basics.html A basic example to get started with Amazon SQS. This snippet typically demonstrates the initial setup and a simple interaction with the service. ```text Hello Amazon SQS ``` -------------------------------- ### MSK Tutorial Setup Script Source: https://docs.aws.amazon.com/cli/latest/userguide/bash_iam_code_examples.html This script automates the setup for the Amazon MSK Getting Started tutorial. It configures logging and includes functions for error handling and resource existence checks. ```bash # Amazon MSK Getting Started Tutorial Script - Version 8 # This script automates the steps in the Amazon MSK Getting Started tutorial # It creates an MSK cluster, sets up IAM permissions, creates a client machine, # and configures the client to interact with the cluster # Set up logging LOG_FILE="msk_tutorial_$(date +%Y%m%d_%H%M%S).log" exec > >(tee -a "$LOG_FILE") 2>&1 echo "Starting Amazon MSK Getting Started Tutorial Script - Version 8" echo "Logging to $LOG_FILE" echo "============================================== " # Function to handle errors handle_error() { echo "ERROR: $1" echo "Resources created so far:" if [ -n "$CLUSTER_ARN" ]; then echo "- MSK Cluster: $CLUSTER_ARN"; fi if [ -n "$POLICY_ARN" ]; then echo "- IAM Policy: $POLICY_ARN"; fi if [ -n "$ROLE_NAME" ]; then echo "- IAM Role: $ROLE_NAME"; fi if [ -n "$INSTANCE_PROFILE_NAME" ]; then echo "- IAM Instance Profile: $INSTANCE_PROFILE_NAME"; fi if [ -n "$CLIENT_SG_ID" ]; then echo "- Client Security Group: $CLIENT_SG_ID"; fi if [ -n "$INSTANCE_ID" ]; then echo "- EC2 Instance: $INSTANCE_ID"; fi if [ -n "$KEY_NAME" ]; then echo "- Key Pair: $KEY_NAME"; fi echo "Attempting to clean up resources..." cleanup_resources exit 1 } # Function to check if a resource exists resource_exists() { local resource_type="$1" local resource_id="$2" case "$resource_type" in "cluster") aws kafka describe-cluster --cluster-arn "$resource_id" &>/dev/null ;; "policy") aws iam get-policy --policy-arn "$resource_id" &>/dev/null ;; "role") aws iam get-role --role-name "$resource_id" &>/dev/null ;; "instance-profile") aws iam get-instance-profile --instance-profile-name "$resource_id" &>/dev/null ;; "security-group") aws ec2 describe-security-groups --group-ids "$resource_id" &>/dev/null ;; "instance") aws ec2 describe-instances --instance-ids "$resource_id" --query 'Reservations[0].Instances[0].State.Name' --output text | grep -v "terminated" &>/dev/null ;; "key-pair") aws ec2 describe-key-pairs --key-names "$resource_id" &>/dev/null ;; esac } ``` -------------------------------- ### Aurora DB Cluster Operations Setup Source: https://docs.aws.amazon.com/code-library/latest/ug/cpp_1_aurora_code_examples.md This snippet demonstrates the setup for creating an Aurora DB cluster, including parameter group creation and instance setup. It's part of a larger example for getting started with Aurora DB clusters. ```cpp Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; //! Routine which creates an Amazon Aurora DB cluster and demonstrates several operations //! on that cluster. /*! \sa gettingStartedWithDBClusters() \param clientConfiguration: AWS client configuration. \return bool: Successful completion. */ bool AwsDoc::Aurora::gettingStartedWithDBClusters( const Aws::Client::ClientConfiguration &clientConfig) { Aws::RDS::RDSClient client(clientConfig); ``` -------------------------------- ### Start Instance Source: https://docs.aws.amazon.com/cli/latest/userguide/cli_lightsail_code_examples.html This example demonstrates how to start a Lightsail instance using the `start-instance` command. ```APIDOC ## start-instance ### Description Starts a Lightsail instance. ### Method POST ### Endpoint / ### Parameters #### Query Parameters - **instance-name** (string) - Required - The name of the instance to start. ### Request Example ```bash aws lightsail start-instance --instance-name WordPress-1 ``` ### Response #### Success Response (200) Returns details about the operation to start the instance. ### Response Example ```json { "operations": [ { "id": "f88d2a93-7cea-4165-afce-2d688cb18f23", "resourceName": "WordPress-1", "resourceType": "Instance", "createdAt": 1571695583.463, "location": { "availabilityZone": "us-west-2a", "regionName": "us-west-2" }, "isTerminal": false, "operationType": "StartInstance", "status": "Started", "statusChangedAt": 1571695583.463 } ] } ``` ``` -------------------------------- ### AWS Step Functions Getting Started Tutorial Script Source: https://docs.aws.amazon.com/cli/latest/userguide/bash_sfn_code_examples.html This Bash script is designed to guide users through the AWS Step Functions Getting Started tutorial. It handles command-line arguments for auto-cleanup, sets up secure logging, verifies AWS CLI and jq installation, and configures the AWS region. ```bash #!/bin/bash # AWS Step Functions Getting Started Tutorial Script # This script creates and runs a Step Functions state machine based on the AWS Step Functions Getting Started tutorial set -euo pipefail # Security: Restrict umask to prevent unintended file permissions umask 077 # Parse command line arguments AUTO_CLEANUP=true while [[ $# -gt 0 ]]; do case $1 in --auto-cleanup) AUTO_CLEANUP=true shift ;; -h|--help) echo "Usage: $0 [--auto-cleanup] [--help]" echo " --auto-cleanup: Automatically clean up resources without prompting" echo " --help: Show this help message" exit 0 ;; *) echo "Unknown option: $1" echo "Use --help for usage information" exit 1 ;; esac done # Set up logging with secure permissions LOG_FILE="step-functions-tutorial.log" touch "$LOG_FILE" chmod 600 "$LOG_FILE" # Security: Use process substitution with explicit FD cleanup exec 3>&1 4>&2 exec > >(tee -a "$LOG_FILE") 2>&1 trap 'exec 1>&3 2>&4 3>&- 4>&-' EXIT echo "Starting AWS Step Functions Getting Started Tutorial..." echo "Logging to $LOG_FILE" # Verify AWS CLI is installed and configured if ! command -v aws &> /dev/null; then echo "ERROR: AWS CLI is not installed" exit 1 fi # Verify AWS credentials are configured if ! aws sts get-caller-identity &> /dev/null; then echo "ERROR: AWS credentials are not configured or invalid" exit 1 fi # Check if jq is available for better JSON parsing if ! command -v jq &> /dev/null; then echo "WARNING: jq is not installed. Using basic JSON parsing which may be less reliable." echo "Consider installing jq for better error handling: brew install jq (macOS) or apt-get install jq (Ubuntu)" USE_JQ=false else USE_JQ=true fi # Use fixed region that supports Amazon Comprehend CURRENT_REGION="us-west-2" echo "Using fixed AWS region: $CURRENT_REGION (supports Amazon Comprehend)" # Set AWS CLI to use the fixed region for all commands export AWS_DEFAULT_REGION="$CURRENT_REGION" export AWS_REGION="$CURRENT_REGION" # Amazon Comprehend is available in us-west-2, so we can always enable it echo "Amazon Comprehend is available in region $CURRENT_REGION" SKIP_COMPREHEND=false # Security: Initialize all resource variables STATE_MACHINE_ARN="" ROLE_NAME="" ROLE_ARN="" POLICY_ARN="" STEPFUNCTIONS_POLICY_ARN="" EXECUTION_ARN="" EXECUTION2_ARN="" EXECUTION3_ARN="" # Performance: Cache for AWS API calls to reduce redundant requests declare -A API_CACHE # Function to make cached AWS CLI calls aws_call_cached() { local cache_key="$1" shift if [[ -v API_CACHE["$cache_key"] ]]; then echo "${API_CACHE[$cache_key]}" return 0 fi local result result=$(aws "$@" 2>&1) || return $? API_CACHE["$cache_key"]="$result" echo "$result" } ``` -------------------------------- ### Next Steps for Client Setup Source: https://docs.aws.amazon.com/code-library/latest/ug/iam_example_ec2_GettingStarted_057_section.md Provides instructions for connecting to the EC2 instance via SSH, uploading the setup script, running it on the instance, and sourcing the environment setup script. ```bash echo "NEXT STEPS:" echo "1. Connect to your EC2 instance:" echo " ssh -i $KEY_FILE ec2-user@$CLIENT_DNS" echo "2. Upload the setup script to your instance:" echo " scp -i $KEY_FILE setup_client.sh ec2-user@$CLIENT_DNS:~/ echo "3. Run the setup script on your instance:" echo " ssh -i $KEY_FILE ec2-user@$CLIENT_DNS 'chmod +x ~/setup_client.sh && ~/setup_client.sh'" echo "4. Source the environment setup script:" echo " source ~/setup_env.sh" ``` -------------------------------- ### Hello Amazon S3 Control Source: https://docs.aws.amazon.com/code-library/latest/ug/java_2_s3-control_code_examples.md This example demonstrates how to get started with Amazon S3 Control by listing batch jobs asynchronously. It requires AWS SDK for Java 2.x setup and authentication configuration. ```java import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.core.retry.RetryPolicy; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3control.S3ControlAsyncClient; import software.amazon.awssdk.services.s3control.model.JobListDescriptor; import software.amazon.awssdk.services.s3control.model.JobStatus; import software.amazon.awssdk.services.s3control.model.ListJobsRequest; import software.amazon.awssdk.services.s3control.paginators.ListJobsPublisher; import java.time.Duration; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; /** * Before running this example: *

* The SDK must be able to authenticate AWS requests on your behalf. If you have not configured * authentication for SDKs and tools,see https://docs.aws.amazon.com/sdkref/latest/guide/access.html in the AWS SDKs and Tools Reference Guide. *

* You must have a runtime environment configured with the Java SDK. * See https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/setup.html in the Developer Guide if this is not set up. */ public class HelloS3Batch { private static S3ControlAsyncClient asyncClient; public static void main(String[] args) { S3BatchActions actions = new S3BatchActions(); String accountId = actions.getAccountId(); try { listBatchJobsAsync(accountId) .exceptionally(ex -> { System.err.println("List batch jobs failed: " + ex.getMessage()); return null; }) .join(); } catch (CompletionException ex) { System.err.println("Failed to list batch jobs: " + ex.getMessage()); } } /** * Retrieves the asynchronous S3 Control client instance. *

* This method creates and returns a singleton instance of the {@link S3ControlAsyncClient}. If the instance * has not been created yet, it will be initialized with the following configuration: *

    *
  • Maximum concurrency: 100
  • *
  • Connection timeout: 60 seconds
  • *
  • Read timeout: 60 seconds
  • *
  • Write timeout: 60 seconds
  • *
  • API call timeout: 2 minutes
  • *
  • API call attempt timeout: 90 seconds
  • *
  • Retry policy: 3 retries
  • *
  • Region: US_EAST_1
  • *
  • Credentials provider: {@link EnvironmentVariableCredentialsProvider}
  • *
* * @return the asynchronous S3 Control client instance */ private static S3ControlAsyncClient getAsyncClient() { if (asyncClient == null) { SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder() .maxConcurrency(100) .connectionTimeout(Duration.ofSeconds(60)) .readTimeout(Duration.ofSeconds(60)) .writeTimeout(Duration.ofSeconds(60)) .build(); ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder() .apiCallTimeout(Duration.ofMinutes(2)) .apiCallAttemptTimeout(Duration.ofSeconds(90)) .retryStrategy(RetryMode.STANDARD) .build(); ``` -------------------------------- ### MediaConnect Getting Started Tutorial Script Source: https://docs.aws.amazon.com/cli/latest/userguide/bash_mediaconnect_code_examples.html This Bash script demonstrates a complete MediaConnect tutorial. It creates a flow, adds an output, grants an entitlement, and cleans up resources. It includes setup for logging and error handling. ```bash #!/bin/bash # AWS Elemental MediaConnect Getting Started Tutorial Script # This script creates a MediaConnect flow, adds an output, grants an entitlement, # and then cleans up the resources. set -euo pipefail # Security: Restrict umask to prevent world-readable files umask 0077 # Set up logging with restricted permissions LOG_FILE="mediaconnect-tutorial.log" touch "$LOG_FILE" chmod 600 "$LOG_FILE" exec > >(tee -a "$LOG_FILE") 2>&1 echo "Starting AWS Elemental MediaConnect tutorial script at $(date)" echo "All commands and outputs will be logged to $LOG_FILE" # Tags for all resources TAGS_ARRAY=("Key=project,Value=doc-smith" "Key=tutorial,Value=aws-elemental-mediaconnect-gs") # Function to handle errors handle_error() { echo "ERROR: $1" >&2 echo "Attempting to clean up resources..." cleanup_resources exit 1 } # Function to validate AWS CLI is available validate_aws_cli() { if ! command -v aws &> /dev/null; then handle_error "AWS CLI is not installed or not in PATH" fi # Security: Verify AWS CLI version is recent local aws_version aws_version=$(aws --version 2>&1 | head -1) echo "AWS CLI version: $aws_version" if ! aws sts get-caller-identity &> /dev/null; then handle_error "AWS credentials are not configured or invalid" fi # Security: Validate caller identity local account_id account_id=$(aws sts get-caller-identity --query Account --output text 2>/dev/null) if [ -z "$account_id" ]; then handle_error "Failed to retrieve AWS account ID" fi echo "AWS Account ID: $account_id" } # Function to safely extract JSON values using jq (preferred) or fallback extract_json_value() { local json_output="$1" local key="$2" if [ -z "$json_output" ]; then return 1 fi # Security: Use jq if available for safer JSON parsing if command -v jq &> /dev/null; then echo "$json_output" | jq -r ".${key} // empty" 2>/dev/null || return 1 else # Fallback with additional validation if ! echo "$json_output" | grep -q "\"$key\"="; then return 1 fi echo "$json_output" | grep -o "\"$key\": \"[^\"]*" | head -1 | cut -d'"' -f4 fi } # Function to tag MediaConnect resource tag_mediaconnect_resource() { local resource_arn="$1" echo "Tagging resource: $resource_arn" for tag in "${TAGS_ARRAY[@]}"; do if ! aws mediaconnect tag-resource --resource-arn "$resource_arn" --tags "$tag" 2>&1; then echo "WARNING: Failed to apply tag $tag to resource" fi done } ``` -------------------------------- ### Get Started with Systems Manager using JavaScript v3 Source: https://docs.aws.amazon.com/code-library/latest/ug/javascript_3_ssm_code_examples.md Initializes the SSMClient and lists up to 5 documents, demonstrating basic interaction with Systems Manager. Requires setup instructions from the AWS Code Examples Repository. ```javascript import { paginateListDocuments, SSMClient } from "@aws-sdk/client-ssm"; // Call ListDocuments and display the result. export const main = async () => { const client = new SSMClient(); const listDocumentsPaginated = []; console.log( "Hello, AWS Systems Manager! Let's list some of your documents:\n", ); try { // The paginate function is a wrapper around the base command. const paginator = paginateListDocuments({ client }, { MaxResults: 5 }); for await (const page of paginator) { listDocumentsPaginated.push(...page.DocumentIdentifiers); } } catch (caught) { console.error(`There was a problem saying hello: ${caught.message}`); throw caught; } for (const { Name, DocumentFormat, CreatedDate } of listDocumentsPaginated) { console.log(`${Name} - ${DocumentFormat} - ${CreatedDate}`); } }; // Call function if run directly. import { fileURLToPath } from "node:url"; if (process.argv[1] === fileURLToPath(import.meta.url)) { main(); } ``` -------------------------------- ### S3 Getting Started Bash Script Source: https://docs.aws.amazon.com/cli/latest/userguide/bash_s3_code_examples.html This script demonstrates S3 Getting Started operations including creating a bucket, uploading/downloading objects, copying to a prefix, enabling versioning, configuring encryption and public access blocking, tagging the bucket, listing objects and versions, and cleaning up resources. It includes prerequisite checks for AWS credentials and region configuration. ```bash #!/bin/bash # S3 Getting Started - Create a bucket, upload and download objects, copy to a # folder prefix, enable versioning, configure encryption and public access # blocking, tag the bucket, list objects and versions, and clean up. set -eE set -o pipefail # ============================================================================ # Prerequisites check # ============================================================================ CONFIGURED_REGION=$(aws configure get region 2>/dev/null || true) if [ -z "$CONFIGURED_REGION" ] && [ -z "$AWS_DEFAULT_REGION" ] && [ -z "$AWS_REGION" ]; then echo "ERROR: No AWS region configured. Run 'aws configure' or set AWS_DEFAULT_REGION." exit 1 fi # Verify AWS credentials are configured if ! aws sts get-caller-identity &>/dev/null; then echo "ERROR: AWS credentials not configured or invalid. Run 'aws configure'." exit 1 fi # ============================================================================ # Setup: logging, temp directory, resource tracking # ============================================================================ UNIQUE_ID=$(head -c 6 /dev/urandom | od -An -tx1 | tr -d ' ') # Check for shared prereq bucket PREREQ_BUCKET=$(aws cloudformation describe-stacks --stack-name tutorial-prereqs-bucket --query 'Stacks[0].Outputs[?OutputKey==`BucketName`].OutputValue' --output text 2>/dev/null || true) if [ -n "$PREREQ_BUCKET" ] && [ "$PREREQ_BUCKET" != "None" ]; then BUCKET_NAME="$PREREQ_BUCKET" BUCKET_IS_SHARED=true echo "Using shared bucket: $BUCKET_NAME" else BUCKET_IS_SHARED=false BUCKET_NAME="s3api-${UNIQUE_ID}" fi TEMP_DIR=$(mktemp -d) trap 'rm -rf "$TEMP_DIR"' EXIT LOG_FILE="${TEMP_DIR}/s3-gettingstarted.log" CREATED_RESOURCES=() exec > >(tee -a "$LOG_FILE") 2>&1 echo "============================================" echo "S3 Getting Started" echo "============================================" echo "Bucket name: ${BUCKET_NAME}" echo "Temp directory: ${TEMP_DIR}" echo "Log file: ${LOG_FILE}" echo "" # ============================================================================ # Helper functions # ============================================================================ get_region() { echo "${AWS_REGION:-${AWS_DEFAULT_REGION:-${CONFIGURED_REGION}}}" } ``` -------------------------------- ### Display Tutorial Completion Summary Source: https://docs.aws.amazon.com/IAM/latest/UserGuide/iam_example_iam_GettingStarted_028_section.html Prints a summary of the resources created and next steps after a successful tutorial execution. This provides a confirmation of the setup and guidance for further actions. ```bash # Display summary of created resources echo "" echo "===========================================" echo "TUTORIAL COMPLETED SUCCESSFULLY!" echo "===========================================" echo "Resources created:" echo "- S3 Bucket: $S3_BUCKET_NAME" echo "- Customers Feature Group: $CUSTOMERS_FEATURE_GROUP_NAME" echo "- Orders Feature Group: $ORDERS_FEATURE_GROUP_NAME" if [[ " ${CREATED_RESOURCES[@]} " =~ " IAMRole:" ]]; then echo "- IAM Role: $(echo "${CREATED_RESOURCES[@]}" | grep -o 'IAMRole:[^[:space:]]*' | cut -d: -f2)" fi echo "" echo "You can now:" echo "1. View your feature groups in the SageMaker console" echo "2. Query the offline store using Amazon Athena" echo "3. Use the feature groups in your ML workflows" echo "===========================================" echo "" ``` -------------------------------- ### Getting started with user pools Source: https://docs.aws.amazon.com/code-library/latest/ug/cognito-identity-provider_code_examples.md A basic example demonstrating the core steps to get started with Amazon Cognito user pools, including sign-up and sign-in. ```javascript // This is a placeholder for a more comprehensive 'Getting Started' example. // Actual code would involve multiple steps like: // 1. Creating a User Pool // 2. Creating a User Pool Client // 3. Using SignUpCommand and InitiateAuthCommand console.log('Getting started with Cognito User Pools...'); // Example: Sign up a user // const signUpResponse = await cognitoClient.send(new SignUpCommand({...})); // Example: Initiate authentication // const authResponse = await cognitoClient.send(new InitiateAuthCommand({...})); ``` -------------------------------- ### Main Entry Point for EC2 Example Source: https://docs.aws.amazon.com/code-library/latest/ug/ec2_example_ec2_Hello_section.md Sets up the main entry point for the command-line application. It parses arguments and executes the example command. ```swift /// The program's asynchronous entry point. @main struct Main { static func main() async { let args = Array(CommandLine.arguments.dropFirst()) do { let command = try ExampleCommand.parse(args) try await command.runAsync() } catch { ExampleCommand.exit(withError: error) } } } ``` -------------------------------- ### Install the CLI Source: https://docs.aws.amazon.com/sagemaker-unified-studio/latest/userguide/cicd-getting-started.html Install the CLI using pip. ```bash pip install aws-smus-cicd-cli ``` -------------------------------- ### Run ECR Getting Started Scenario Source: https://docs.aws.amazon.com/code-library/latest/ug/python_3_ecr_code_examples.md Executes the ECR getting started scenario, which includes creating a repository and potentially other ECR operations. Requires Docker to be installed and running. ```python if __name__ == "__main__": parser = argparse.ArgumentParser( description="Run Amazon ECR getting started scenario." ) parser.add_argument( "--iam-role-arn", type=str, default=None, help="an optional IAM role ARN that will be granted access to download images from a repository.", required=False, ) parser.add_argument( "--no-art", action="store_true", help="accessibility setting that suppresses art in the console output.", ) args = parser.parse_args() no_art = args.no_art iam_role_arn = args.iam_role_arn demo = None a_docker_client = None try: a_docker_client = docker.from_env() if not a_docker_client.ping(): raise docker.errors.DockerException("Docker is not running.") except docker.errors.DockerException as err: logging.error( """ The Python Docker client could not be created. Do you have Docker installed and running? Here is the error message: %s """, err, ) sys.exit("Error with Docker.") try: an_ecr_wrapper = ECRWrapper.from_client() demo = ECRGettingStarted(an_ecr_wrapper, a_docker_client) demo.run(iam_role_arn) except Exception as exception: logging.exception("Something went wrong with the demo!") if demo is not None: demo.cleanup(False) ``` -------------------------------- ### Get Started with SageMaker AI Source: https://docs.aws.amazon.com/code-library/latest/ug/javascript_3_sagemaker_code_examples.md This example demonstrates how to get started with SageMaker AI by listing notebook instances. It requires the SageMakerClient and ListNotebookInstancesCommand from the AWS SDK for JavaScript (v3). ```javascript import { SageMakerClient, ListNotebookInstancesCommand, } from "@aws-sdk/client-sagemaker"; const client = new SageMakerClient({ region: "us-west-2", }); export const helloSagemaker = async () => { const command = new ListNotebookInstancesCommand({ MaxResults: 5 }); const response = await client.send(command); console.log( "Hello Amazon SageMaker! Let's list some of your notebook instances:" ); const instances = response.NotebookInstances || []; if (instances.length === 0) { console.log( "• No notebook instances found. Try creating one in the AWS Management Console or with the CreateNotebookInstanceCommand." ); } else { console.log( instances .map( (i) => `• Instance: ${i.NotebookInstanceName}\n Arn:${ i.NotebookInstanceArn } Creation Date: ${i.CreationTime.toISOString()}` ) .join("\n") ); } return response; }; ``` -------------------------------- ### Initialize Logging and Setup Source: https://docs.aws.amazon.com/code-library/latest/ug/bash_2_vpc-lattice_code_examples.md Sets up a log file with secure permissions and logs the start of the script. This is a foundational step for any script that requires logging. ```bash LOG_FILE="vpc-lattice-tutorial.log" touch "$LOG_FILE" chmod 600 "$LOG_FILE" echo "Starting VPC Lattice tutorial script at $(date)" > "$LOG_FILE" ``` -------------------------------- ### Get Started with Amazon Cognito Identity Provider Source: https://docs.aws.amazon.com/code-library/latest/ug/javascript_3_cognito-identity-provider_code_examples.md This example demonstrates how to get started with Amazon Cognito by listing user pools. It uses the `paginateListUserPools` function and requires the `CognitoIdentityProviderClient`. ```javascript import { paginateListUserPools, CognitoIdentityProviderClient, } from "@aws-sdk/client-cognito-identity-provider"; const client = new CognitoIdentityProviderClient({}); export const helloCognito = async () => { const paginator = paginateListUserPools({ client }, {}); const userPoolNames = []; for await (const page of paginator) { const names = page.UserPools.map((pool) => pool.Name); userPoolNames.push(...names); } console.log("User pool names: "); console.log(userPoolNames.join("\n")); return userPoolNames; }; ``` -------------------------------- ### Get Started with Dedicated Network Connections Source: https://docs.aws.amazon.com/code-library/latest/ug/ec2_code_examples.md Example for setting up dedicated network connections using AWS Direct Connect. ```bash aws directconnect allocate-public-virtual-interface --connection-id dxcon-abcdef123456789 --public-prefix-time 2001:db8:1234:5678::/64 --amazon-address 192.168.1.1/30 ``` -------------------------------- ### Verify the installation Source: https://docs.aws.amazon.com/sagemaker-unified-studio/latest/userguide/cicd-getting-started.html Verify the CLI installation by checking its version. ```bash aws-smus-cicd-cli --version ``` -------------------------------- ### AWS CLI Bash Script for ECR Getting Started Source: https://docs.aws.amazon.com/code-library/latest/ug/ecr_example_ecr_GettingStarted_078_section.md This script demonstrates the lifecycle of a Docker image in Amazon ECR, including creation, repository setup, authentication, push, pull, and cleanup. Ensure the AWS CLI is installed before running. ```bash #!/bin/bash # Amazon ECR Getting Started Script # This script demonstrates the lifecycle of a Docker image in Amazon ECR # Set up logging LOG_FILE="ecr-tutorial.log" exec > >(tee -a "$LOG_FILE") 2>&1 echo "===================================================" echo "Amazon ECR Getting Started Tutorial" echo "===================================================" echo "This script will:" echo "1. Create a Docker image" echo "2. Create an Amazon ECR repository" echo "3. Authenticate to Amazon ECR" echo "4. Push the image to Amazon ECR" echo "5. Pull the image from Amazon ECR" echo "6. Clean up resources (optional)" echo "===================================================" # Check prerequisites echo "Checking prerequisites..." # Check if AWS CLI is installed if ! command -v aws &> /dev/null; then echo "ERROR: AWS CLI is not installed. Please install it before running this script." echo "Visit https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html for installation instructions." exit 1 fi ```