> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Demo Secrets in CodeBuild Using Secrets Manager and SSM Parameter Store

> Guide to managing and injecting secrets into AWS CodeBuild using AWS Secrets Manager and SSM Parameter Store, including rotation, cost tradeoffs, buildspec usage, and IAM/KMS permissions.

Welcome back. In this hands‑on lesson we cover secrets management for SDLC automation—specifically how to store, retrieve, and use secrets in AWS CodeBuild using AWS Secrets Manager and AWS Systems Manager Parameter Store (SSM). You’ll learn when to choose each service, key differences (cost, rotation, encryption), how to configure CodeBuild to retrieve them, and the required IAM/KMS permissions.

This guide focuses on practical patterns for build-time secret injection into CodeBuild. Use Secrets Manager for credentials needing rotation and Parameter Store for many configuration values where cost or simple typing (String, StringList) matters. See AWS docs for deeper reference: [Secrets Manager](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html) and [Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html).

## Decision framework: Secrets Manager vs Parameter Store

| Feature | AWS Secrets Manager | AWS Systems Manager Parameter Store |
| - | -: | - |
| Primary purpose | Secret lifecycle management & rotation | General parameter/config storage |
| Types supported | Secret (JSON key/value) | `String`, `StringList`, `SecureString` |
| Automatic rotation | Built-in rotation (RDS, DocumentDB, etc.) and Lambda-based custom rotation | No built-in rotation automation |
| Cost | Per-secret monthly charge | Standard tier often free; advanced tier billed |
| Best use case | Credentials that require rotation and per-secret lifecycle | Many configuration values, feature flags, tokens |
| Cross-account encrypted access | Requires customer-managed KMS key + key policy | Prefer customer-managed KMS key for cross-account decrypts |

Key guidance:

* Use Secrets Manager when you require built‑in rotation or secret lifecycle management.
* Use Parameter Store for many simpler configuration values, `StringList` needs, or when minimizing costs.
* For cross-account retrieval of encrypted values, plan a customer-managed KMS key and include explicit key policies allowing the consuming role/account.

## Secrets Manager — creating a secret

