Skip to content

CloudFormation for AWS CodeBuild Deployment

aivf_baisheng edited this page Sep 5, 2025 · 6 revisions

image

Overview

Welcome to the CloudFormation Template Guide for deployment of Moonshot in AWS CodeBuild.

This guide aims to provide step-by-step instructions on how to set up and configure the CloudFormation Template to deploy Moonshot in AWS CodeBuild.

This serves as an alternative method to set up your AWS infrastructure and deploy Moonshoot in your CodeBuild.


What is CloudFormation Template?

The CloudFormation Template is a blueprint that provides a written set of instructions to Amazon Web Services (AWS) to create and configure your CodeBuild automatically without having to manually create CodeBuild yourself.


Benefits of CloudFormation Template

  • Saves Time and Effort
    Automatically sets up CodeBuild and related resources in minutes, eliminating repetitive manual work.

  • Ensures Consistency
    Every deployment uses the exact same configuration, reducing human error and avoiding environment drift.

  • Supports Infrastructure as Code (IaC)
    The setup is written in code (YAML/JSON), which can be version-controlled, audited, and reused across projects.

  • Simplifies Replication Across Environments
    Easily replicate the same CodeBuild setup in different environments (development, testing, production) without reconfiguration.

Enables Automation in CI/CD Pipelines
CloudFormation can be triggered as part of automated workflows, making it easier to integrate with DevOps pipelines.

  • Improves Reliability and Accuracy
    Reduces the chance of misconfigurations compared to manual setups through the AWS Console.

  • Makes Rollbacks Easy
    You can revert the infrastructure to a previous known state if something goes wrong.

  • Centralized Management
    Manage all your infrastructure, including CodeBuild, from a single template, which is helpful for large projects and teams.

  • Reduces Dependency on Manual Knowledge
    Anyone with access to the template can deploy the setup without needing to know all the steps manually.


Steps to Build & Deploy CloudFormation Template on AWS

  1. Create cloudformation.yaml.
  2. Add the following code inside the file and save it:
AWSTemplateFormatVersion: '2010-09-09'
Description: CloudFormation template to integrate Moonshot with AWS CodeBuild using GHCR image and secure OpenAI API key

Parameters:
  SourceBucketName:
    Type: String
    Description: Name of the S3 bucket containing moonshot.zip
  ArtifactBucketName:
    Type: String
    Description: S3 bucket for storing CodeBuild output artifacts
  OpenAIAPIKeyParameterName:
    Type: String
    Default: /moonshot/openai_api_key
    Description: Name of the SSM Parameter Store SecureString for the OpenAI API key
  CloudWatchLogGroupName:
    Type: String
    Default: /aws/codebuild/moonshot-logs
    Description: Name of the CloudWatch log group for storing CodeBuild logs

Resources:

  CodeBuildServiceRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: CodeBuildMoonshotServiceRole
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: codebuild.amazonaws.com
            Action: sts:AssumeRole
      Policies:
        - PolicyName: CodeBuildMoonshotPolicy
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - logs:CreateLogGroup
                  - logs:CreateLogStream
                  - logs:PutLogEvents
                  - s3:GetObject
                  - s3:PutObject
                  - codebuild:BatchGetBuilds
                  - codebuild:StartBuild
                  - codebuild:BatchGetProjects
                  - ssm:GetParameters
                Resource: "*"

              - Effect: Allow
                Action:
                  - ecr:GetAuthorizationToken
                  - ecr:BatchCheckLayerAvailability
                  - ecr:GetDownloadUrlForLayer
                  - ecr:BatchGetImage
                Resource: "*"


  MoonshotLogGroup:
    Type: AWS::Logs::LogGroup
    Properties:
      LogGroupName: !Ref CloudWatchLogGroupName
      RetentionInDays: 7

  MoonshotCodeBuildProject:
    Type: AWS::CodeBuild::Project
    Properties:
      Name: Moonshot
      Description: CodeBuild project to run Moonshot AI safety tests
      Source:
        Type: S3
        Location: !Sub "${SourceBucketName}/moonshot.zip"
      Artifacts:
        Type: S3
        Location: !Ref ArtifactBucketName
        NamespaceType: BUILD_ID
      Environment:
        Type: LINUX_CONTAINER
        ComputeType: BUILD_GENERAL1_SMALL
        Image: 988448834162.dkr.ecr.ap-southeast-2.amazonaws.com/moonshot/ecrdraft1
        PrivilegedMode: true
        EnvironmentVariables:
          - Name: OPENAI_API_KEY
            Type: PARAMETER_STORE
            Value: !Ref OpenAIAPIKeyParameterName
          - Name: MS_TEST_CONFIG_PATH
            Type: PLAINTEXT
            Value: "/app/data/test_configs/tests.yaml"
          - Name: MS_CONFIG_PATH
            Type: PLAINTEXT
            Value: "/app/moonshot_config.yaml"
        ImagePullCredentialsType: SERVICE_ROLE
      ServiceRole: !GetAtt CodeBuildServiceRole.Arn
      LogsConfig:
        CloudWatchLogs:
          Status: ENABLED
          GroupName: !Ref CloudWatchLogGroupName

