Reputation: 14903
The role configured on CodeBuild project works fine with the runtime environment but doesn't work when we run a command from inside the container, it says "unable to locate credentials".
Let me know how can we use the role out of the box inside the container.
Upvotes: 8
Views: 7343
Reputation: 8890
You can make use of credential source "EcsContainer" to assume role seamlessly without having to export new credentials in your buildspec.yml.
credential_source - The credential provider to use to get credentials for the initial assume-role call. This parameter cannot be provided alongside source_profile. Valid values are:
- Environment to pull source credentials from environment variables.
- Ec2InstanceMetadata to use the EC2 instance role as source credentials.
- EcsContainer to use the ECS container credentials as the source credentials.
From: https://docs.aws.amazon.com/cli/latest/topic/config-vars.html
Steps:
Step-0: Create a new Role 'arn:aws:iam::0000000000:role/RoleToBeAssumed' and attach required policies to provide the permission required for the commands you are running during the build.
Step-1: Add sts:assumeRole permissions to your CodeBuild Service Role. Here is a sample policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor1",
"Effect": "Allow",
"Action": "sts:*",
"Resource": "arn:aws:iam::0000000000:role/RoleToBeAssumed"
}
]
}
Step-2: Configure your build container to use the credential metadata as source for assuming the role. Here is a buildspec example:
version: 0.2
phases:
install:
runtime-versions:
nodejs: 8
commands:
- aws sts get-caller-identity
- aws configure credential_source EcsContainer
- aws configure role_arn 'arn:aws:iam::0000000000:role/RoleToBeAssumed'
- cat ~/.aws/config
- aws sts get-caller-identity
Upvotes: 9
Reputation: 14903
Another way is to assume the role manually and export the auth tokens. Make sure you have ASSUME_ROLE_ARN available as environment variable -
commands:
- TEMP_ROLE=`aws sts assume-role --role-arn $ASSUME_ROLE_ARN --role-session-name temp`
- export 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')
- docker push $ECR_IMAGE_URL:$IMAGE_TAG
Upvotes: 2
Reputation: 546
If you need to run a Docker container in a build environment and the container requires AWS credentials, you must pass through the credentials from the build environment to the container.
docker run -e AWS_DEFAULT_REGION -e AWS_CONTAINER_CREDENTIALS_RELATIVE_URI your-image-tag aws s3 ls
https://docs.aws.amazon.com/codebuild/latest/userguide/troubleshooting.html#troubleshooting-versions
Upvotes: 7