Skip to content

CodebuildConfig

Bases: BaseModel, AwsTypesValidationMixin

Configuration model for AWS CodeBuild project creation and management.

Defines the structure and validation rules for creating CodeBuild projects with support for different project types (standalone projects vs pipeline projects), various git providers, ECR integration, and comprehensive AWS resource validation.

Attributes:

Name Type Description
vpc Any

VPC for CodeBuild project execution

role Any

IAM role with permissions for CodeBuild operations

codebuild_type CodebuildType

Type of CodeBuild project (PROJECT or PIPELINE_PROJECT)

buildspec_path str

Path to the buildspec.yml file in the repository

ecr_repo Optional[Any]

ECR repository for container image storage (PROJECT type only)

git_provider Optional[GitProvider]

Git provider for source code (currently supports CodeCommit only)

git_repo Optional[Any]

Git repository containing source code (PROJECT type only)

git_branch Optional[str]

Git branch to build from (PROJECT type only)

pipeline_type Optional[PipelineType]

Pipeline integration type (PIPELINE_PROJECT type only)

ami_ecr_repo Optional[Any]

ECR repository for AMI builds (PIPELINE_PROJECT type only)

env_vars Optional[Dict[str, Any]]

Environment variables for build execution (PIPELINE_PROJECT type only)

usage_context Optional[str]

Context information for build usage

logs_bucket Optional[Any]

S3 bucket for storing build logs

security_groups Optional[List[Any]]

A list of security groups to attach to the codebuild

privileged bool

Enable privileged mode for Docker builds

compute_type ComputeType

CodeBuild compute capacity (SMALL, MEDIUM, LARGE, etc.)

build_image Any

Build environment image (Amazon Linux, Ubuntu, Windows, etc.)

create_build_scheduler bool

Enable scheduled builds

build_after_deployment bool

Trigger build immediately after project creation