![A screenshot of the AWS Secrets Manager "Store a new secret" page showing the "Choose secret type" step with "Credentials for Amazon RDS database" selected, and credential fields (username and a masked password) displayed.](https://mintcdn.com/kodekloud-c4ac6d9a/deef86LW8w1XLb8X/images/AWS-Certified-DevOps-Engineer-Professional/Domain-1-SDLC-Automation/Demo-Secrets-in-CodeBuild-Using-Secrets-Manager-and-SSM-Parameter-Store/aws-secretsmanager-rds-credentials-form.jpg?fit=max\&auto=format\&n=deef86LW8w1XLb8X\&q=85\&s=0520df9a6fd9ce4c4dd7301606b6f652)

When creating a secret in Secrets Manager:

* Choose the secret type (RDS, Redshift, DocumentDB, other, or a custom key/value secret).
* For API/OAuth tokens or container registry credentials, pick “Other type of secret” and store JSON key/value pairs such as `username`, `password`, `registry`.
* Secrets Manager stores secrets encrypted with KMS by default. For cross-account access, use a customer-managed KMS key and grant access via the key policy.

You can store arbitrary key/value pairs; Secrets Manager will persist them as JSON. This lets consumers (like CodeBuild) reference specific fields within the secret.

![A screenshot of the AWS Secrets Manager "Store a new secret" screen showing key/value pairs for username (mycompany), password (SuperSecretPassword123!), and registry (docker.io). The page also shows an encryption key selection and Next/Cancel buttons.](https://mintcdn.com/kodekloud-c4ac6d9a/deef86LW8w1XLb8X/images/AWS-Certified-DevOps-Engineer-Professional/Domain-1-SDLC-Automation/Demo-Secrets-in-CodeBuild-Using-Secrets-Manager-and-SSM-Parameter-Store/aws-secrets-manager-store-secret-credentials.jpg?fit=max\&auto=format\&n=deef86LW8w1XLb8X\&q=85\&s=83309987a0bb077844d557ec92f201c2)

Name and document secrets with a clear convention: e.g., `prod/AppBeta/Mysql` or `devops-020-130/docker-credentials`.

![A screenshot of the AWS Secrets Manager "Configure secret" page with the Secret name field filled as "prod/AppBeta/Mysql" and an optional description noting access to the MySQL production database for AppBeta. The left sidebar shows the multi-step wizard (Choose secret type, Configure secret, Configure rotation, Review).](https://mintcdn.com/kodekloud-c4ac6d9a/deef86LW8w1XLb8X/images/AWS-Certified-DevOps-Engineer-Professional/Domain-1-SDLC-Automation/Demo-Secrets-in-CodeBuild-Using-Secrets-Manager-and-SSM-Parameter-Store/aws-secrets-configure-prod-appbeta-mysql.jpg?fit=max\&auto=format\&n=deef86LW8w1XLb8X\&q=85\&s=f8a4592008daf7ab15f71dc8cb69fd32)

### Rotation (Secrets Manager)

Secrets Manager supports scheduled automatic rotation (configurable interval, up to 365 days) and can execute a Lambda rotation function for custom secrets (e.g., Docker Hub tokens). For built-in services (RDS), rotation often uses prebuilt methods.

![Screenshot of the AWS Secrets Manager "Store a new secret" page showing rotation schedule settings. The Start day is set to "First Monday" with start time 21 and a 4h window, and the Lambda rotation function "WatcherLambda" is selected.](https://mintcdn.com/kodekloud-c4ac6d9a/deef86LW8w1XLb8X/images/AWS-Certified-DevOps-Engineer-Professional/Domain-1-SDLC-Automation/Demo-Secrets-in-CodeBuild-Using-Secrets-Manager-and-SSM-Parameter-Store/aws-secrets-rotation-first-monday-watcherlambda.jpg?fit=max\&auto=format\&n=deef86LW8w1XLb8X\&q=85\&s=bf7400973473a1adf966506abbf115ac)

### Example: retrieving a secret with Python (Boto3)

This snippet returns the JSON secret string stored in Secrets Manager.

```python theme={null}
import boto3
from botocore.exceptions import ClientError


def get_secret():
    secret_name = "devops-020-130/docker-credentials"
    region_name = "us-east-1"

    # Create Secrets Manager client
    session = boto3.session.Session()
    client = session.client(service_name="secretsmanager", region_name=region_name)

    try:
        resp = client.get_secret_value(SecretId=secret_name)
    except ClientError:
        # See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
        raise
    else:
        # For key/value secrets, the result returns a JSON string in "SecretString"
        secret_string = resp.get("SecretString")
        return secret_string
```

## Parameter Store — creating parameters

![A screenshot of the AWS Systems Manager Parameter Store console showing the "My parameters" list with entries like /devops-020-130/api-key, their types (SecureString, String, StringList), tiers and last-modified timestamps. The top bar shows console controls and buttons such as "Create parameter" and "Manage settings."](https://mintcdn.com/kodekloud-c4ac6d9a/deef86LW8w1XLb8X/images/AWS-Certified-DevOps-Engineer-Professional/Domain-1-SDLC-Automation/Demo-Secrets-in-CodeBuild-Using-Secrets-Manager-and-SSM-Parameter-Store/aws-ssm-parameter-store-list.jpg?fit=max\&auto=format\&n=deef86LW8w1XLb8X\&q=85\&s=175570468549e4b238e3db5c8838c652)

Parameter Store supports:

* `String` — plain text values,
* `StringList` — comma-separated lists,
* `SecureString` — encrypted values (KMS-backed).

Standard tier is sufficient for many uses; advanced tier supports larger sizes and higher throughput but incurs cost.

When storing `SecureString` values in a multi-account environment, use a customer-managed KMS key and set the key policy to allow the consuming IAM role(s) to decrypt.

To keep parameter paths organized, adopt a prefix pattern like `/devops-020-130/codebuild/npm-auth-token`.

![Screenshot of the AWS Systems Manager Parameter Store "Create parameter" form showing the Name field filled with "/devops-020-130/codebuild/npm-auth-token" and the Advanced tier selected. The Description, Tier and Type options are also visible on the page.](https://mintcdn.com/kodekloud-c4ac6d9a/deef86LW8w1XLb8X/images/AWS-Certified-DevOps-Engineer-Professional/Domain-1-SDLC-Automation/Demo-Secrets-in-CodeBuild-Using-Secrets-Manager-and-SSM-Parameter-Store/ssm-parameter-create-advanced-tier-npm-auth-token.jpg?fit=max\&auto=format\&n=deef86LW8w1XLb8X\&q=85\&s=cf6cdba0f6ac78dc5326934122c85705)

After creation the parameter will appear in the list and be available for retrieval by authorized principals.

![Screenshot of the AWS Systems Manager Parameter Store console listing parameters (e.g., /devops-020-130/api-key, build-environment, npm-auth-token) with their tiers, types (SecureString, String, StringList) and last-modified timestamps. The top bar shows a notification about available upgrades and a "Create parameter" button.](https://mintcdn.com/kodekloud-c4ac6d9a/deef86LW8w1XLb8X/images/AWS-Certified-DevOps-Engineer-Professional/Domain-1-SDLC-Automation/Demo-Secrets-in-CodeBuild-Using-Secrets-Manager-and-SSM-Parameter-Store/aws-ssm-parameter-store-listing.jpg?fit=max\&auto=format\&n=deef86LW8w1XLb8X\&q=85\&s=6a5fe9e07f1f18b6b267874270894f85)

## BuildSpec: injecting Secrets Manager and Parameter Store values into CodeBuild

CodeBuild natively supports referencing both SSM Parameter Store and Secrets Manager secrets as environment variables in your `buildspec.yml`. Use the secret/parameter identifiers as string keys in the `secrets-manager` and `parameter-store` sections — CodeBuild handles retrieval and injection at build runtime.

```yaml theme={null}
version: 0.2

env:
  shell: bash
  variables:
    BUILD_ENVIRONMENT: "demo"
    PYTHONPATH: "./src"
    ENABLE_COVERAGE: "true"
  parameter-store:
    NOTIFICATION_TOPIC: "/devops-course/devops-020-100/notification-topic"
    BUILD_ENV_CONFIG: "/devops-course/devops-020-100/build-environment"
  secrets-manager:
    DOCKER_USERNAME: "devops-020-100/docker-hub:username"
    DOCKER_PASSWORD: "devops-020-100/docker-hub:password"
  exported-variables:
    - BUILD_ENVIRONMENT
    - CODEBUILD_BUILD_NUMBER

phases:
  install:
    runtime-versions:
      python: 3.11
      nodejs: 18
    commands:
      - echo "=== INSTALL PHASE ==="
      - echo "Installing build dependencies..."
      - pip install --upgrade pip
      - pip install -r requirements.txt
  pre_build:
    on-failure: CONTINUE
    commands:
      - echo "=== PRE_BUILD PHASE ==="
      - echo "Running code quality checks..."
      - flake8 src/ --count --select=E9,F63,F7,F82 --show-source
      - echo "Validating configuration..."
      - python -c "import yaml; yaml.safe_load(open('config.yml'))"
      - echo "Environment: $BUILD_ENVIRONMENT"
      - echo "Notification Topic: $NOTIFICATION_TOPIC"
  build:
    commands:
      - echo "=== BUILD PHASE ==="
      - echo "Build number: $CODEBUILD_BUILD_NUMBER"
      - echo "Commit: $CODEBUILD_RESOLVED_SOURCE_VERSION"
      - echo "Build started on $(date)"
      - mkdir -p dist reports
      - pytest tests/ --cov=src --cov-report=xml --junitxml=test-results.xml
      - python setup.py sdist bdist_wheel
      - echo "Build completed on $(date)"
  post_build:
    commands:
      - echo "=== POST_BUILD PHASE ==="
      - echo "Build status: $CODEBUILD_BUILD_SUCCEEDING"
      - |
        if [ "$CODEBUILD_BUILD_SUCCEEDING" = "1" ]; then
          echo "Build successful - preparing artifacts"
        else
          echo "Build failed - check logs for errors"
        fi
      - |
        echo "{\"build\": \"$CODEBUILD_BUILD_NUMBER\", \"commit\": \"$CODEBUILD_RESOLVED_SOURCE_VERSION\"}" > metadata.json

reports:
  pytest-reports:
    files:
      - "test-results.xml"
    file-format: JUNITXML
```

Notes on the `buildspec.yml` above:

* For Secrets Manager JSON secrets, reference fields using `secret-name:jsonKey`. Example: `devops-020-100/docker-hub:username`.
* For Parameter Store, provide the parameter path (for example, `/devops-course/devops-020-100/build-environment`).
* Exported variables are available to later phases in the same build. To pass values to downstream pipeline stages, configure the pipeline to capture and forward them.

## Parameter types and sample usage

* `String` — single value configuration (e.g., API endpoint).
* `StringList` — comma-separated lists useful for feature flags or lists of services.

Example: create a `StringList` parameter `/devops-020-130/feature-flags` with the value `ENABLE_LOGGING,ENABLE_METRICS,ENABLE_TRACING`.

![A screenshot of the AWS Systems Manager Parameter Store showing the parameter /devops-020-130/feature-flags with details (ARN, tier Standard, type StringList) and value ENABLE\_LOGGING,ENABLE\_METRICS,ENABLE\_TRACING. The page also displays last-modified info and Edit/Delete buttons.](https://mintcdn.com/kodekloud-c4ac6d9a/deef86LW8w1XLb8X/images/AWS-Certified-DevOps-Engineer-Professional/Domain-1-SDLC-Automation/Demo-Secrets-in-CodeBuild-Using-Secrets-Manager-and-SSM-Parameter-Store/aws-ssm-parameter-feature-flags.jpg?fit=max\&auto=format\&n=deef86LW8w1XLb8X\&q=85\&s=2e35ca61cb3d5c74fbfac5d51110398f)

## Permissions — CodeBuild service role

CodeBuild must have IAM permissions to get Parameter Store parameters and Secrets Manager secrets. For values encrypted with a customer-managed KMS key, the CodeBuild role also needs KMS permissions. Below is a representative minimal IAM policy demonstrating the required actions.

```json theme={null}
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "S3ArtifactAccess",
      "Effect": "Allow",
      "Action": [
        "s3:GetObjectVersion",
        "s3:GetObject",
        "s3:GetBucketLocation",
        "s3:GetBucketAcl"
      ],
      "Resource": [
        "arn:aws:s3:::devops-020-130-artifacts-e984bb14/*",
        "arn:aws:s3:::devops-020-130-artifacts-e984bb14"
      ]
    },
    {
      "Sid": "SecretsManagerAccess",
      "Effect": "Allow",
      "Action": "secretsmanager:GetSecretValue",
      "Resource": "arn:aws:secretsmanager:us-east-1:598274344262:secret:devops-020-130/*"
    },
    {
      "Sid": "ParameterStoreAccess",
      "Effect": "Allow",
      "Action": [
        "ssm:GetParameters",
        "ssm:GetParameter"
      ],
      "Resource": "arn:aws:ssm:us-east-1:598274344262:parameter/devops-020-130/*"
    },
    {
      "Sid": "KMSDecryptForSecretsAndParameters",
      "Effect": "Allow",
      "Action": [
        "kms:DescribeKey",
        "kms:Decrypt"
      ],
      "Resource": "*",
      "Condition": {
        "StringEquals": {
          "kms:ViaService": [
            "secretsmanager.us-east-1.amazonaws.com",
            "ssm.us-east-1.amazonaws.com"
          ]
        }
      }
    }
  ]
}
```

Key permission notes:

* If using a customer-managed KMS key, the key policy must explicitly allow the CodeBuild role (or the AWS account role that calls decrypt) to perform `kms:Decrypt` and `kms:DescribeKey`.
* If you rely on AWS-managed KMS keys within the same account, extra KMS permissions may not be required. For cross-account decrypts, you must use customer-managed keys and update key policies accordingly.
* If a build fails with `AccessDeniedException` while reading `SecureString` or Secrets Manager secrets, verify both the IAM role policy and the KMS key policy.

For cross-account secret/parameter retrieval, do not rely on AWS-managed KMS keys. Plan a customer-managed KMS key with a key policy granting explicit decrypt permissions to the consuming principals in other accounts.

## Quick reference: when to choose which service

| Scenario | Recommended service |
| - | - |
| You need automatic credential rotation for a database or API key | `Secrets Manager` |
| You need to store many simple configuration values and want cost savings | `Parameter Store (Standard)` |
| You need comma-separated lists for feature toggles | `Parameter Store (StringList)` |
| You have multi-account builds that need encrypted secret access | `Secrets Manager` or `Parameter Store` with customer-managed KMS key + key policy |

## Links and further reading

* [AWS Secrets Manager User Guide](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html)
* [AWS Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html)
* [AWS CodeBuild Environment Variables and Secrets](https://docs.aws.amazon.com/codebuild/latest/userguide/build-spec-ref.html#build-spec.env)

Thanks for reading.

> **[Watch Video](https://learn.kodekloud.com/user/courses/aws-certified-devops-engineer-professional/module/199ecdf9-a58f-4c2d-b9c9-eac36de111cd/lesson/0cd79e64-860b-4dda-a8f8-abd33452bff7)**

> **[Practice Lab](https://learn.kodekloud.com/user/courses/aws-certified-devops-engineer-professional/module/199ecdf9-a58f-4c2d-b9c9-eac36de111cd/lesson/c87c5ab8-9210-4d03-813a-fd3cf17ce29e)**


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.