How do I pass temporary credentials for AssumeRole into the Docker runtime with AWS CodeBuild?

Last updated: 2020-09-24

I want to pass temporary credentials for AssumeRole into the Docker runtime with AWS CodeBuild.

Short description

CodeBuild uses the CodeBuild service role as the default AWS credential in the build container and Docker runtime.

Export the AssumeRole credentials as environment variables. Then, pass these variables into the Docker runtime by using the docker build --build-arg parameter. For more information, see docker build on the Docker Docs website.

Resolution

1.    Create a new role for the Docker runtime (for example, Secretassumerole). Then, use the new role to get the secret AWSExampleSecret value from AWS Secrets Manager. For example:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "secretsmanager:GetResourcePolicy",
                "secretsmanager:GetSecretValue",
                "secretsmanager:DescribeSecret",
                "secretsmanager:ListSecretVersionIds"
            ],
            "Resource": [
                "arn:aws:secretsmanager:ap-northeast-1:$account_id:secret:tutorials/AWSExampleSecret-EHWYme"
            ]
        }
    ]
}

Note: You can give any operation permission during the Docker runtime.

2.    Add sts:assumeRole permissions to your CodeBuild service role to allow AssumeRole operations. For example:

{
    "Version": "2012-10-17",
    "Statement": [
            {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": "sts:AssumeRole",
            "Resource": "arn:aws:iam::$account_id:role:role/Secretassumerole"
        }
    ]
}

3.    Use a build spec to export the AssumeRole credentials into an environment variable. Then, use the docker build command to pass the credentials into your Docker runtime. For example:

version: 0.2
phases:
  install:
    runtime-versions:
      nodejs: 8
    commands:
      - ASSUME_ROLE_ARN="arn:aws:iam::$account_id:role/Secretassumerole"
      - TEMP_ROLE=`aws sts assume-role --role-arn $ASSUME_ROLE_ARN --role-session-name test`
      - export TEMP_ROLE
      - echo $TEMP_ROLE
      - export AWS_ACCESS_KEY_ID=$(echo "${TEMP_ROLE}" | jq -r '.Credentials.AccessKeyId')
      - export AWS_SECRET_ACCESS_KEY=$(echo "${TEMP_ROLE}" | jq -r '.Credentials.SecretAccessKey')
      - export AWS_SESSION_TOKEN=$(echo "${TEMP_ROLE}" | jq -r '.Credentials.SessionToken')
      - echo $AWS_ACCESS_KEY_ID
      - echo $AWS_SECRET_ACCESS_KEY
      - echo $AWS_SESSION_TOKEN
  pre_build:
    commands:
      - echo Build started on `date`
      - echo Building the Docker image...
      - docker build --build-arg AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID --build-arg AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY --build-arg AWS_SESSION_TOKEN=$AWS_SESSION_TOKEN

Note: You can use --duration-seconds to set the maximum session duration for the assume role. The --duration-seconds option accepts a value from 1 hour to 12 hours. If you set a value higher than 12 hours, the operation fails.

4.    In your Dockerfile, get the AssumeRole credentials when you build an image. For example:

FROM amazonlinux:latest
RUN yum -y install aws-cli 
ARG AWS_DEFAULT_REGION 
ARG AWS_ACCESS_KEY_ID 
ARG AWS_SECRET_ACCESS_KEY 
ARG AWS_SESSION_TOKEN 
RUN echo $AWS_DEFAULT_REGION 
RUN echo $AWS_ACCESS_KEY_ID 
RUN echo $AWS_SECRET_ACCESS_KEY 
RUN echo $AWS_SESSION_TOKEN 
RUN aws sts get-caller-identity 
RUN aws secretsmanager get-secret-value --secret-id tutorials/AWSExampleSecret

Note: You can remove the echo statement from the buildspec and Dockerfile that prints the temporary credentials.

You see output similar to the following:

Step 8/11 : RUN echo $AWS_ACCESS_KEY_ID 
 ---> Running in 7349ee896c1a 
ASIAWNOF2TBWYN3DC7RX 
Removing intermediate container 7349ee896c1a 
 ---> 32a8170f9697 
Step 9/11 : RUN echo $AWS_SECRET_ACCESS_KEY 
 ---> Running in 9f16f1252d93 
KJq+JNqmnNq1JirNUBkxc+kRVavgZwhpFFIJjxD6 
Removing intermediate container 9f16f1252d93 
 ---> 91fe8de3d301 
Step 10/11 : RUN echo $AWS_SESSION_TOKEN 
 ---> Running in 12ddfe17d5de 
FQoGZXIvYXdzEJP//////////wEaDPTjooaOAaU8NDj5oyKkAjVwT4uQHTZJdCtfOZxa6wTZVOy0Zkw+laN1RRVZhvhdPOWhU8VgK2d7ZgTlqaXn4NSrdWlnub6g5JobP4o509t3VLdMUR5ZJJcpnSlJAY5YM7vlPndroGcV+Y689ztVzQ1uVxdtpjQK1qh87fw6m0dHt7Q8Y8TferRNVvCM4kOroxPzovTbO6IkLDcBp8PhOVgtVtxEpON6nZrN990zzUmhXjT0vrtpDtAi339hhs7fzDOrnllQHSAmSerT0NhMOYVqBH1HJOq3FYnG+TUbHENpSq3kwTiPL2uoTw7/Ufrrgz4i3ENHm3rIWlbD8VuleDl5yhooKifmKDPjQAHs5HbVjD9lnxQFrCIuyvZdmsqzgoIjPt6z5H8lzugLHAAmbgiOwDoo+Oba7QU= 
Removing intermediate container 12ddfe17d5de 
 ---> 0cc838f3c865 
Step 11/11 : RUN aws sts get-caller-identity 
 ---> Running in 98b7c2f07621 
{ 
    "Account": “xxxxxxxxx”,  
    "UserId": "AROAWNOF2TBWS3TGMQRV3:test",  
    "Arn": "arn:aws:sts::$account_id:assumed-role/Secretassumerole/test" 
} 
Removing intermediate container 6d525393d667 
 ---> 2da2f38adc77 
Step 12/12 : RUN aws secretsmanager get-secret-value --secret-id tutorials/AWSExampleSecret --region ap-northeast-1 
 ---> Running in c8ac00304416 
{ 
    "Name": "tutorials/AWSExampleSecret",  
    "VersionId": "3f37aa26-691e-4b4b-ad80-861680464cb9",  
    "SecretString": "{\"username\":\"myserviceusername\",\"password\":\"MyVerySecureP@ssw0rd!\"}",  
    "VersionStages": [ 
        "AWSCURRENT" 
    ],  
    "CreatedDate": 1558616482.926,  
    "ARN": "arn:aws:secretsmanager:ap-northeast-1:$account_id:secret:tutorials/M-EHWYme" 
} 
Removing intermediate container c8ac00304416 
 ---> c3be32e39b0e 
Successfully built c3be32e39b0e

Did this article help?


Do you need billing or technical support?