CodeBuild project using an AWS managed key

Choose an AWS managed or customer-managed key according to the key-policy requirements for CodeBuild artifacts.

Description

CodeBuild's encryption_key selects the KMS key for build output artifacts. The default is the AWS managed key for S3. Choose a customer-managed key when you need to control its policy or lifecycle.

Potential impact

Missing S3 or KMS permissions can prevent CodeBuild from uploading artifacts or authorized readers from downloading them.

Remediation

Set encryption_key to the required key ARN or alias. Limit the service role's write access and readers' S3 and KMS permissions to what they need. Run a build, check the key on the output object, and test a download. Configure protection for caches, logs and build secrets separately.

Examples

The excerpts omit the project's source, build environment and artifact settings. Supply those settings and use existing roles and keys.

AWS managed key

hcl
data "aws_kms_key" "by_alias" {
  key_id = "alias/aws/s3"
}

resource "aws_codebuild_project" "example" {
  name           = "project-cloudrail-test"
  service_role   = aws_iam_role.codebuild.arn
  encryption_key = data.aws_kms_key.by_alias.arn
}

alias/aws/s3 selects the AWS managed key for S3.

Customer-managed key

hcl
data "aws_kms_key" "by_alias" {
  key_id = "alias/myAlias"
}

resource "aws_codebuild_project" "example" {
  name           = "project-cloudrail-test"
  service_role   = aws_iam_role.codebuild2.arn
  encryption_key = data.aws_kms_key.by_alias.arn
}

Replace alias/myAlias with your customer-managed key alias. The service role also changes to codebuild2. Verify its access to the key and the artifact bucket.

References