MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

How to set Security Credentials in a AWS Code Build

AWS CodeBuild should get its AWS credentials from an IAM service role attached to the build project, not from access keys typed into environment variables. This guide explains how to set up that role, check which identity a build uses, and load secrets such as API tokens and passwords from Parameter Store or Secrets Manager. It also corrects the insecure steps in the original post.

To set security credentials in AWS CodeBuild, you can use the AWS CLI or the CodeBuild console.

Using the AWS CLI:

  1. Run the command aws configure to set up your credentials.
  2. Type in your AWS access key and secret key when prompted.

Using the CodeBuild console:

  1. Go to the CodeBuild console and select the project you want to set the credentials for.
  2. Click on the “Edit” button in the “Environment” section.
  3. In the “Environment Variables” section, click on the “Add environment variable” button.
  4. In the “Name” field, enter “AWS_ACCESS_KEY_ID” and in the “Value” field, enter your access key.
  5. Click on the “Add environment variable” button again and enter “AWS_SECRET_ACCESS_KEY” in the “Name” field and your secret key in the “Value” field.
  6. Click on the “Save” button to save your changes.

You can also use IAM roles to give CodeBuild access to other AWS resou


Corrections to the steps above

The steps above will work in a narrow sense, but they teach a pattern AWS advises against. Each problem and its fix is listed below.

Original stepProblemCorrect approach
Run aws configure to set credentialsThis writes ~/.aws/credentials on the machine where you run it. It has no effect on CodeBuild containers. Inside a buildspec it also fails because it waits for interactive input.Attach an IAM service role to the build project. CodeBuild provides temporary credentials for that role to the container automatically.
Add AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY as environment variablesPlaintext environment variables appear in the console and in batch-get-projects API output. The keys are long-lived, and they override the service role in the SDK credential chain.Grant the needed permissions to the service role. Store any other secrets as PARAMETER_STORE or SECRETS_MANAGER variables.
Final sentence is cut off ("other AWS resou")The step that actually solves the problem is missing.IAM roles are the main method, not an alternative. The sections below cover them in full.

Note: If you already put access keys into a CodeBuild project, delete those variables and deactivate and delete the keys in IAM. Anyone with codebuild:BatchGetProjects permission may already have read them.

How CodeBuild gets AWS credentials

Every CodeBuild project has a service role. When a build starts, CodeBuild assumes that role and gives the container temporary, automatically rotated credentials through the container credentials endpoint (the AWS_CONTAINER_CREDENTIALS_RELATIVE_URI variable). The AWS CLI and all AWS SDKs read this endpoint by default. Commands like aws s3 cp or aws ecr get-login-password therefore work without any configuration.

In short: decide what the build needs to do, and grant exactly those permissions to the service role. For credentials that are not from AWS, such as a Docker Hub token, a database password or a third-party API key, store the value in Systems Manager Parameter Store or Secrets Manager. The build then reads it through the role.

Create a service role for CodeBuild

The console can create a role for you when you create a project ("New service role"). Creating it yourself gives you control over the permissions. The trust policy below allows CodeBuild to assume the role:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "Service": "codebuild.amazonaws.com" },
      "Action": "sts:AssumeRole"
    }
  ]
}Code language: JSON / JSON with Comments (json)

The permissions policy below covers CloudWatch Logs (which every build needs), one S3 artifact bucket, and reading the specific parameters and secrets the build uses. Replace the region, account ID and resource names with your own.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"],
      "Resource": "arn:aws:logs:us-east-1:123456789012:log-group:/aws/codebuild/my-app-build*"
    },
    {
      "Effect": "Allow",
      "Action": ["s3:GetObject", "s3:PutObject"],
      "Resource": "arn:aws:s3:::my-artifact-bucket/*"
    },
    {
      "Effect": "Allow",
      "Action": ["ssm:GetParameters"],
      "Resource": "arn:aws:ssm:us-east-1:123456789012:parameter/myapp/prod/*"
    },
    {
      "Effect": "Allow",
      "Action": ["secretsmanager:GetSecretValue"],
      "Resource": "arn:aws:secretsmanager:us-east-1:123456789012:secret:prod/myapp/*"
    }
  ]
}Code language: JSON / JSON with Comments (json)

