Welcome to the AWS Code Examples Repository.

NOTICE

We have changed the default branch for this repo from master to main.

If the parent branch of your fork or branch is master, the following instructions tell you how to change the parent branch to main.

To show the parent branch, where BRANCH is the name of your branch:

  1. Navigate to the root of your branch or fork.
  2. Make sure your branch is the current branch (git checkout BRANCH).
  3. Run git branch --contains.

Changing a branch parent branch from master to main

To change the parent branch for your branch to main, navigate to the root of your branch and enter the following commands, where BRANCH is the name of your branch:

git branch -m master main
git fetch origin
git branch -u origin/main main
git remote set-head origin -a
git remote update --prune

Changing a fork's default branch from master to main

GitHub will notify you when a parent branch has changed. To change your fork's default branch to main:

  1. Navigate to main web page of your fork.
  2. You should see a "The default branch on the parent repository has been renamed" message.
  3. Select the branch settings link.
  4. Change master to main.

Questions or Issues?

If you have any questions, or run across any issue retargeting your branch or fork, open an issue and give us as much detail as possible.

Welcome

This is the repository for various code examples used in the public AWS documentation. For more information, see Tools to Build on AWS.

Finding code examples

The code examples are organized by AWS SDK or AWS programming tool. For example, among the top-level folders:

  • cpp for the latest version of the AWS SDK for C++ (version 1)
  • dotnetv3 for the latest version of the AWS SDK for .NET (version 3.5 and later)
  • gov2 for the latest version of the AWS SDK for Go (version 2)
  • javav2 for the latest version of the AWS SDK for Java (version 2)
  • javascriptv3 for the latest version of the AWS SDK for JavaScript (version 3)
  • php for the latest version of the AWS SDK for PHP (version 3)
  • python for the latest version of the AWS SDK for Python (Boto3)
  • ruby for the latest version of the AWS SDK for Ruby (version 3)

We also have code examples for two SDKs currently in alpha, DO NOT USE THIS EXAMPLE CODE IN PRODUCTION:

  • .kotlin_alpha for the alpha version of the AWS SDK for Kotlin.
  • rust_dev_preview for the developer preview version of the AWS SDK for Rust.

Code examples for older AWS SDK versions are archived in this repository but no longer maintained. These include:

  • dotnet for versions of the AWS SDK for .NET prior to version 3.5
  • go for AWS SDK for Go version 1
  • java for AWS SDK for Java version 1
  • javascript for AWS SDK for JavaScript version 2

As AWS SDK major version numbers increment, this repository will begin to more consistently reflect their version numbers among these folders to make these distinctions clearer. For example, if and when the AWS SDK for Ruby moves to a version 4, a new rubyv4 folder will be added. Then when AWS officially announces that AWS SDK for Ruby version 3 has been deprecated, the ruby folder will be deleted.

Other top-level folders include:

  • aws-cli for script examples for use with the AWS Command Line Interface (AWS CLI).
  • cloudformation for example templates for use with AWS CloudFormation.
  • iam_policies for example policy documents for use with AWS Identity and Access Management (IAM).
  • lambda_functions for example function code for use with AWS Lambda.
  • typescript for TypeScript-based code examples for use with the AWS Cloud Development Kit (CDK), and other AWS services. (For TypeScript-based code examples for use with the AWS SDK for JavaScript, see the javascriptv3 folder.)

Note that the scripts folder contains scripts that the AWS documentation team uses internally to build the code examples into various AWS documentation sets.

Building and running code examples

Inside each language-specific directory, we include a README file that explains how to build and run the examples in the directory.

The example code in the language-specific directories is organized by the AWS service command in the AWS Command Line Interface (AWS CLI) Command Reference (s3 for Amazon S3 examples, and so on).

Proposing new code examples

To propose a new code example for the AWS documentation team to consider working on, create a request.

Note that the AWS documentation team prefers to produce code examples that cover broader scenarios and use cases, versus simple code snippets that cover only individual API calls.

Submitting code examples for use in AWS documentation

If you plan to contribute examples for use in the documentation (the purpose of this repository), read this section carefully so that we can work together effectively. For process instructions and additional guidance, see the Guidelines for contributing.

Copyright and License