Source code in mare_aws_common_lib/models/codebuild_config.py
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
class CodebuildConfig(BaseModel, AwsTypesValidationMixin):
    """Configuration model for AWS CodeBuild project creation and management.

    Defines the structure and validation rules for creating CodeBuild projects
    with support for different project types (standalone projects vs pipeline projects),
    various git providers, ECR integration, and comprehensive AWS resource validation.

    Attributes:
        vpc: VPC for CodeBuild project execution
        role: IAM role with permissions for CodeBuild operations
        codebuild_type: Type of CodeBuild project (PROJECT or PIPELINE_PROJECT)
        buildspec_path: Path to the buildspec.yml file in the repository
        ecr_repo: ECR repository for container image storage (PROJECT type only)
        git_provider: Git provider for source code (currently supports CodeCommit only)
        git_repo: Git repository containing source code (PROJECT type only)
        git_branch: Git branch to build from (PROJECT type only)
        pipeline_type: Pipeline integration type (PIPELINE_PROJECT type only)
        ami_ecr_repo: ECR repository for AMI builds (PIPELINE_PROJECT type only)
        env_vars: Environment variables for build execution (PIPELINE_PROJECT type only)
        usage_context: Context information for build usage
        logs_bucket: S3 bucket for storing build logs
        security_groups: A list of security groups to attach to the codebuild
        privileged: Enable privileged mode for Docker builds
        compute_type: CodeBuild compute capacity (SMALL, MEDIUM, LARGE, etc.)
        build_image: Build environment image (Amazon Linux, Ubuntu, Windows, etc.)
        create_build_scheduler: Enable scheduled builds
        build_after_deployment: Trigger build immediately after project creation
    """

    model_config = ConfigDict(extra="forbid", arbitrary_types_allowed=True)

    # Required fields
    vpc: Any = Field(..., description="VPC configuration")
    role: Any = Field(..., description="IAM role for CodeBuild")
    codebuild_type: CodebuildType = Field(..., description="Codebuild project type")
    buildspec_path: str = Field(..., description="Path to buildspec file")

     # Conditionally required fields
    ecr_repo: Optional[Any] = Field(None, description="ECR repository")
    git_provider: Optional[GitProvider] = Field(None, description="Git provider")
    git_repo: Optional[Any] = Field(None, description="Git repository")
    git_branch: Optional[str] = Field(None, description="Git branch")
    pipeline_type: Optional[PipelineType] = Field(None, description="Pipeline type")

    # Optional fields
    ami_ecr_repo: Optional[Any] = Field(None, description="AMI ECR repository")
    env_vars: Optional[Dict[str, Any]] = Field(None, description="Environment variables")
    usage_context: Optional[str] = Field(None, description="Usage context")
    logs_bucket: Optional[Any] = Field(None, description="S3 bucket for logs")
    security_groups: Optional[List[Any]] = Field(None, description="A list of security groups to attach")

    privileged: bool = Field(default=False, description="Whether to run in privileged mode")
    compute_type: codebuild.ComputeType = Field(
        default=codebuild.ComputeType.MEDIUM, 
        description="CodeBuild compute type"
    )
    build_image: Any = Field(
        default_factory=lambda: codebuild.LinuxBuildImage.AMAZON_LINUX_2_5,
        description="Build image"
    )

    # Flags
    create_build_scheduler: bool = Field(default=False, description="Whether to create a build scheduler")
    build_after_deployment: bool = Field(default=False, description="Whether to build immediately after deployment")

    class Typed:
        """Inner class, type-safe accessor for AWS CDK resources with proper typing.

        Provides strongly-typed access to AWS CDK resources for improved
        IDE support and type checking in CodeBuild project configuration.
        """
        def __init__(self, config: 'CodebuildConfig'):
            self._config = config

        @property
        def vpc(self) -> 'ec2.Vpc':
            """VPC for CodeBuild project execution."""
            return self._config.vpc

        @property 
        def role(self) -> 'iam.Role':
            """IAM role for CodeBuild project permissions."""
            return self._config.role

        @property
        def ecr_repo(self) -> 'Optional[ecr.Repository]':
            """ECR repository for container image storage."""
            return self._config.ecr_repo

        @property
        def git_repo(self) -> 'Optional[codecommit.Repository]':
            """Git repository for source code."""
            return self._config.git_repo

        @property
        def build_image(self) -> 'codebuild.IBuildImage':
            """CodeBuild environment image."""
            return self._config.build_image

        @property
        def logs_bucket(self) -> 's3.IBucket':
            """S3 bucket for build logs storage."""
            return self._config.logs_bucket

    @property
    def typed(self) -> Typed:
        """Access to type-safe AWS CDK resource properties, references the Typed inner class."""
        if not hasattr(self, '_typed'):
            self._typed = self.Typed(self)
        return self._typed

    @field_validator("vpc", mode="after")
    @classmethod
    def validate_vpc_field(cls, value):
        """Validate VPC object implements ec2.IVpc interface."""
        return cls.validate_vpc(value)

    @field_validator("role", mode="after")
    @classmethod
    def validate_role_field(cls, value):
        """Validate IAM role object implements iam.IRole interface."""
        return cls.validate_role(value)

    @field_validator("ecr_repo", "git_repo", mode="after")
    @classmethod
    def validate_ecr_repo(cls, value, info: ValidationInfo):
        """Validate repository objects implement proper CDK interfaces."""
        repo_type = info.field_name.split("_")[0]
        valid_object_type = "ecr.IRepository" if repo_type == "ecr" else "codecommit.IRepository"
        codebuild_type = info.data.get("codebuild_type")
        required = codebuild_type == CodebuildType.PROJECT
        return cls.validate_repository(value, repo_type, valid_object_type, required)

    @field_validator("git_provider", mode="after")
    @classmethod
    def validate_git_provider(cls, value):
        """Validate git provider is supported (currently CodeCommit only)."""
        if value != GitProvider.CODECOMMIT:
            raise ValueError(f"{value} is not yet supported by the CodebuildBuilder")
        return value


    @field_validator("logs_bucket", mode="after")
    @classmethod
    def validate_logs_bucket(cls, value):
        """Validate S3 bucket object implements s3.IBucket interface."""
        return cls.validate_bucket(value)


    @field_validator("env_vars", mode="after")
    @classmethod
    def validate_env_vars(cls, value):
        """Validate environment variables are proper CodeBuild format."""
        return cls.validate_vars(value)

    @field_validator("build_image", mode="after")
    @classmethod  
    def validate_build_image_type(cls, value) -> codebuild.LinuxBuildImage | codebuild.WindowsBuildImage:
        """Validate build image is proper CodeBuild image type."""
        if value is not None and not isinstance(value, (codebuild.LinuxBuildImage, codebuild.WindowsBuildImage)):
            raise ValueError("Must be an instance of codebuild.LinuxBuildImage or codebuild.WindowsBuildImage")
        return value

    @model_validator(mode="after")
    def validate_codebuild_config(self) -> 'CodebuildConfig':
        """Validate complete configuration based on CodeBuild project type.

        Ensures that required fields are present for each project type and
        prevents invalid field combinations across different project types.

        Returns:
            Self with validated configuration

        Raises:
            ValueError: If required fields are missing for the specified project type
            ValueError: If fields specific to other project types are present
        """
        if self.codebuild_type == CodebuildType.PROJECT:
            required_fields = [
                ("ecr_repo", self.ecr_repo),
                ("git_provider", self.git_provider),
                ("git_repo", self.git_repo),
                ("git_branch", self.git_branch)
            ]
            missing = [name for name, val in required_fields if not val]
            if missing:
                raise ValueError(f"Missing required fields for Codebuild PROJECT: {', '.join(missing)}")

             # Disallow fields specific to CODEBUILD PIPELINE_PROJECT
            if self.ami_ecr_repo or self.env_vars:
                raise ValueError("Fields 'ami_ecr_repo' and 'env_vars' are only allowed for Codebuild PIPELINE_PROJECT")

        elif self.codebuild_type == CodebuildType.PIPELINE_PROJECT:
            required_fields = [
                ("pipeline_type", self.pipeline_type)
            ]
            missing = [name for name, val in required_fields if not val]
            if missing:
                raise ValueError(f"Missing required fields for Codebuild PIPELINE_PROJECT: {', '.join(missing)}")

             # Disallow fields specific to PROJECT
            if self.ecr_repo or self.git_repo or self.git_branch:
                raise ValueError("Fields 'ecr_repo', 'git_repo' and 'git_branch' are only allowed for Codebuild PROJECT")

        return self

