buildspec-with-ssm

Securely manage parameters in your AWS CodeBuild buildspec using SSM. Learn how to access Docker Hub credentials and ECR for automated deployments.

Buildspec With Ssm

This buildspec demonstrates how to securely manage sensitive information, such as Docker Hub credentials, using AWS Systems Manager Parameter Store (SSM) within an AWS CodeBuild environment. This approach enhances security by avoiding hardcoding credentials directly into your build scripts.

Buildspec Configuration

The following YAML configuration outlines the build process, including environment setup, authentication with Docker Hub and ECR, building and tagging Docker images, and pushing them to the respective repositories.

version: 0.2

env:
  environment:
    aws_region: "eu-west-1"
    container_name: "test"
    repository_url: "xxxxxxxxxxxx"
  parameter-store:
    dockerhub_username: "/devops/dev/DOCKERHUB_USERNAME"
    dockerhub_password: "/devops/dev/DOCKERHUB_PASSWORD"

phases:
  pre_build:
    commands:
      - echo logging into Dockerhub as upstream not yet using gallery.ecr.aws
      - docker login -u $dockerhub_username -p $dockerhub_password
      - echo logging into ECR
      - $(aws ecr get-login --region $aws_region --no-include-email)
      - REPOSITORY_URI=${repository_url}
      - IMAGE_TAG=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7)
  build:
    commands:
      - echo build started on $(date)
      - docker build -t $REPOSITORY_URI:latest .
      - docker tag $REPOSITORY_URI:latest $REPOSITORY_URI:$IMAGE_TAG
  post_build:
    commands:
      - echo build completed on $(date)
      - echo pushing the docker images
      - docker push $REPOSITORY_URI:latest
      - docker push $REPOSITORY_URI:$IMAGE_TAG
      - echo writing image definitions file for deployment
      - printf '[{"name":"$container_name","imageUri":"%s"}]' $REPOSITORY_URI:$IMAGE_TAG > imagedefinitions.json
    
artifacts:
  files: imagedefinitions.json

Key Components Explained

Environment Variables

The env section defines environment variables, including the AWS region, container name, and repository URL. Critically, it also specifies the parameters to retrieve from SSM Parameter Store.

SSM Parameter Store Integration

The parameter-store section maps environment variables to SSM parameters. This allows CodeBuild to securely retrieve sensitive information at runtime.

Build Phases

The phases section outlines the build process:

  • pre_build: Logs into Docker Hub and ECR using credentials retrieved from SSM.
  • build: Builds and tags the Docker image.
  • post_build: Pushes the Docker images to Docker Hub and ECR, and creates an imagedefinitions.json file for deployment.

Artifacts

The artifacts section specifies the files to be included in the build output, in this case, the imagedefinitions.json file.

External Resources