All content in this repository, unless otherwise stated, is Copyright © Amazon Web Services, Inc. or its affiliates. All rights reserved.

Except where otherwise noted, all examples in this collection are licensed under the Apache license, version 2.0 (the "License"). The full license text is provided in the LICENSE file accompanying this repository.

Owner
Amazon Web Services - Documentation
Documenting Amazon Web Services and SDKs
Amazon Web Services - Documentation
Comments
  • Help Wanted

    Help Wanted

    Do you have any ideas for new examples? For any particular service? In any particular language?

    We would love to hear from you.

    Suggestions? Questions? Whatever keeps you awake at night.

  • AWS Comprehend Medical Text Analysis Map

    AWS Comprehend Medical Text Analysis Map

    Hello,

    I have JSON data using AWS comprehend medical but unfortunately, I couldn't find the example to generate the following map in the examples on AWS's Github page.

    How can I create this SVG (map) that AWS creates programmatically or does anyone have an example?

    AWSCM

    Is it possible for you to share the code to create this diagram? Thank you.

  • How to do async multi-part upload using InputStream for parts

    How to do async multi-part upload using InputStream for parts

    I have some very large files to upload using multi-part upload. I'd like to use the async interface, but I don't see any way to attach an InputStream to the UploadPartRequest. It only accepts buffers. What if I don't want to read 5MB of data into a byte buffer and pass it in for every part to be uploaded? What if I'd rather just pass in my InputStream that encapsulates my file part?

  • [Bug] S3Client GetObject works - S3EncryptionClient says NoSuchKey!

    [Bug] S3Client GetObject works - S3EncryptionClient says NoSuchKey!

    This may be a bug with C++ AWS SDK. I am able to upload, list, and then download items from my bucket just fine. I can also upload with the encryption client, list, and download with the vanilla client just fine. Naturally files are encrypted at this point... BUT if I try to list and download with the encryption client, it says there's no such key!

        std::vector<std::string> files = GetList(); // uses s3 list object
        Aws::Client::ClientConfiguration config;
        config.region = '{region}'
    
        const size_t keyLen = keyFile->GetKeyLength();
        const auto key = std::string(keyFile->GetKey(), keyLen);
    
        char to_uchar[keyLen];
        std::copy(key.begin(), key.end(), to_uchar);
        to_uchar[keyLen] = 0;
    
        // AES256
        auto encryption = Aws::MakeShared<Aws::S3Encryption::Materials::SimpleEncryptionMaterials>(to_uchar, keyLen);
    
        #ifdef UNDER_MACOS
            CryptoConfiguration cryptoConfiguration(StorageMethod::METADATA, CryptoMode::ENCRYPTION_ONLY);
        #else
            CryptoConfiguration cryptoConfiguration(StorageMethod::METADATA, CryptoMode::STRICT_AUTHENTICATED_ENCRYPTION);
        #endif
    
        //Aws::S3::S3Client s3(config); // <--- this works!
        Aws::S3Encryption::S3EncryptionClient s3(encryption, cryptoConfiguration, config); // <-- this doesn't work!
    
        for(auto key : files) {
            Aws::S3::Model::GetObjectRequest req;
            req.WithBucket("{BUCKET}");
            req.WithKey(key.c_str());
            auto res = s3.GetObject(req);
    
            if(res.IsSuccess()) {
                Aws::OFStream local_file;
                std::string loc = "outputdir/"+key;
                local_file.open(loc.c_str(), std::ios::out | std::ios::binary);
                local_file << res.GetResult().GetBody().rdbuf();
            } else {
                std::cout << "S3 get `" + key + "` request failed with error (" << res.GetError().GetExceptionName() << "): \"" << res.GetError().GetMessage() << "\"" << std::endl;
            }
        }
    

    Again, with regular S3 client it is fine. With S3EncryptionClient, this is my output for every file:

    S3 get `fake_file_XYZ` request failed with error (NoSuchKey): "The specified key does not exist."
    

    But my aws CLI shows that it does!

  • [BUG] S3 Connection timeout - Unable to execute HTTP request

    [BUG] S3 Connection timeout - Unable to execute HTTP request

    What is the issue?

    I'm trying to connect to S3 bucket using S3Client from Java2 (software.amazon.awssdk.services.s3.S3Client) and using S3EventNotification from Java1(com.amazonaws.services.s3.event.S3EventNotification) reading the .gz file and converting to ResponseInputStream it results to connect timeout(intermittent issue)

    How can someone reproduce this issue (if applicable)?

    1. Lambda is configured with VPC, subnets and security group. execution time is 5 min's

    2. Lambda function having S3Client and reading the .gz file from S3 bucket and converting to ResponseInputStream

    3. Lambda function is used S3EventNotification to construct object request To get objectRequest = getS3ObjectRequest, used this code

      S3EventNotification s3EventNotification = S3EventNotification.parseJson(message.getBody()); S3EventNotification.S3EventNotificationRecord record = s3EventNotification.getRecords().get(0); String bucketName = record.getS3().getBucket().getName(); String bucketKey = record.getS3().getObject().getKey(); GetObjectRequest getObjectRequest = GetObjectRequest.builder() .bucket(bucketName) .key(bucketKey) .build();

    4. S3Client code s3Client = S3Client.builder() .region(Region.US_EAST_1) .build();

    5. To get the object from S3 bucket s3Client.getObject(objectRequest)

    What is the actual result when the preceding steps are followed (if applicable)? Results S3 Connection timeout, exception trace is here. software.amazon.awssdk.core.exception.SdkClientException: Unable to execute HTTP request: Connect to bucketname.s3.amazonaws.com:443 [bucketname.s3.amazonaws.com/] failed: connect timed out

    What was the result you expected instead (if applicable)?

    trying to avoid the connection time out.

    Environment details to help us try to reproduce the issue (if applicable)

    • AWS Lambda
    • AWS SDK for Java 2.x
    • AWS SDK for Java 1.x (for S3EventNotification)

    Any other related details we should know about?

    this issue is intermittent, let me know if you are not clear with this description. I have tried like increasing the connection timeout for httpclient but still same issue.

    SdkHttpClient sdkHttpClient = ApacheHttpClient.builder().connectionTimeout(Duration.ofSeconds(60)).build();

        s3Client = S3Client.builder()
                .region(Region.US_EAST_1)
                .httpClient(sdkHttpClient)
                .build();
    
  • [BUG] ec2 cpp sdk  NetworkInterface* - Multiple Compilation error

    [BUG] ec2 cpp sdk NetworkInterface* - Multiple Compilation error

    We face multiple Compilation error on EC2 when using ec2 cpp sdk in windows MFC application

    When using some .h which use any NetworkInterface*.h, we have various compilation errors.

    ex: NetworkInterfaceType.h(19,14): error C2332: 'struct': missing tag name NetworkInterfaceStatus.h(11,1): error C2143: syntax error: missing ';' before '{' CreateNetworkInterfaceResponse.h(49,89): error C2280: 'Aws::EC2::Model::NetworkInterface &Aws::EC2::Model::NetworkInterface::operator =(const Aws::EC2::Model::NetworkInterface &)': attempting to reference a deleted function

    Microsoft Visual Studio Community 2019 Version 16.9.5 VisualStudio.16.Release/16.9.5+31229.75 Microsoft .NET Framework Version 4.8.04084

  • [BUG] aws-doc-sdk-examples/go/example_code/cloudwatch/listing_metrics.go

    [BUG] aws-doc-sdk-examples/go/example_code/cloudwatch/listing_metrics.go

    What is the issue?

    I am trying to tap into CloudWatch Metrics using a AWS Lambda of a particular namespace using the above example, but all I get in response is a blank Array [].

    How can someone reproduce this issue (if applicable)?

    1. Deploy a Lambda Function
    2. Deploy the above code as a Golang binary zip
    3. Invoke the Function

    What is the actual result when the preceding steps are followed (if applicable)?

    On invoking the function, the metrics should be listed of the desired dimension, namespace but instead all I get is blank array []

    What was the result you expected instead (if applicable)?

    I expected the metrics data as per the documentation --> https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/cw-example-getting-metrics.html

    Environment details to help us try to reproduce the issue (if applicable)

    • Operating system and version: [Linux AWS Lambda amd64 ]
    • SDK or tool name: [AWS SDK for Go]
    • SDK or tool version: [1.14.5]
  • Exception Thrown (ntdll.dll) - S3 Object listing - c++ SDK

    Exception Thrown (ntdll.dll) - S3 Object listing - c++ SDK

    I am trying to just list bucket objects and I always face the same exception after the Aws api gets out of scope:

    
        Aws::SDKOptions options;
        Aws::InitAPI(options);
        {
            Aws::Client::ClientConfiguration config;
            config.region = Aws::Region::US_EAST_2;
            Aws::S3::S3Client s3_client(Aws::Auth::AWSCredentials(KEY,ACCESS_KEY), config);
    
            const Aws::String bucket_name = BUCKET;
    
            Aws::S3::Model::ListObjectsRequest objects_request;
            objects_request.WithBucket(bucket_name);
    
            auto list_objects_outcome = s3_client.ListObjects(objects_request);
    
            if (list_objects_outcome.IsSuccess())
            {
                Aws::Vector<Aws::S3::Model::Object> object_list =
                        list_objects_outcome.GetResult().GetContents();
    
                for (auto const &s3_object : object_list)
                {
                    std::cout << "* " << s3_object.GetKey() << std::endl;
                }
            }
            else
            {
                std::cout << "ListObjects error: " <<
                             list_objects_outcome.GetError().GetExceptionName() << " " <<
                             list_objects_outcome.GetError().GetMessage() << std::endl;
            }
        }
        Aws::ShutdownAPI(options);
    

    After connecting and listing all objects successfully I get an Exception thrown

    Exception thrown at 0x00007FFDDE9CC892 (ntdll.dll) in TestAWS_S3.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.

    The above happens even if I just define an Aws SDK Object (i.e. living only the Aws::Client::ClientConfiguration config; line uncommented).

    I am using a Win10 64bit PC with MSVC2017 Win64. The issue exists for both Release and Debug SDK builds.

    Have anyone faced the same issue?

  • Add (mostly C++; one Python) SDK examples

    Add (mostly C++; one Python) SDK examples

    I have been thinking of adding,

    • [x] SNS
      • [x] C++ https://github.com/awsdocs/aws-doc-sdk-examples/pull/189
    • [x] GuardDuty
      • [x] C++ https://github.com/awsdocs/aws-doc-sdk-examples/pull/209
    • [x] SES
      • [x] C++ https://github.com/awsdocs/aws-doc-sdk-examples/pull/208
      • [x] Python https://github.com/awsdocs/aws-doc-sdk-examples/pull/188
    • [x] EBS
      • [x] C++ https://github.com/awsdocs/aws-doc-sdk-examples/pull/221
    • [x] Elastic File System
      • [x] C++ https://github.com/awsdocs/aws-doc-sdk-examples/pull/212
    • [x] CloudTrail
      • [x] C++ https://github.com/awsdocs/aws-doc-sdk-examples/pull/210
    • [x] CodeCommit
      • [x] C++ https://github.com/awsdocs/aws-doc-sdk-examples/pull/215
    • [x] CodeBuild
      • [x] C++ https://github.com/awsdocs/aws-doc-sdk-examples/pull/214
    • [ ] ElastiCache
      • [ ] C++ https://github.com/awsdocs/aws-doc-sdk-examples/pull/220
    • [x] Neptune
      • [x] C++ https://github.com/awsdocs/aws-doc-sdk-examples/pull/211
    • [x] Glacier
      • [x] C++ https://github.com/awsdocs/aws-doc-sdk-examples/pull/213
    • [ ] Storage Gateway
      • [ ] C++ https://github.com/awsdocs/aws-doc-sdk-examples/pull/219

    The C++ code samples are near to none for the above over the web and code examples of later ones are not present in the documentation as sample codes like other example codes. Please let me know if you think it would be useful to add example code for the above in this repository, would be happy to add also if I should expand any of the above from the list to describe the specific api calls.

  • Sync objects to another bucket

    Sync objects to another bucket

    I'm looking for some code to copy a bunch of objects (an HLS stream with very many segments) to another bucket with a prefix, as efficiently as possible.

    BONUS: this sync job might have been already run and it will be a waste to redo the copy inefficiently.

    I noticed https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/go/example_code/s3/s3_copy_object.go but it would be better to have some sort of aws s3 sync starting points in golang for example.

  • [BUG] S3Client Failed to Create Bucket in Sample Codes

    [BUG] S3Client Failed to Create Bucket in Sample Codes

    What is the issue? Hi, I am following the sample code S3 Create Bucket Command for JS V3: javascriptv3/example_code/s3/src/s3_createbucket.js and I did the UI in react native based on this tutorial: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/getting-started-react-native.html

    But after typing the new bucket name in the UI, I got an error to create the bucket.

    How can someone reproduce this issue (if applicable)?

    1. Code Snippets: image

    2. UI for creating buckets Screen Shot 2021-06-09 at 11 21 33 AM

    3. Error Detail Screen Shot 2021-06-09 at 11 17 34 AM

    Environment details to help us try to reproduce the issue (if applicable)

    • Operating system and version: [Windows 10 | OSX Ver 11.3.1 ]
    • SDK or tool name: [AWS SDK for JavaScript]
    • SDK or tool version: Screen Shot 2021-06-09 at 11 19 44 AM
  • Add cpp lambda runtime

    Add cpp lambda runtime

    The user story

    As a c+= developer, I want use c++ for my lambda function.

    I know this is done when: The c++ lambda function is a replacement for the python lambda function in the scenario.

  • enable `assumeRole` method for use in IAM STS documentation

    enable `assumeRole` method for use in IAM STS documentation

    The IAM documentation for assumeRole in STS is missing a Java v2 code example. This PR adds snippet tags around the assumeRole method. This method was renamed from assumeGivenRole to simply assumeRole.

    This PR also add checkstyle.xml and fixes any checkstyle errors.

    aws-doc-sdk-examples Pull Request

    Thank you for making a submission to the aws-doc-sdk-examples repository. For more information about submitting pull requests to this repository, see Guidelines for contributing.

    NOTE: This pull request (PR) template contains two sections. Use the section that applies to your submission, and remove the section which doesn't apply.


    I'm resolving an issue with an existing code example

    Describe the changes you have made here, including any issue numbers.

    • add snippet tags around assumeRole method
    • rename assumeGivenRole to assumeRole
    • add checkstyle validation. Resolve any checkstyle errors.

    Confirm you have met the following minimum requirements:


    Open source license adherence

    By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

  • Refine Rust docker image and mark as GA

    Refine Rust docker image and mark as GA

    As an AWS customer, I want to be able to rely on the Docker image found in the Rust language repository to contain all the necessary examples for Rust, including pre-compiled dependencies so that I can effectively run example code in a Docker environment.

    I know this is done when:

    • the Dockerfile itself contains correct steps for resolving dependencies and is built successfully
    • the resulting Docker image is successfully pushed to ECR via the existing DevOps processes
    • the container that is created from that image runs some subset of example code (e.g. the Lambda MVP) successfully by exec'ing in, adding AWS credentials, and invoking it via terminal session
    • usage steps explaining which examples can be run and how are documented in the README.md#docker-image section.
  • Refine Cpp docker image and mark as GA

    Refine Cpp docker image and mark as GA

    As an AWS customer, I want to be able to rely on the Docker image found in each language repository to contain all the necessary examples for my language, including pre-compiled dependencies so that I can effectively run example code in a Docker environment.

    I know this is done when:

    • the Dockerfile itself contains correct steps for resolving dependencies and is built successfully
    • the resulting Docker image is successfully pushed to ECR via the existing DevOps processes
    • the container that is created from that image runs some subset of example code (e.g. the Lambda MVP) successfully by exec'ing in, adding AWS credentials, and invoking it via terminal session
    • usage steps explaining which examples can be run and how are documented in the README.md#docker-image section.
