← Back to writing

Michał Pasierbski

🔑 How to handle secrets in AWS Codebuild

A guide to securely managing secrets in AWS CodeBuild pipelines.

Originally published on Medium

Title card reading 'How to handle secrets in AWS Codebuild' over a pattern of AWS cube icons

Problem

You have a CodeBuild project that build you static site from headless CMS and you need the access token to call the API. You are smart enough to know that hardcoding it directly in source code is not a good idea.

Environment variables

You could set secrets as environment variables directly in CodeBuild. This works but has couple downsides:

Secrets manager

AWS has a service to securely store passwords, tokens, credentials or any other sensitive data — AWS Secrets Manager. Fortunately Secrets Manager integrates seamlessly with CodeBuild through a buildspec file.

Values from Secrets Manager can be mapped out to environment variables that will be available through all build project phases.

env:
  secrets-manager:
    ENV_VARIABLE_NAME: secrets-name-or-arn:key

CodeBuild can also resolve secret-name-or-arn from environment variable passed to build projects itself, which come in very handy when working with IaC (Infrastructure as code) library, like terraform or aws-cdk.

resource "aws_secretsmanager_secret" "secrets" {
  name = "some-name"
}
resource "aws_codebuild_project" "build" {
  environment {
    environment_variable {
      name = "SECRETS_ID"
      value = "${aws_secretsmanager_secret.secrets.arn}"
    }
  }
}

Here is a sample buildspec file:

version: 0.2
env:
  secrets-manager:
    NPM_REGISTRY_TOKEN: $SECRETS_ID:NPM_REGISTRY_TOKEN
    SUPER_SECRET_PASSWORD: arn:aws:secretsmanager:eu-west-1:123456789:secret:secrets-name:PASSWORD
    OTHER_SECRET_PASSWORD: secrets-name:OTHER_PASSWORD
phases:
  install:
    runtime-versions:
      nodejs: 10
    commands:
    - npm install
  build:
    commands:
    - npm run build

For more details about buildspec check official documentation.

NOTE: Of course IAM role associated with CodeBuild project has to have sufficient permissions to access secrets