typed property

Access to type-safe AWS CDK resource properties, references the Typed inner class.

Typed

Inner class, type-safe accessor for AWS CDK resources with proper typing.

Provides strongly-typed access to AWS CDK resources for improved IDE support and type checking in CodeBuild project configuration.

Source code in mare_aws_common_lib/models/codebuild_config.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
class Typed:
    """Inner class, type-safe accessor for AWS CDK resources with proper typing.

    Provides strongly-typed access to AWS CDK resources for improved
    IDE support and type checking in CodeBuild project configuration.
    """
    def __init__(self, config: 'CodebuildConfig'):
        self._config = config

    @property
    def vpc(self) -> 'ec2.Vpc':
        """VPC for CodeBuild project execution."""
        return self._config.vpc

    @property 
    def role(self) -> 'iam.Role':
        """IAM role for CodeBuild project permissions."""
        return self._config.role

    @property
    def ecr_repo(self) -> 'Optional[ecr.Repository]':
        """ECR repository for container image storage."""
        return self._config.ecr_repo

    @property
    def git_repo(self) -> 'Optional[codecommit.Repository]':
        """Git repository for source code."""
        return self._config.git_repo

    @property
    def build_image(self) -> 'codebuild.IBuildImage':
        """CodeBuild environment image."""
        return self._config.build_image

    @property
    def logs_bucket(self) -> 's3.IBucket':
        """S3 bucket for build logs storage."""
        return self._config.logs_bucket

build_image property

CodeBuild environment image.

ecr_repo property

ECR repository for container image storage.

git_repo property

Git repository for source code.

logs_bucket property

S3 bucket for build logs storage.

role property

IAM role for CodeBuild project permissions.

vpc property

VPC for CodeBuild project execution.

validate_build_image_type(value) classmethod

Validate build image is proper CodeBuild image type.

Source code in mare_aws_common_lib/models/codebuild_config.py
171
172
173
174
175
176
177
@field_validator("build_image", mode="after")
@classmethod  
def validate_build_image_type(cls, value) -> codebuild.LinuxBuildImage | codebuild.WindowsBuildImage:
    """Validate build image is proper CodeBuild image type."""
    if value is not None and not isinstance(value, (codebuild.LinuxBuildImage, codebuild.WindowsBuildImage)):
        raise ValueError("Must be an instance of codebuild.LinuxBuildImage or codebuild.WindowsBuildImage")
    return value

validate_codebuild_config()

Validate complete configuration based on CodeBuild project type.

Ensures that required fields are present for each project type and prevents invalid field combinations across different project types.

Returns:

Type Description
CodebuildConfig

Self with validated configuration

Raises:

Type Description
ValueError

If required fields are missing for the specified project type

ValueError

If fields specific to other project types are present