This repository shows how can we use `AWS Lambda` to build serverless applications in golang.

Serverless Api in Go with AWS Lambda Here we are going to use AWS Lambda to build serverless applications in golang. Prerequisites You’ll need an AWS

Nov 3, 2021
Simple no frills AWS S3 Golang Library using REST with V4 Signing (without AWS Go SDK)

simples3 : Simple no frills AWS S3 Library using REST with V4 Signing Overview SimpleS3 is a golang library for uploading and deleting objects on S3 b

Nov 4, 2022
Integrate AWS EKS Anywhere cluster with AWS Services
 Integrate AWS EKS Anywhere cluster with AWS Services

This article provides step-by-step instruction on integrating AWS EKS Anywhere with AWS Services so the applications running on customer data center can securely connect with these services.

Mar 6, 2022
Apis para la administracion de notifiaciones, utilizando servicios como AWS SNS y AWS SQS

notificacion_api Servicio para envío de notificaciónes por difusión en AWS SNS Especificaciones Técnicas Tecnologías Implementadas y Versiones Golang

Jan 7, 2022
AWS credential_process utility to assume AWS IAM Roles with Yubikey Touch and Authenticator App TOPT MFA to provide temporary session credentials; With encrypted caching and support for automatic credential refresh.
AWS credential_process utility to assume AWS IAM Roles with Yubikey Touch and Authenticator App TOPT MFA to provide temporary session credentials; With encrypted caching and support for automatic credential refresh.

