Skip to content

CodebuildBuilder

Purpose

The CodeBuildBuilder is a concrete implementation of the AbstractAWSResourceBuilder designed to create AWS CodeBuild projects for continuous integration and delivery pipelines. This builder creates production-ready build projects with comprehensive VPC integration, ECR repository access, automated scheduling, immediate build triggers, and organizational security standards for container image builds and AMI creation workflows.

Dependencies

This builder requires the following AWS resources and permissions:

Required AWS Permissions

  • CodeBuild Management: Create, configure, and manage CodeBuild projects and pipeline projects
  • VPC Operations: Deploy CodeBuild projects within VPC for secure network access
  • ECR Integration: Pull and push container images for build processes
  • IAM Role Management: Assign service roles and configure cross-account access policies
  • EventBridge Rules: Create scheduled build triggers and automation workflows
  • S3 Operations: Store build logs and artifacts in designated S3 buckets
  • Custom Resources: Create AWS SDK calls for immediate build triggering
  • Resource Tagging: Apply organizational tags to CodeBuild resources for governance

Foundation Dependencies

  • VPC Infrastructure: Existing VPC with private subnets for secure build execution
  • IAM Roles: Pre-configured CodeBuild service roles with appropriate permissions
  • ECR Repositories: Container registries for storing build artifacts and base images
  • Git Repositories: Source code repositories (currently CodeCommit support only)
  • Cross-Account Roles: DevOps roles for multi-environment pipeline access
  • Environment Configuration: Account and region mappings for multi-environment deployments
  • Naming Standards: Organizational resource naming conventions following company patterns
  • Tagging Strategy: Consistent tagging for cost allocation, security policies, and operational categorization

Configuration

The builder validates all configuration through the CodebuildConfig model, which becomes the authoritative source for all CodeBuild project settings.

CDK Configuration Structure

PROJECT Type Configuration

{
  "usage": "AMI",
  "vpc": "vpc_object",
  "role": "iam_role_object", 
  "codebuild_type": "PROJECT",
  "buildspec_path": "buildspec.yml",
  "ecr_repo": "ecr_repository_object",
  "git_provider": "CODECOMMIT",
  "git_repo": "codecommit_repository_object",
  "git_branch": "main",
  "privileged": true,
  "compute_type": "MEDIUM",
  "build_image": "AMAZON_LINUX_2_5",
  "create_build_scheduler": false,
  "build_after_deployment": true,
  "usage_context": "container-builds",
  "logs_bucket": "s3_bucket_object"
}

PIPELINE_PROJECT Type Configuration

{
  "usage": "LIQUIBASE",
  "vpc": "vpc_object",
  "role": "iam_role_object",
  "codebuild_type": "PIPELINE_PROJECT", 
  "buildspec_path": "ci/buildspec.yml",
  "pipeline_type": "CI_CD",
  "ami_ecr_repo": "ami_ecr_repository_object",
  "env_vars": {
    "NODE_ENV": "production_build_env_var",
    "API_URL": "api_url_build_env_var"
  },
  "privileged": false,
  "compute_type": "LARGE",
  "logs_bucket": "logs_s3_bucket_object",
  "usage_context": "pipeline-integration"
}

Configuration Parameters

Parameter Mandatory Type Default Description
usage Yes Usage Target usage of the codebuild project
vpc Yes ec2.IVpc VPC for CodeBuild project execution and network security
role Yes iam.IRole IAM role with CodeBuild permissions and ECR access
codebuild_type Yes CodebuildType PROJECT (standalone) or PIPELINE_PROJECT (CI/CD integration)
buildspec_path Yes str Path to buildspec.yml file in the repository
ecr_repo Yes when PROJECT ecr.IRepository None ECR repository for container image storage
git_provider Yes when PROJECT GitProvider None Git provider (currently CODECOMMIT only)
git_repo Yes when PROJECT codecommit.IRepository None Git repository containing source code
git_branch Yes when PROJECT str None Git branch to build from (e.g., "main", "develop")
pipeline_type Yes when PIPELINE_PROJECT PipelineType None Pipeline integration type (CI_CD, BUILD_ONLY, etc.)
ami_ecr_repo No ecr.IRepository None ECR repository for custom AMI builds
env_vars No Dict[str, BuildEnvironmentVariable] None Environment variables for build execution
usage_context No str None Context identifier for project naming (e.g., "api", "frontend")
logs_bucket No s3.IBucket None S3 bucket for storing build logs
security_groups No List[ec2.ISecurityGroup] None A list of security groups to attach to the codebuild
privileged No bool False Enable privileged mode for Docker operations
compute_type No codebuild.ComputeType MEDIUM Build environment compute capacity
build_image No IBuildImage AMAZON_LINUX_2_5 Build environment operating system image
create_build_scheduler No bool False Create EventBridge rule for scheduled builds
build_after_deployment No bool False Trigger build immediately after project creation

Usage

Here are some examples of how to use the CodebuildBuilder to build CodeBuild projects in a CDK stack:

Example for standard Codebuild projects

