Use AWS CDK to create CodeBuild Project for building Docker Images
Asked Answered
N

2

6

I want to define a CodeBuild project in source code using the AWS CDK. The CodeBuild project needs to be able to build and then push docker images.

When creating a new CodeBuild Project in the AWS Console there's an option:

Privileged Enable this flag if you want to build Docker images or want your builds to get elevated privileges.

enter image description here

I don't see an equivalent api for turning on the Privileged flag in the API Docs.

var codeBuildProject = new Project(this, "Example_Build", new ProjectProps
{
    ProjectName = "ExampleBuildFromCDK",
    // How to add Privileged?
    BuildSpec = BuildSpec.FromSourceFilename("example/buildspec.yml"),
    Source = Source.CodeCommit(new CodeCommitSourceProps
    {
        Repository = Repository.FromRepositoryArn(this, "CodeCommit", CodeRepositoryArn),
        BranchOrRef = "refs/heads/example/added-docker-images"
    })
});

And if I try to run my build without setting Privileged to true, I'll get the standard error:

Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

How to I use the AWS CDK to create a CodeBuild Project that has "Privileged" to build Docker images?

Nematic answered 23/10, 2020 at 2:57 Comment(0)
S
10
    new Project(this, "coolBuildProject", {
      // ... setting up your codeBuildProject
      environment: {
        // this is the essential piece you're looking for
        privileged: true,
      },
    });

In general, you can find all other (build) environment settings here: https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-codebuild.BuildEnvironment.html#privileged

Stepaniestepbrother answered 23/10, 2020 at 10:58 Comment(1)
That's the one! Setting was hidden in the Environment property docs.aws.amazon.com/cdk/api/latest/docs/…Nematic
M
0

I suspect that the previously accepted answer was written for CDK 1.x. For CDK 2.x, I found that the default build image does provide support for building docker images. This is easily remedied by explicitly setting the build image as follows.

new Project(this, "coolBuildProject", {
      // ... setting up your codeBuildProject
      environment: {
        // this is the essential piece you're looking for
        privileged: true,
        // insert your preferred image below.
        buildImage: codebuild.LinuxBuildImage.fromCodeBuildImageId("aws/codebuild/standard:6.0"),
      },
    });

Messy answered 12/4, 2023 at 2:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.