AWS credential_process utility to assume AWS IAM Roles with Yubikey Touch and Authenticator App TOPT MFA to provide temporary session credentials; With encrypted caching and support for automatic credential refresh.

Dec 20, 2022
A package for access aws service using AWS SDK for Golang

goaws ?? A package for access aws service using AWS SDK for Golang Advantage with goaws package Example for get user list IAM with AWS SDK for Golang

Nov 25, 2021
Simple CRUD API written in Go, built using AWS SAM tool and using the AWS' infrastructure.
Simple CRUD API written in Go, built using AWS SAM tool and using the AWS' infrastructure.

tutor-pet API Simple CRUD API written in Go, built using AWS SAM tool and using the AWS' infrastructure. Macro architecture: Code architecture: Pre-Re

Aug 17, 2022
Aws-parameter-bulk - Export AWS SSM Parameter Store values in bulk to .env files

aws-parameter-bulk Utility to read parameters from AWS Systems Manager (SSM) Par

Oct 18, 2022
Feb 7, 2022
Una prueba técnica: Servicio Golang REST API local, sobre Docker, gRPC, AWS Serverless y sobre Kubernetes en AWS EC2

Una prueba técnica: Servicio Golang REST API local, sobre Docker, gRPC, AWS Serverless y sobre Kubernetes en AWS EC2