Source code in mare_aws_common_lib/models/codebuild_config.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
@model_validator(mode="after")
def validate_codebuild_config(self) -> 'CodebuildConfig':
    """Validate complete configuration based on CodeBuild project type.

    Ensures that required fields are present for each project type and
    prevents invalid field combinations across different project types.

    Returns:
        Self with validated configuration

    Raises:
        ValueError: If required fields are missing for the specified project type
        ValueError: If fields specific to other project types are present
    """
    if self.codebuild_type == CodebuildType.PROJECT:
        required_fields = [
            ("ecr_repo", self.ecr_repo),
            ("git_provider", self.git_provider),
            ("git_repo", self.git_repo),
            ("git_branch", self.git_branch)
        ]
        missing = [name for name, val in required_fields if not val]
        if missing:
            raise ValueError(f"Missing required fields for Codebuild PROJECT: {', '.join(missing)}")

         # Disallow fields specific to CODEBUILD PIPELINE_PROJECT
        if self.ami_ecr_repo or self.env_vars:
            raise ValueError("Fields 'ami_ecr_repo' and 'env_vars' are only allowed for Codebuild PIPELINE_PROJECT")

    elif self.codebuild_type == CodebuildType.PIPELINE_PROJECT:
        required_fields = [
            ("pipeline_type", self.pipeline_type)
        ]
        missing = [name for name, val in required_fields if not val]
        if missing:
            raise ValueError(f"Missing required fields for Codebuild PIPELINE_PROJECT: {', '.join(missing)}")

         # Disallow fields specific to PROJECT
        if self.ecr_repo or self.git_repo or self.git_branch:
            raise ValueError("Fields 'ecr_repo', 'git_repo' and 'git_branch' are only allowed for Codebuild PROJECT")

    return self

validate_ecr_repo(value, info) classmethod

Validate repository objects implement proper CDK interfaces.

Source code in mare_aws_common_lib/models/codebuild_config.py
139
140
141
142
143
144
145
146
147
@field_validator("ecr_repo", "git_repo", mode="after")
@classmethod
def validate_ecr_repo(cls, value, info: ValidationInfo):
    """Validate repository objects implement proper CDK interfaces."""
    repo_type = info.field_name.split("_")[0]
    valid_object_type = "ecr.IRepository" if repo_type == "ecr" else "codecommit.IRepository"
    codebuild_type = info.data.get("codebuild_type")
    required = codebuild_type == CodebuildType.PROJECT
    return cls.validate_repository(value, repo_type, valid_object_type, required)

validate_env_vars(value) classmethod

Validate environment variables are proper CodeBuild format.

Source code in mare_aws_common_lib/models/codebuild_config.py
165
166
167
168
169
@field_validator("env_vars", mode="after")
@classmethod
def validate_env_vars(cls, value):
    """Validate environment variables are proper CodeBuild format."""
    return cls.validate_vars(value)

validate_git_provider(value) classmethod

Validate git provider is supported (currently CodeCommit only).

Source code in mare_aws_common_lib/models/codebuild_config.py
149
150
151
152
153
154
155
@field_validator("git_provider", mode="after")
@classmethod
def validate_git_provider(cls, value):
    """Validate git provider is supported (currently CodeCommit only)."""
    if value != GitProvider.CODECOMMIT:
        raise ValueError(f"{value} is not yet supported by the CodebuildBuilder")
    return value

validate_logs_bucket(value) classmethod

Validate S3 bucket object implements s3.IBucket interface.

Source code in mare_aws_common_lib/models/codebuild_config.py
158
159
160
161
162
@field_validator("logs_bucket", mode="after")
@classmethod
def validate_logs_bucket(cls, value):
    """Validate S3 bucket object implements s3.IBucket interface."""
    return cls.validate_bucket(value)

validate_role_field(value) classmethod

Validate IAM role object implements iam.IRole interface.

Source code in mare_aws_common_lib/models/codebuild_config.py
133
134
135
136
137
@field_validator("role", mode="after")
@classmethod
def validate_role_field(cls, value):
    """Validate IAM role object implements iam.IRole interface."""
    return cls.validate_role(value)

validate_vpc_field(value) classmethod

Validate VPC object implements ec2.IVpc interface.

Source code in mare_aws_common_lib/models/codebuild_config.py
127
128
129
130
131
@field_validator("vpc", mode="after")
@classmethod
def validate_vpc_field(cls, value):
    """Validate VPC object implements ec2.IVpc interface."""
    return cls.validate_vpc(value)
Example
from mare_aws_common_lib.models import CodebuildConfig
from mare_aws_common_lib.enums import CodebuildType, GitProvider

config = CodebuildConfig(
   vpc=vpc,
   role=codebuild_role,
   codebuild_type=CodebuildType.PROJECT,
   buildspec_path="buildspec.yml",
   ecr_repo=ecr_repository,
   git_provider=GitProvider.CODECOMMIT,
   git_repo=git_repository,
   git_branch="main",
   privileged=True,
   build_after_deployment=True
)