Create the role and attach the policies with the AWS CLI. Run these commands on your workstation, not inside the build:

aws iam create-role \
  --role-name codebuild-my-app-role \
  --assume-role-policy-document file://trust-policy.json

aws iam put-role-policy \
  --role-name codebuild-my-app-role \
  --policy-name codebuild-my-app-permissions \
  --policy-document file://permissions-policy.jsonCode language: JavaScript (javascript)

Note: If a parameter or secret is encrypted with a customer managed KMS key, the role also needs kms:Decrypt on that key. Secrets encrypted with the AWS managed key do not need this extra permission.

Attach the role to the build project

  1. Open the CodeBuild console, select the project and choose Edit.
  2. In the Environment section, under Service role, choose Existing service role and select codebuild-my-app-role.
  3. Remove any AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY or AWS_SESSION_TOKEN environment variables. If they are present, the CLI uses them instead of the role.
  4. Save the project.

The same change can be made from the CLI:

aws codebuild update-project \
  --name my-app-build \
  --service-role arn:aws:iam::123456789012:role/codebuild-my-app-role

Load secrets in the buildspec

Reference secrets in the env block of buildspec.yml. CodeBuild fetches them with the service role when the build starts and exposes them as environment variables. Their values are masked in build logs.

version: 0.2

env:
  variables:
    APP_ENV: "prod"                          # non-sensitive, plaintext is fine
  parameter-store:
    DB_PASSWORD: "/myapp/prod/db_password"    # SecureString parameter name
  secrets-manager:
    DOCKERHUB_TOKEN: "prod/myapp/dockerhub:token"   # secret-id:json-key

phases:
  pre_build:
    commands:
      - aws sts get-caller-identity
      - echo "$DOCKERHUB_TOKEN" | docker login -u myuser --password-stdin
  build:
    commands:
      - ./deploy.shCode language: PHP (php)

The full Secrets Manager reference format is secret-id:json-key:version-stage:version-id. Leave out the trailing parts to get the current version, or leave out the JSON key to get the whole secret string. If you prefer to keep secret references in the project instead of the buildspec, add environment variables in the console and set Type to Parameter or Secrets Manager. Set the value to the parameter name or secret ID, not the secret itself.

Check which identity the build uses with the output of aws sts get-caller-identity. It should look like this:

{
    "UserId": "AROAEXAMPLEID:AWSCodeBuild-...",
    "Account": "123456789012",
    "Arn": "arn:aws:sts::123456789012:assumed-role/codebuild-my-app-role/AWSCodeBuild-..."
}Code language: JSON / JSON with Comments (json)

If the ARN shows :user/ instead of assumed-role, static keys are still set somewhere in the project or in the buildspec.

Deploying to another AWS account

Use role assumption, not stored keys. In the target account, create a role whose trust policy allows the CodeBuild service role ARN to assume it. Give the CodeBuild service role sts:AssumeRole on that target role. Then use a named profile that sources its credentials from the container:

phases:
  pre_build:
    commands:
      - mkdir -p ~/.aws
      - |
        cat > ~/.aws/config <<'EOF'
        [profile target]
        role_arn = arn:aws:iam::210987654321:role/deploy-from-codebuild
        credential_source = EcsContainer
        EOF
  build:
    commands:
      - aws sts get-caller-identity --profile target
      - aws s3 sync ./dist s3://target-site-bucket --profile targetCode language: PHP (php)

credential_source = EcsContainer tells the CLI to use the CodeBuild role credentials as the base identity and then assume role_arn. The CLI refreshes the temporary credentials automatically.