May 7, 2022
This repository will have code implemented for the 100 days of golang.

golang_100 This repository will have code implemented for the 100 days of golang. The resources I will use to do this 100 days golang programming are:

Jan 10, 2022
Plot your repository stars over time.

Plot your repository stars over time.

Dec 30, 2022
Repository generator for Go

repogen repogen is a Golang Codegen that generates database query and mutation end-to-end with its model. How it works repogen describe our given tabl

Aug 4, 2022
This is the new api repository for Feel the Movies. Written in Go, totally open source.
This is the new api repository for Feel the Movies. Written in Go, totally open source.

This is the new API repository for Feel the Movies. Written in Go, totally open source. App Currently available for Android only. I have plans for an

Sep 18, 2022
Satisfactory Mod Repository (SMR) API

SMR API The Satisfactory Mod Repository backend API Running Execute: go run cmd/api/serve.go Configuration Running the API has a lot of pre-requisites

Feb 4, 2022
It is a package and command line application that provides you to store encrypted credentials/secrets in your repository.

sypher[ ⚠️ Work in progress] sypher provides you to store your credentials and secrets as encrypted in your repository. Usage Install the command line

Feb 23, 2022
Golang-action - A template repository for writing custom GitHub Actions in Golang

Golang Action A template repository for writing custom GitHub Actions in Golang.

Feb 12, 2022
Updates labels for a Github repository using a template file.

Github Labeler The purpose of this application is to sync your default labels with a repository hosted by Github. Labeler automatically merges your la

Mar 6, 2022
A GitHub CLI extension that displays collaboration-related information about a GitHub repository.
A GitHub CLI extension that displays collaboration-related information about a GitHub repository.

collab-scanner GitHub CLI extension A GitHub CLI extension that displays collaboration-related information on a repository. Install gh extension insta

Dec 30, 2022