### Amazon Textract Getting Started Script Setup Source: https://docs.aws.amazon.com/cli/latest/userguide/bash_s3_code_examples This Bash script initializes setup for the Amazon Textract Getting Started tutorial. It configures logging with restricted permissions. ```bash #!/bin/bash # Amazon Textract Getting Started Tutorial Script # This script demonstrates how to use Amazon Textract to analyze document text set -euo pipefail # Set up logging with restricted permissions LOG_FILE="textract-tutorial.log" touch "$LOG_FILE" chmod 600 "$LOG_FILE" exec > >(tee -a "$LOG_FILE") 2>&1 ``` -------------------------------- ### Create Project Directory and Navigate Source: https://docs.aws.amazon.com/amazon-mq/latest/developer-guide/amazon-mq-rabbitmq-pika Create a new directory for your project and navigate into it. This is the initial setup step for the tutorial. ```bash $ mkdir pika-tutorial $ cd pika-tutorial ``` -------------------------------- ### Getting started with user pools Source: https://docs.aws.amazon.com/cognito/latest/developerguide/service_code_examples_cognito-identity-provider This example provides a basic setup for getting started with Amazon Cognito User Pools. It includes creating a user pool and an app client. ```javascript // This is a conceptual example and requires specific AWS SDK calls for actual creation. // Refer to CreateUserPool and CreateUserPoolClient examples for implementation details. console.log("Getting started with Amazon Cognito User Pools:"); console.log("1. Create a User Pool using the CreateUserPool API."); console.log("2. Create an App Client for your User Pool using the CreateUserPoolClient API."); console.log("3. Configure your application to use the User Pool ID and App Client ID for sign-up and sign-in."); console.log("4. Implement user confirmation and password reset flows as needed."); ``` -------------------------------- ### EMR Getting Started Tutorial Bash Script Source: https://docs.aws.amazon.com/cli/latest/userguide/bash_s3_code_examples This script automates the steps in the Amazon EMR Getting Started tutorial. It handles cluster creation, S3 bucket setup with security best practices, and resource cleanup. It requires AWS CLI to be installed and configured. ```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 # Block public access to bucket aws s3api put-public-access-block --bucket "$BUCKET_NAME" \ --public-access-block-configuration \ "BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true" || true # Enable encryption on bucket aws s3api put-bucket-encryption --bucket "$BUCKET_NAME" \ --server-side-encryption-configuration '{ \ "Rules": [{ \ "ApplyServerSideEncryptionByDefault": { \ "SSEAlgorithm": "AES256" \ } \ }] \ }' || true echo "S3 bucket created successfully with security best practices." # Create PySpark script echo "Creating PySpark script: health_violations.py" cat > health_violations.py << 'EOL' import argparse from pyspark.sql import SparkSession ``` -------------------------------- ### Install and Run Sample App Source: https://docs.aws.amazon.com/iot/latest/developerguide/connecting-to-existing-device Navigate to the sample app directory and install dependencies. Then, run the app with your IoT endpoint and certificate details. ```bash cd ~/aws-iot-device-sdk-js-v2/samples/node/pub_sub npm install ``` ```bash node dist/index.js --topic topic_1 --ca_file ~/certs/Amazon-root-CA-1.pem --cert ~/certs/device.pem.crt --key ~/certs/private.pem.key --endpoint {{your-iot-endpoint}} ``` -------------------------------- ### Example setup-export.sh command Source: https://docs.aws.amazon.com/keyspaces/latest/devguide/S3-tutorial-step2 An example command demonstrating how to run the `setup-export.sh` script with placeholder values for the required parameters. ```shell setup-export.sh {{cfn-setup}} {{cfn-glue}} {{catalog}} {{book_awards}} ``` -------------------------------- ### Start and Get Content Moderation Detection in Video Source: https://docs.aws.amazon.com/code-library/latest/ug/java_2_rekognition_code_examples Starts content moderation detection for a video stored in an S3 bucket and retrieves the results. This example requires AWS SDK for Java and Amazon Rekognition setup. ```java String bucket = args[0]; String video = args[1]; String topicArn = args[2]; String roleArn = args[3]; Region region = Region.US_EAST_1; RekognitionClient rekClient = RekognitionClient.builder() .region(region) .build(); NotificationChannel channel = NotificationChannel.builder() .snsTopicArn(topicArn) .roleArn(roleArn) .build(); startModerationDetection(rekClient, channel, bucket, video); getModResults(rekClient); System.out.println("This example is done!"); rekClient.close(); } public static void startModerationDetection(RekognitionClient rekClient, NotificationChannel channel, String bucket, String video) { try { S3Object s3Obj = S3Object.builder() .bucket(bucket) .name(video) .build(); Video vidOb = Video.builder() .s3Object(s3Obj) .build(); StartContentModerationRequest modDetectionRequest = StartContentModerationRequest.builder() .jobTag("Moderation") .notificationChannel(channel) .video(vidOb) .build(); StartContentModerationResponse startModDetectionResult = rekClient .startContentModeration(modDetectionRequest); startJobId = startModDetectionResult.jobId(); } catch (RekognitionException e) { System.out.println(e.getMessage()); System.exit(1); } } public static void getModResults(RekognitionClient rekClient) { try { String paginationToken = null; GetContentModerationResponse modDetectionResponse = null; boolean finished = false; String status; int yy = 0; do { if (modDetectionResponse != null) paginationToken = modDetectionResponse.nextToken(); GetContentModerationRequest modRequest = GetContentModerationRequest.builder() .jobId(startJobId) .nextToken(paginationToken) .maxResults(10) .build(); // Wait until the job succeeds. while (!finished) { modDetectionResponse = rekClient.getContentModeration(modRequest); status = modDetectionResponse.jobStatusAsString(); if (status.compareTo("SUCCEEDED") == 0) finished = true; else { System.out.println(yy + " status is: " + status); Thread.sleep(1000); } yy++; } finished = false; // Proceed when the job is done - otherwise VideoMetadata is null. VideoMetadata videoMetaData = modDetectionResponse.videoMetadata(); System.out.println("Format: " + videoMetaData.format()); System.out.println("Codec: " + videoMetaData.codec()); System.out.println("Duration: " + videoMetaData.durationMillis()); System.out.println("FrameRate: " + videoMetaData.frameRate()); System.out.println("Job"); List mods = modDetectionResponse.moderationLabels(); for (ContentModerationDetection mod : mods) { long seconds = mod.timestamp() / 1000; System.out.print("Mod label: " + seconds + " "); System.out.println(mod.moderationLabel().toString()); System.out.println(); } } while (modDetectionResponse != null && modDetectionResponse.nextToken() != null); } catch (RekognitionException | InterruptedException e) { System.out.println(e.getMessage()); System.exit(1); } } } ``` -------------------------------- ### Example Installer Filename Source: https://docs.aws.amazon.com/elemental-cl3/latest/upgradeguide/upg-red-copy-ins Note the name of the downloaded software file. ```text elemental_production_conductor_live247_3.25.5.12345.run ``` -------------------------------- ### Install and Run Sample Pub-Sub App Source: https://docs.aws.amazon.com/iot/latest/developerguide/creating-a-virtual-thing Navigate to the sample app directory, install its dependencies, and then run the application. ```bash cd ~/aws-iot-device-sdk-js-v2/samples/node/pub_sub npm install ``` -------------------------------- ### Get Started with EC2 Instances using Bash Source: https://docs.aws.amazon.com/cli/latest/userguide/bash_ec2_code_examples This function runs an interactive scenario to guide users through getting started with EC2 instances. It requires EC2 access permissions and Bash version 4.0 or higher. The script handles key pair creation, security group setup, and instance management. ```bash ############################################################################### # function get_started_with_ec2_instances # # Runs an interactive scenario that shows how to get started using EC2 instances. # # "EC2 access" permissions are needed to run this code. # # Returns: # 0 - If successful. # 1 - If an error occurred. ############################################################################### function get_started_with_ec2_instances() { # Requires version 4 for mapfile. local required_version=4.0 # Get the current Bash version # Check if BASH_VERSION is set local current_version if [[ -n "$BASH_VERSION" ]]; then # Convert BASH_VERSION to a number for comparison current_version=$BASH_VERSION else # Get the current Bash version using the bash command current_version=$(bash --version | head -n 1 | awk '{ print $4 }') fi # Convert version strings to numbers for comparison local required_version_num current_version_num required_version_num=$(echo "$required_version" | awk -F. '{ print ($1 * 10000) + ($2 * 100) + $3 }') current_version_num=$(echo "$current_version" | awk -F. '{ print ($1 * 10000) + ($2 * 100) + $3 }') # Compare versions if ((current_version_num < required_version_num)); then echo "Error: This script requires Bash version $required_version or higher." echo "Your current Bash version is number is $current_version." exit 1 fi { if [ "$EC2_OPERATIONS_SOURCED" != "True" ]; then source ./ec2_operations.sh fi } echo_repeat "*" 88 echo "Welcome to the Amazon Elastic Compute Cloud (Amazon EC2) get started with instances demo." echo_repeat "*" 88 echo echo "Let's create an RSA key pair that you can be use to securely connect to " echo "your EC2 instance." echo -n "Enter a unique name for your key: " get_input local key_name key_name=$get_input_result local temp_dir temp_dir=$(mktemp -d) local key_file_name="$temp_dir/${key_name}.pem" if ec2_create_keypair -n "${key_name}" -f "${key_file_name}"; then echo "Created a key pair $key_name and saved the private key to $key_file_name" echo else errecho "The key pair failed to create. This demo will exit." return 1 fi chmod 400 "${key_file_name}" if yes_no_input "Do you want to list some of your key pairs? (y/n) "; then local keys_and_fingerprints keys_and_fingerprints="$(ec2_describe_key_pairs)" && { local image_name_and_id while IFS=$'\n' read -r image_name_and_id; do local entries IFS=$'\t' read -ra entries <<<"$image_name_and_id" echo "Found rsa key ${entries[0]} with fingerprint:" echo " ${entries[1]}" done <<<"$keys_and_fingerprints" } fi echo_repeat "*" 88 echo_repeat "*" 88 echo "Let's create a security group to manage access to your instance." echo -n "Enter a unique name for your security group: " get_input local security_group_name security_group_name=$get_input_result local security_group_id security_group_id=$(ec2_create_security_group -n "$security_group_name" \ -d "Security group for EC2 instance") || { errecho "The security failed to create. This demo will exit." clean_up "$key_name" "$key_file_name" return 1 } ``` -------------------------------- ### Create Client Machine Setup Source: https://docs.aws.amazon.com/code-library/latest/ug/bash_2_ec2_code_examples Prepares resources for a client machine, including finding subnets, verifying VPCs, and creating security groups. ```bash # Step 3: Create a client machine echo "Step 3: Creating client machine" # Find a suitable subnet and instance type combination if ! find_suitable_subnet_and_instance_type "$DEFAULT_VPC_ID" SUBNET_ARRAY[@]; then handle_error "Could not find a suitable subnet and instance type combination" fi echo "Selected subnet: $SELECTED_SUBNET_ID" echo "Selected instance type: $SELECTED_INSTANCE_TYPE" # Verify the subnet is in the same VPC we're using SUBNET_VPC_ID=$(aws ec2 describe-subnets \ --subnet-ids "$SELECTED_SUBNET_ID" \ --query 'Subnets[0].VpcId' \ --output text) if [ "$SUBNET_VPC_ID" != "$DEFAULT_VPC_ID" ]; then handle_error "Subnet VPC ($SUBNET_VPC_ID) does not match default VPC ($DEFAULT_VPC_ID)" fi echo "VPC ID: $SUBNET_VPC_ID" ``` -------------------------------- ### Bash Script for AWS Direct Connect Getting Started Source: https://docs.aws.amazon.com/code-library/latest/ug/direct-connect_example_directconnect_GettingStarted_051_section This script automates the setup of an AWS Direct Connect connection. It requires the AWS CLI to be installed and configured. Ensure you have the necessary permissions. ```bash # Extract the first location code for demonstration purposes LOCATION_CODE=$(aws directconnect describe-locations --query 'locations[0].locationCode' --output text) if [ -z "$LOCATION_CODE" ] || [ "$LOCATION_CODE" == "None" ]; then echo "Error: Could not extract location code from the output." exit 1 fi echo "Using location: $LOCATION_CODE" # Step 2: Create a dedicated connection echo "Creating a dedicated connection at location $LOCATION_CODE with bandwidth 1Gbps..." CONNECTION_OUTPUT=$(aws directconnect create-connection \ --location "$LOCATION_CODE" \ --bandwidth "1Gbps" \ --connection-name "$CONNECTION_NAME" \ --tags key=project,value=doc-smith key=tutorial,value=aws-direct-connect-gs) check_error "$CONNECTION_OUTPUT" "create-connection" echo "$CONNECTION_OUTPUT" # Extract connection ID directly from the output CONNECTION_ID=$(echo "$CONNECTION_OUTPUT" | grep -o '"connectionId": "[^"']*' | cut -d'"' -f4) if [ -z "$CONNECTION_ID" ]; then echo "Error: Could not extract connection ID from the output." exit 1 fi echo "Connection created with ID: $CONNECTION_ID" # Step 3: Describe the connection echo "Retrieving connection details..." DESCRIBE_OUTPUT=$(aws directconnect describe-connections --connection-id "$CONNECTION_ID") check_error "$DESCRIBE_OUTPUT" "describe-connections" echo "$DESCRIBE_OUTPUT" # Step 4: Update the connection name NEW_CONNECTION_NAME="${CONNECTION_NAME}-updated" echo "Updating connection name to $NEW_CONNECTION_NAME..." UPDATE_OUTPUT=$(aws directconnect update-connection \ --connection-id "$CONNECTION_ID" \ --connection-name "$NEW_CONNECTION_NAME") check_error "$UPDATE_OUTPUT" "update-connection" echo "$UPDATE_OUTPUT" # Step 5: Check if we can download the LOA-CFA # Note: In a real scenario, the LOA-CFA might not be immediately available echo "Attempting to download the LOA-CFA (this may not be available yet)..." LOA_OUTPUT=$(aws directconnect describe-loa --connection-id "$CONNECTION_ID" 2>&1) if echo "$LOA_OUTPUT" | grep -i "error" > /dev/null; then echo "LOA-CFA not available yet. This is expected for newly created connections." echo "The LOA-CFA will be available once AWS begins provisioning your connection." else LOA_CONTENT=$(echo "$LOA_OUTPUT" | grep -o '"loaContent": "[^"']*' | cut -d'"' -f4) echo "$LOA_CONTENT" | base64 --decode > "loa-cfa-${CONNECTION_ID}.pdf" echo "LOA-CFA downloaded to loa-cfa-${CONNECTION_ID}.pdf" fi # Step 6: Create a virtual private gateway (required for private virtual interface) echo "Creating a virtual private gateway..." VGW_OUTPUT=$(aws ec2 create-vpn-gateway --type ipsec.1 \ --tag-specifications 'ResourceType=vpn-gateway,Tags=[{Key=project,Value=doc-smith},{Key=tutorial,Value=aws-direct-connect-gs}]') check_error "$VGW_OUTPUT" "create-vpn-gateway" echo "$VGW_OUTPUT" # Extract VGW ID directly from the output VGW_ID=$(echo "$VGW_OUTPUT" | grep -o '"VpnGatewayId": "[^"']*' | cut -d'"' -f4) if [ -z "$VGW_ID" ]; then echo "Error: Could not extract VPN gateway ID from the output." exit 1 fi echo "Virtual private gateway created with ID: $VGW_ID" # Wait for VGW to become available if ! wait_for_vgw "$VGW_ID"; then echo "Failed to wait for VGW to become available. Skipping virtual interface creation." VIF_CREATION_SKIPPED=true else VIF_CREATION_SKIPPED=false fi # Step 7: Create a private virtual interface (only if VGW is available) if [ "$VIF_CREATION_SKIPPED" = false ]; then echo "Creating a private virtual interface..." PRIVATE_VIF_OUTPUT=$(aws directconnect create-private-virtual-interface \ --connection-id "$CONNECTION_ID" \ --new-private-virtual-interface '{ "virtualInterfaceName": "PrivateVIF-' ``` -------------------------------- ### Bash Script for Amazon Textract Getting Started Source: https://docs.aws.amazon.com/code-library/latest/ug/bash_2_s3_code_examples This script guides through using Amazon Textract to analyze document text. It includes error handling, AWS CLI verification, and S3 bucket setup. ```bash echo "===================================================" echo "Amazon Textract Getting Started Tutorial"echo "===================================================" echo "This script will guide you through using Amazon Textract to analyze document text." echo "" # Function to check for errors in command output and exit code check_error() { local exit_code=$1 local output=$2 local cmd=$3 if [ $exit_code -ne 0 ] || echo "$output" | grep -i "error" > /dev/null; then echo "ERROR: Command failed: $cmd" echo "$output" | sed 's/\(aws_secret_access_key\|Authorization\|X-Amz-Security-Token\).*/\1=***REDACTED***/g' cleanup_on_error exit 1 fi } # Function to clean up resources on error cleanup_on_error() { echo "Error encountered. Cleaning up resources..." # Clean up temporary JSON files if [ -f "document.json" ]; then rm -f document.json fi if [ -f "features.json" ]; then rm -f features.json fi if [ -n "${DOCUMENT_NAME:-}" ] && [ -n "${BUCKET_NAME:-}" ]; then echo "Deleting document from S3..." aws s3 rm "s3://${BUCKET_NAME}/${DOCUMENT_NAME}" || echo "Failed to delete document" fi if [ -n "${BUCKET_NAME:-}" ] && [ "${BUCKET_IS_SHARED:-false}" = "false" ]; then echo "Deleting S3 bucket..." aws s3 rb "s3://${BUCKET_NAME}" --force || echo "Failed to delete bucket" fi } # Set up trap for cleanup on exit trap cleanup_on_error EXIT # Verify AWS CLI is installed and configured echo "Verifying AWS CLI configuration..." if ! command -v aws &> /dev/null; then echo "ERROR: AWS CLI is not installed." exit 1 fi AWS_CONFIG_OUTPUT=$(aws configure list 2>&1) AWS_CONFIG_STATUS=$? if [ $AWS_CONFIG_STATUS -ne 0 ]; then echo "ERROR: AWS CLI is not properly configured." echo "$AWS_CONFIG_OUTPUT" | sed 's/\(aws_secret_access_key\|Authorization\).*/\1=***REDACTED***/g' exit 1 fi # Verify AWS region is configured and supports Textract AWS_REGION=$(aws configure get region) if [ -z "$AWS_REGION" ]; then echo "ERROR: No AWS region configured. Please run 'aws configure' to set a default region." exit 1 fi # Check if Textract is available in the configured region echo "Checking if Amazon Textract is available in region $AWS_REGION..." TEXTRACT_CHECK=$(aws textract help 2>&1) TEXTRACT_CHECK_STATUS=$? if [ $TEXTRACT_CHECK_STATUS -ne 0 ]; then echo "ERROR: Amazon Textract may not be available in region $AWS_REGION." exit 1 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 || echo "") 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="textract-${RANDOM_ID}" fi DOCUMENT_NAME="document.png" RESOURCES_CREATED=() # Step 1: Create S3 bucket if [ "$BUCKET_IS_SHARED" = false ]; then echo "Creating S3 bucket: $BUCKET_NAME" CREATE_BUCKET_OUTPUT=$(aws s3 mb "s3://$BUCKET_NAME" --region "$AWS_REGION" 2>&1) CREATE_BUCKET_STATUS=$? echo "$CREATE_BUCKET_OUTPUT" check_error $CREATE_BUCKET_STATUS "$CREATE_BUCKET_OUTPUT" "aws s3 mb s3://$BUCKET_NAME" aws s3api put-bucket-tagging \ --bucket "$BUCKET_NAME" \ --tagging 'TagSet=[{Key=project,Value=doc-smith},{Key=tutorial,Value=amazon-textract-gs}]' # Apply security settings to bucket aws s3api put-bucket-versioning --bucket "$BUCKET_NAME" --versioning-configuration Status=Enabled 2>&1 || true aws s3api put-bucket-encryption --bucket "$BUCKET_NAME" --server-side-encryption-configuration '{"Rules": [{"ApplyServerSideEncryptionByDefault": {"SSEAlgorithm": "AES256"}}]}' 2>&1 || true aws s3api put-bucket-acl --bucket "$BUCKET_NAME" --acl private 2>&1 || true RESOURCES_CREATED+=("S3 Bucket: $BUCKET_NAME") fi ``` -------------------------------- ### Example vCenter Configuration Setup Source: https://docs.aws.amazon.com/migrationhub-orchestrator/latest/userguide/configure-plugin This example demonstrates the interactive prompts and expected responses for setting up vCenter configurations, including credentials for vCenter, Windows, and Linux servers, and options for servers outside of vCenter. ```bash Start setting up vCenter configurations for remote execution Note: authenticating using VMware vCenter credentials requires VMware tools to be installed on the target servers Would you like to authenticate using VMware vCenter credentials? [Y/N]: Y Host Url for VMware vCenter: {{host-url}} Username for VMware vCenter: {{username}} Password for VMware vCenter: Successfully stored vCenter credentials... Setup for Windows using VMware vCenter? [Y/N]: Y Username for Windows: {{username}} Password for Windows: Successfully stored vCenter windows credentials... Setup for Linux using VMware vCenter? [Y/N]: Y Username for Linux: {{username}} Password for Linux: Successfully stored vCenter linux credentials... Would you like to setup credentials for servers outside vCenter using NTLM for windows and SSH/Cert based for linux? [Y/N]: Y Would you like to use the same Windows credentials used during vCenter setup? [Y/N]: Y Are you okay with plugin accepting and locally storing server certificates on your behalf during first interaction with windows servers? These certificates will be used by plugin for secure communication with windows servers [Y/N]:Y Successfully stored windows server credentials... Please note that all windows server certificates are stored in directory /opt/amazon/mhub-orchestrator-plugin/remote-auth/windows/certs Please note the IP address of the plugin and run the script specified in the user documentation on all the windows servers in your inventory Would you like to setup credentials for servers not managed by vCenter using SSH/Cert based for Linux? [Y/N]: Y Choose one of the following options for remote authentication: 1. SSH based authentication 2. Certificate based authentication Enter your options [1-2]: 1 Would you like to use the same Linux credentials used during vCenter setup? [Y/N]: Y Generating SSH key on this machine... SSH key pair path: /opt/amazon/mhub-orchestrator-plugin/remote-auth/linux/keys/id_rsa_rubix Please add the public key "id_rsa_rubix.pub" to the "$HOME/.ssh/authorized_keys" file in your remote machines. Your Linux remote server configurations are saved successfully. ``` -------------------------------- ### Set up Project and Install Dependencies Source: https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-get-started-websocket Commands to create a project directory, set up a virtual environment, and install the bedrock-agentcore package. ```bash mkdir agentcore-runtime-quickstart-websocket cd agentcore-runtime-quickstart-websocket python3 -m venv .venv source .venv/bin/activate ``` ```bash pip install --upgrade pip ``` ```bash pip install bedrock-agentcore ``` -------------------------------- ### Hello Aurora Example Source: https://docs.aws.amazon.com/code-library/latest/ug/csharp_4_aurora_code_examples Demonstrates how to get started with Aurora by listing DB clusters using the AWS SDK for .NET (v4). Requires AWS SDK for .NET Core setup and an AWS profile. ```csharp using Amazon.RDS; using Amazon.RDS.Model; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace AuroraActions; public static class HelloAurora { static async Task Main(string[] args) { // Use the AWS .NET Core Setup package to set up dependency injection for the // Amazon Relational Database Service (Amazon RDS). // Use your AWS profile name, or leave it blank to use the default profile. using var host = Host.CreateDefaultBuilder(args) .ConfigureServices((_, services) => services.AddAWSService() ).Build(); // Now the client is available for injection. Fetching it directly here for example purposes only. var rdsClient = host.Services.GetRequiredService(); // You can use await and any of the async methods to get a response. var response = await rdsClient.DescribeDBClustersAsync(new DescribeDBClustersRequest { IncludeShared = true }); Console.WriteLine($"Hello Amazon RDS Aurora! Let's list some clusters in this account:"); if (response.DBClusters == null) { Console.WriteLine($"\tNo clusters found."); } else { foreach (var cluster in response.DBClusters) { Console.WriteLine( $"\tCluster: database: {cluster.DatabaseName} identifier: {cluster.DBClusterIdentifier}."); } } } } ``` -------------------------------- ### Get started with EventBridge Scheduler Source: https://docs.aws.amazon.com/code-library/latest/ug/csharp_3_scheduler_code_examples This example demonstrates how to initialize the EventBridge Scheduler client and list schedules in your AWS account using the AWS SDK for .NET. It utilizes dependency injection for service setup. ```csharp public static class HelloScheduler { static async Task Main(string[] args) { // Use the AWS .NET Core Setup package to set up dependency injection for the EventBridge Scheduler service. // Use your AWS profile name, or leave it blank to use the default profile. using var host = Host.CreateDefaultBuilder(args) .ConfigureServices((_, services) => services.AddAWSService() ).Build(); // Now the client is available for injection. var schedulerClient = host.Services.GetRequiredService(); // You can use await and any of the async methods to get a response, or a paginator to list schedules or groups. var results = new List(); var paginateSchedules = schedulerClient.Paginators.ListSchedules( new ListSchedulesRequest()); Console.WriteLine( $"Hello AWS Scheduler! Let's list schedules in your account."); // Get the entire list using the paginator. await foreach (var schedule in paginateSchedules.Schedules) { results.Add(schedule); } Console.WriteLine($"\tTotal of {results.Count} schedule(s) available."); results.ForEach(s => Console.WriteLine($"\tSchedule: {s.Name}")); } } ``` -------------------------------- ### Choosing an AWS Quick Start Template Source: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/using-sam-cli-init This example shows the interactive prompts when initializing a project using an AWS Quick Start Template. It demonstrates selecting the template source and then choosing a specific application template. ```bash Which template source would you like to use? 1 - AWS Quick Start Templates 2 - Custom Template Location Choice: {{1}} Choose an AWS Quick Start application template 1 - Hello World Example 2 - Multi-step workflow 3 - Serverless API 4 - Scheduled task 5 - Standalone function 6 - Data processing 7 - Hello World Example With Powertools 8 - Infrastructure event management 9 - Serverless Connector Hello World Example 10 - Multi-step workflow with Connectors 11 - Lambda EFS example 12 - DynamoDB Example 13 - Machine Learning Template: {{4}} ``` -------------------------------- ### Run Amazon S3 Getting Started Example (JavaScript) Source: https://docs.aws.amazon.com/AmazonS3/latest/developerguide/s3_example_s3_Scenario_GettingStarted_section This is the main function that orchestrates the Amazon S3 getting started example. It demonstrates bucket creation, file operations, and cleanup. Ensure you have the AWS SDK for JavaScript configured. ```javascript const main = async () => { const OBJECT_DIRECTORY = `${dirnameFromMetaUrl( import.meta.url, )}../../../../resources/sample_files/.sample_media`; try { console.log(wrapText("Welcome to the Amazon S3 getting started example.")); console.log("Let's create a bucket."); const bucketName = await createBucket(); await prompter.confirm({ message: continueMessage }); console.log(wrapText("File upload.")); console.log( "I have some default files ready to go. You can edit the source code to provide your own.", ); await uploadFilesToBucket({ bucketName, folderPath: OBJECT_DIRECTORY, }); await listFilesInBucket({ bucketName }); await prompter.confirm({ message: continueMessage }); console.log(wrapText("Copy files.")); await copyFileFromBucket({ destinationBucket: bucketName }); await listFilesInBucket({ bucketName }); await prompter.confirm({ message: continueMessage }); console.log(wrapText("Download files.")); await downloadFilesFromBucket({ bucketName }); console.log(wrapText("Clean up.")); await emptyBucket({ bucketName }); await deleteBucket({ bucketName }); } catch (err) { console.error(err); } }; ``` -------------------------------- ### Run Device Sample Camera Example Source: https://docs.aws.amazon.com/iot-mi/latest/devguide/hub-control Executes the device sample camera example, assuming MQTTProxy and HubOnboarding components are running. ```bash ./examples/iotmi_device_sample_camera/iotmi_device_sample_camera ``` -------------------------------- ### Get started with AWS Glue using JavaScript Source: https://docs.aws.amazon.com/code-library/latest/ug/javascript_3_glue_code_examples This example demonstrates how to get started with AWS Glue by listing available jobs. It requires the `@aws-sdk/client-glue` package. ```javascript import { ListJobsCommand, GlueClient } from "@aws-sdk/client-glue"; const client = new GlueClient({}); export const main = async () => { const command = new ListJobsCommand({}); const { JobNames } = await client.send(command); const formattedJobNames = JobNames.join("\n"); console.log("Job names: "); console.log(formattedJobNames); return JobNames; }; ``` -------------------------------- ### Initialize Terraform and Navigate to Example Source: https://docs.aws.amazon.com/prometheus/latest/userguide/obs_accelerator Initialize Terraform in the specific example directory and prepare for configuration. ```bash cd examples/eks-amp-managed terraform init ``` -------------------------------- ### Example Kickstart File Name Source: https://docs.aws.amazon.com/elemental-live/latest/installguide/install-vm-lv-ig-prep An example of a kickstart file name used for creating a VM instance. ```text centos-20161028T12270-production-usb.ova ``` -------------------------------- ### Hello CloudWatch Example Source: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/full A basic example to get started with CloudWatch using an AWS SDK. ```python import boto3 # Initialize CloudWatch client cloudwatch = boto3.client('cloudwatch') # Example: List all alarms (this is a placeholder, actual operation might differ) response = cloudwatch.describe_alarms() print(response) ``` -------------------------------- ### C++ Lambda Scenario: Get Started with Functions Source: https://docs.aws.amazon.com/code-library/latest/ug/lambda_example_lambda_Scenario_GettingStartedFunctions_section Initiates the 'Get started with functions' scenario in C++. This example requires an IAM role ARN and uses the Lambda client. ```cpp //! Get started with functions scenario. /*! \param clientConfig: AWS client configuration. \return bool: Successful completion. */ bool AwsDoc::Lambda::getStartedWithFunctionsScenario( const Aws::Client::ClientConfiguration &clientConfig) { Aws::Lambda::LambdaClient client(clientConfig); // 1. Create an AWS Identity and Access Management (IAM) role for Lambda function. Aws::String roleArn; if (!getIamRoleArn(roleArn, clientConfig)) { return false; } ``` -------------------------------- ### Connect and Setup Client Source: https://docs.aws.amazon.com/cli/latest/userguide/bash_sts_code_examples Instructions for connecting to an EC2 instance and uploading/running a setup script. Ensure you have your key file and client DNS ready. ```bash 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 "" 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 "" ``` -------------------------------- ### AWS Configuration Setup Example Source: https://docs.aws.amazon.com/migrationhub-strategy/latest/userguide/getting-started-collector-setup This example demonstrates the prompts and expected inputs for setting up AWS configurations for the collector, including IAM permissions, credential type, access keys, region, and metrics/log upload preferences. ```bash Have you setup IAM permissions in you AWS account as per the user guide? [Y/N]: Y Choose one of the following options for providing user credentials: 1. Long term AWS credentials 2. Temporary AWS credentials Enter your options [1-2]: 2 AWS session token: AWS access key ID [None]: AWS secret access Key [None]: AWS region name [us-west-2]: AWS configurations are saved successfully Upload collector related metrics to migration hub strategy service? By default collector will upload metrics. [Y/N]: Y Upload collector related logs to migration hub strategy service? By default collector will upload logs. [Y/N]: Y Application data collector configurations are saved successfully Start registering application data collector Application data collector is registered successfully. ``` -------------------------------- ### Hello Amazon EC2: DescribeSecurityGroups Source: https://docs.aws.amazon.com/code-library/latest/ug/javascript_3_ec2_code_examples This example shows how to get started with Amazon EC2 by describing security groups. It lists up to 10 security groups, displaying their IDs and names. Ensure you have the AWS SDK for JavaScript (v3) installed and configured. ```javascript import { DescribeSecurityGroupsCommand, EC2Client } from "@aws-sdk/client-ec2"; // Call DescribeSecurityGroups and display the result. export const main = async () => { const client = new EC2Client(); try { const { SecurityGroups } = await client.send( new DescribeSecurityGroupsCommand({}), ); const securityGroupList = SecurityGroups.slice(0, 9) .map((sg) => ` • ${sg.GroupId}: ${sg.GroupName}`) .join("\n"); console.log( "Hello, Amazon EC2! Let's list up to 10 of your security groups:", ); console.log(securityGroupList); } catch (err) { console.error(err); } }; // Call function if run directly. import { fileURLToPath } from "node:url"; if (process.argv[1] === fileURLToPath(import.meta.url)) { main(); } ``` -------------------------------- ### Get started with Amazon ECR Source: https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/java_ecr_code_examples This example demonstrates how to get started with Amazon ECR by listing Docker image tags in a specified repository. It requires the repository name as a command-line argument. ```java import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ecr.EcrClient; import software.amazon.awssdk.services.ecr.model.EcrException; import software.amazon.awssdk.services.ecr.model.ListImagesRequest; import software.amazon.awssdk.services.ecr.paginators.ListImagesIterable; public class HelloECR { public static void main(String[] args) { final String usage = """ Usage: Where: repositoryName - The name of the Amazon ECR repository. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String repoName = args[0]; EcrClient ecrClient = EcrClient.builder() .region(Region.US_EAST_1) .build(); listImageTags(ecrClient, repoName); } public static void listImageTags(EcrClient ecrClient, String repoName){ ListImagesRequest listImagesPaginator = ListImagesRequest.builder() .repositoryName(repoName) .build(); ListImagesIterable imagesIterable = ecrClient.listImagesPaginator(listImagesPaginator); imagesIterable.stream() .flatMap(r -> r.imageIds().stream()) .forEach(image -> System.out.println("The docker image tag is: " +image.imageTag())); } } ``` -------------------------------- ### Navigate to Project Directory Source: https://docs.aws.amazon.com/cloudformation-cli/latest/hooks-userguide/hooks-init Change into the newly created project directory to begin initialization. ```bash cd {{~/mycompany-testing-mytesthook}} ``` -------------------------------- ### Hello Amazon Bedrock Example Source: https://docs.aws.amazon.com/bedrock/latest/userguide/full Get started with Amazon Bedrock using basic examples. The source code for these examples is available in the AWS Code Examples GitHub repository. ```python import boto3 # Initialize the Bedrock Runtime client boto_session = boto3.Session(region_name="us-east-1") bedrock_runtime = boto_session.client( service_name="bedrock-runtime", endpoint_url="https://bedrock-runtime.us-east-1.amazonaws.com", ) # Example usage (replace with actual model ID and prompt) # response = bedrock_runtime.invoke_model(...) # print(response) print("Bedrock Runtime client initialized.") ``` -------------------------------- ### System Configuration and Defaults Setup Source: https://docs.aws.amazon.com/elemental-cl3/latest/upgradeguide/sample-upg-cl3-upg Outlines the post-verification steps, including creating directory structures, setting server defaults, checking user presets, and configuring various system services like Apache, SNMP, NTP, and Avahi. ```text Creating default directory structures and data Setting server defaults... Checking user presets... Checking user profiles... Changing permissions and ownership... Cleaning elemental_ipc... Removing tmp... Removing cached files Configuring Apache... Adding Elemental service... Configuring log rotation... Configuring SNMP... Configuring dynamic libraries... Configuring NTP... Setting sysctl configuration and adding to /etc/rc.local... Configuring Avahi... ``` -------------------------------- ### Run AWS Backint Agent Installer (Interactive Mode) Source: https://docs.aws.amazon.com/sap/latest/sap-AnyDB/ase-backint-install Execute the installer script without any arguments to start the interactive installation process, which guides you through configuration. ```bash ./install-aws-backint-agent-ase ``` -------------------------------- ### Launch Installed Program Source: https://docs.aws.amazon.com/cloudshell/latest/userguide/vm-specs Example of how to run a program after it has been installed in the current session. ```bash echo "Welcome to AWS CloudShell" | cowsay ```