codebuild_builder = CodebuildBuilder()
codebuild_project = codebuild_builder.set_application_helper(app_helper) \
                                     .set_codebuild_type(CodebuildType.PROJECT) \
                                     .set_usage(Usage.ami) \
                                     .set_builder_config({
                                        "vpc": vpc,
                                        "ecr_repo": ami_ecr_repo,
                                        "git_provider": "CODECOMMIT",
                                        "git_repo": git_repo,
                                        "git_branch": "master",
                                        "buildspec_path": buildspec_path,
                                        "create_build_scheduler": True,
                                        "build_after_deployment": True
                                      }) \
                                     .build(scope_from_stack)

Example for Codebuild pipeline projects

codebuild_builder = CodebuildBuilder()
codebuild_project = codebuild_builder.set_application_helper(app_helper) \
                                     .set_codebuild_type(CodebuildType.PIPELINE_PROJECT) \
                                     .set_usage(Usage.frontend) \
                                     .set_builder_config({
                                        "vpc": vpc, # ec2.Vpc
                                        "role": codebuild_role, # iam.IRole
                                        "ami_ecr_repo": ami_ecr_repo, # ecr.Repository
                                        "buildspec_path": buildspec_path, # str
                                        "env_vars": env_vars # Dict[str, codebuild.BuildEnvironmentVariable]
                                      }) \
                                     .build(scope_from_stack)

Behavior and Features

Automatic Project Configuration

Security and Network Isolation:

  • VPC Deployment: All CodeBuild projects deployed within specified VPC for network security
  • Private Subnet Execution: Build environments isolated from public internet access
  • ECR Integration: Automatic permissions for container image pull and push operations
  • Cross-Account Access: Automatic IAM policies for DevOps cross-account role assumption
  • Organizational Tagging: Standard tags applied for governance and cost allocation

Build Environment Management:

  • Compute Scaling: Configurable compute types from SMALL to X2_LARGE for different workloads
  • Docker Support: Privileged mode available for container builds and Docker-in-Docker scenarios
  • Custom Images: Support for both AWS managed images and custom ECR-hosted build images
  • Environment Variables: Secure environment variable injection with Parameter Store and Secrets Manager integration

Source Code Integration:

  • CodeCommit Support: Native integration with AWS CodeCommit repositories
  • Branch Flexibility: Configurable branch targeting for different deployment strategies
  • Buildspec Management: Flexible buildspec file path configuration for different project structures

Naming Convention

CodeBuild project names follow the pattern: {organization-prefix}-{app-name}-{project-type}-{context}-{suffix}

The builder automatically:

  • Applies organizational naming standards
  • Includes project type and context identifiers
  • Truncates names to respect CodeBuild limits (255 characters)
  • Generates unique CloudFormation logical IDs

Build Type Behavior

PROJECT Type (Standalone Builds):

  • Source Integration: Direct integration with CodeCommit repositories
  • ECR Publishing: Automatic container image building and publishing workflows
  • Environment Variables: Standard AWS environment variables (ACCOUNT_ID, REGION, PROJECT_NAME)
  • Immediate Execution: Optional immediate build triggering after deployment
  • Scheduled Builds: Optional EventBridge-based weekly build scheduling

PIPELINE_PROJECT Type (CI/CD Integration):

  • Pipeline Integration: Designed for AWS CodePipeline integration
  • Custom Environment: User-defined environment variables for build customization
  • AMI Support: Optional custom AMI builds using ECR-hosted images
  • Artifact Management: Optimized for pipeline artifact passing and stage coordination

Logging and Monitoring

S3 Logging Integration:

  • Custom Log Storage: Optional S3 bucket configuration for centralized log management
  • CloudWatch Fallback: Default CloudWatch Logs when S3 bucket not specified
  • Log Retention: Configurable retention policies through S3 lifecycle management
  • Cross-Account Access: S3 logging permissions automatically configured

Optional Features

Scheduled Build Triggers:

  • EventBridge Rules: Weekly build schedule (Mondays at 00:30 UTC)
  • Customizable Timing: Cron-based scheduling for different build frequencies
  • Automatic Targeting: CodeBuild project automatically configured as EventBridge target

Immediate Build Execution:

  • Custom Resources: AWS SDK-based build triggering immediately after deployment
  • Dependency Management: Proper CloudFormation dependencies ensure project readiness
  • Error Handling: Robust error handling for immediate build failures

Notes

  • the set_usage method from the abstract class must be used in this builder. Usage must be one of the Usage enum provided by the mare_aws_common_lib package (Usage.DEPLOY, Usage.BUILD_DEPLOY and Usage.BUILD_RELEASE should be avoided).
  • CodeBuild projects support only CodeCommit git provider currently
  • PROJECT type requires ECR repository for container image storage
  • Scheduled builds run every Monday at 00:30 UTC by default
  • Custom build images must be available in ECR with "latest" tag
  • Cross-account role assumption requires proper trust relationships
  • VPC deployment requires private subnets with internet access via NAT Gateway
  • Standard codebuild project builder assumes that we are building something that needs to be pushed into an ecr repository
  • The set_usage method from the abstract class must be used in this builder. Usage must be one of the Usage enum provided by the mare_aws_common_lib package.