Common errors and fixes

ErrorCauseFix
... is not authorized to perform: ssm:GetParametersThe service role cannot read the parameterAdd ssm:GetParameters for that parameter ARN to the role
Secrets Manager error or AccessDeniedException on GetSecretValuePermission missing, wrong secret ID or JSON key, or a customer managed KMS key without kms:DecryptCheck the reference format and the role policy, and add KMS permissions if needed
ParameterNotFoundWrong name, or the parameter exists in a different region from the projectUse the full name including the leading /, in the same region
AccessDenied even though the role has the permissionStatic key variables override the roleRemove AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY from the project and the buildspec
Build hangs or fails at aws configureInteractive command with no input availableRemove it. CodeBuild does not need aws configure

Security best practices

  • Use one service role per project or pipeline stage, scoped to specific resource ARNs rather than *.
  • Never put secrets in env: variables or plaintext project variables. Use parameter-store or secrets-manager.
  • Avoid echoing secrets or running env or printenv in build commands. Log masking helps but does not catch transformed values.
  • Builds from pull requests on public repositories can run untrusted code with your role's permissions. Restrict webhook filters and keep those roles minimal.
  • Review the role's activity with CloudTrail, and remove permissions that are no longer used.

For more on cloud security controls, see More Security tutorials and the Cybersecurity and Information Security tutorial collection.

Frequently asked questions

Do I need to run aws configure in CodeBuild?

No. CodeBuild gives the build container temporary credentials for the project's service role, and the AWS CLI and SDKs pick them up automatically. Running aws configure in a buildspec fails because it waits for interactive input.

Is it safe to store AWS access keys as CodeBuild environment variables?

No. Plaintext variables can be read in the console and through the API, and the keys are long-lived. Use the service role for AWS access, and Parameter Store or Secrets Manager variable types for other secrets.

How do I use a Secrets Manager secret in buildspec.yml?

Add it under env: secrets-manager: as VAR_NAME: secret-id:json-key, and grant the service role secretsmanager:GetSecretValue on that secret. CodeBuild injects the value as an environment variable and masks it in logs.

How can a CodeBuild project deploy to a different AWS account?

Create a role in the target account that trusts the CodeBuild service role, and allow sts:AssumeRole on it. In the build, use a CLI profile with role_arn and credential_source = EcsContainer.

How do I check which credentials my build is using?

Run aws sts get-caller-identity in the build. The ARN should show assumed-role/<your-codebuild-role>. If it shows an IAM user, static keys are overriding the role.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

AWS CLI Credentials Setup: Configure, Verify, and Secure Access

Learn how to configure AWS credentials with the AWS CLI, verify your identity, and understand where credentials are stored. This updated guide also compares profiles, environment variables, and role-based access.

Read More

AWS Tutorials: How to activate AWS EC2 Session Manager?

What is AWS Session Manager? AWS Session Manager is a managed service provided by Amazon Web Services (AWS) that enables secure and seamless access to instances in…

Read More

AWS IAM Policy to Protect SES SMTP

You can lock down Amazon SES SMTP credentials with an IAM policy on the IAM user that owns them. A Deny on aws:SourceIp limits which IP addresses…

Read More

AWS Tutorials: AWS CodeBuild – Buildspec code for creating AMI from running instances

This page has an AWS CodeBuild buildspec that finds every running EC2 instance tagged environment=uat and creates an AMI from each one with the AWS CLI. It…

Read More

AWS Tutorials: How to Shutdown (Stop / Start) ElastiCache Service in AWS

Amazon ElastiCache has no stop or start button. You keep paying for every node until you shrink or delete it. This guide shows the two ways to…

Read More

AWS Tutorials: AWS S3 Commands Example

The aws s3 commands in the AWS CLI handle everyday Amazon S3 work: creating and removing buckets, uploading and downloading files, moving objects and syncing whole directories….

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x