Outputs:
  CodeBuildProjectName:
    Description: "Name of the Moonshot CodeBuild project"
    Value: !Ref MoonshotCodeBuildProject
  1. Go to https://aws.amazon.com/ and log in to your AWS account.

  2. Search for Parameter Store and click on it. image

  3. Click on Create Parameter (This parameter is used to store your OpenAI API keys securely). image

Tip

You can do the same for the API keys of other frontier models.

  1. Fill in the necessary details (Name, Description, Tier, Type, KMS Key Source, KMS Key ID and Value of your API Key), and select SecureString under Type. image

  2. The created parameter for your OpenAI API key would look like this: image

  3. Create buildspec.yaml.

  4. Add the following code inside the file and save it:

version: 0.2

phases:
  pre_build:
    commands:
      - echo "Setting working directory to /app"
      - cd /app
  build:
    commands:
      - export MS_TEST_CONFIG_PATH=${MS_TEST_CONFIG_PATH}
      - export MS_CONFIG_PATH=${MS_CONFIG_PATH}
      - moonshot run <run_id> <test_id> <endpoint_id>

artifacts:
  files:
    - "*"
  base-directory: "/app/data/results"

Tip

To use Moonshot for your use case, you should configure MS_TEST_CONFIG_PATH and MS_CONFIG_PATH to point to your my_tests.yaml and my_moonshot_config.yaml stored in your S3.

Tip

You can refer to this guide for more information on Moonshot's command to run tests.


  1. Zip the buildspec.yaml into a zipped file -- moonshot.zip.

  2. Search for S3 and click on it. image

  3. Create two S3 Buckets: a. First S3 Bucket (s3-moonshot-bucket) to upload the moonshot.zip file. b. Second S3 Bucket (s3-moonshot-artifact-bucket) to store the output console logs after running the build for CodeBuild. image

12a. Let’s create our First S3 Bucket (s3-moonshot-bucket) and upload the moonshot.zip file i). Fill in the necessary details image image image image

ii). Click on s3-moonshot-bucket. iii). Click on Upload. image

iv). Click on Add files and upload the moonshot.zip file. image image

v). Scroll to the bottom of the page and click on Upload. image image

12b. Let’s create our Second S3 Bucket (s3-moonshot-artifact-bucket) to store the output console logs after running the build for CodeBuild i). Fill in the necessary details image image image image

  1. Search for CloudFormation and click on it image

  2. Select With new resources (standard) under Create stack. image

  3. Select Choose an existing template.

  4. Select Upload a template file.

  5. Click on Choose file to upload your CloudFormation Template. image

  6. Upload the CloudFormation Template and Click on Next image

  7. Fill in moonshot-cloudformation as the Stack Name.

  8. Enter the first S3 Bucket (s3-moonshot-bucket) as the SourceBucketName.

  9. Enter the second S3 Bucket (s3-moonshot-artifact-bucket) as the ArtifactBucketName.

  10. Click on Next. image

  11. Scroll to the bottom of the page to acknowledge.

  12. Click on Next. image

  13. Scroll to the bottom of the page and click on Submit. image

  14. Upon clicking on Submit, you will see that the moonshot-cloudformation is the CREATE_IN_PROGRESS status. image

  15. After a short while, you should see that the moonshot-cloudformation has been successfully created. image

  16. Search for CodeBuild and click on it. image

  17. You will see that the CodeBuild project to run Moonshot has been automatically created using the moonshot-cloudformation. image

  18. Click on the Moonshot project.

  19. Click on Start build. image

  20. Click on the Phase details tab.

  21. You will see that the Status of every stage of the Build has succeeded.

  22. Overall, the Build Status has succeeded. image

  23. To see the console logs of the build for this Moonshot project, click on the Build logs tab.


Congratulations! You have successfully set up your AWS CodeBuild to deploy and run Moonshot.

Clone this wiki locally