Skip to content
v2.274.0

CodeBuildAction Class ​

CodePipeline build action that uses AWS CodeBuild.

Example ​

ts
// Create a Cloudfront Web Distribution
import * as cloudfront from 'aws-cdk-lib/aws-cloudfront';
declare const distribution: cloudfront.Distribution;

// Create the build project that will invalidate the cache
const invalidateBuildProject = new codebuild.PipelineProject(this, `InvalidateProject`, {
  buildSpec: codebuild.BuildSpec.fromObject({
    version: '0.2',
    phases: {
      build: {
        commands:[
          'aws cloudfront create-invalidation --distribution-id ${CLOUDFRONT_ID} --paths "/*"',
          // Choose whatever files or paths you'd like, or all files as specified here
        ],
      },
    },
  }),
  environmentVariables: {
    CLOUDFRONT_ID: { value: distribution.distributionId },
  },
});

// Add Cloudfront invalidation permissions to the project
const distributionArn = `arn:aws:cloudfront::${this.account}:distribution/${distribution.distributionId}`;
invalidateBuildProject.addToRolePolicy(new iam.PolicyStatement({
  resources: [distributionArn],
  actions: [
    'cloudfront:CreateInvalidation',
  ],
}));

// Create the pipeline (here only the S3 deploy and Invalidate cache build)
const deployBucket = new s3.Bucket(this, 'DeployBucket');
const deployInput = new codepipeline.Artifact();
new codepipeline.Pipeline(this, 'Pipeline', {
  stages: [
    // ...
    {
      stageName: 'Deploy',
      actions: [
        new codepipeline_actions.S3DeployAction({
          actionName: 'S3Deploy',
          bucket: deployBucket,
          input: deployInput,
          runOrder: 1,
        }),
        new codepipeline_actions.CodeBuildAction({
          actionName: 'InvalidateCache',
          project: invalidateBuildProject,
          input: deployInput,
          runOrder: 2,
        }),
      ],
    },
  ],
});
python
# Create a Cloudfront Web Distribution
import aws_cdk.aws_cloudfront as cloudfront
# distribution: cloudfront.Distribution


# Create the build project that will invalidate the cache
invalidate_build_project = codebuild.PipelineProject(self, "InvalidateProject",
    build_spec=codebuild.BuildSpec.from_object({
        "version": "0.2",
        "phases": {
            "build": {
                "commands": ["aws cloudfront create-invalidation --distribution-id ${CLOUDFRONT_ID} --paths \"/*\""
                ]
            }
        }
    }),
    environment_variables={
        "CLOUDFRONT_ID": codebuild.BuildEnvironmentVariable(value=distribution.distribution_id)
    }
)

# Add Cloudfront invalidation permissions to the project
distribution_arn = f"arn:aws:cloudfront::{this.account}:distribution/{distribution.distributionId}"
invalidate_build_project.add_to_role_policy(iam.PolicyStatement(
    resources=[distribution_arn],
    actions=["cloudfront:CreateInvalidation"
    ]
))

# Create the pipeline (here only the S3 deploy and Invalidate cache build)
deploy_bucket = s3.Bucket(self, "DeployBucket")
deploy_input = codepipeline.Artifact()
codepipeline.Pipeline(self, "Pipeline",
    stages=[codepipeline.StageProps(
        stage_name="Deploy",
        actions=[
            codepipeline_actions.S3DeployAction(
                action_name="S3Deploy",
                bucket=deploy_bucket,
                input=deploy_input,
                run_order=1
            ),
            codepipeline_actions.CodeBuildAction(
                action_name="InvalidateCache",
                project=invalidate_build_project,
                input=deploy_input,
                run_order=2
            )
        ]
    )
    ]
)
java
// Create a Cloudfront Web Distribution
import software.amazon.awscdk.services.cloudfront.*;
Distribution distribution;


// Create the build project that will invalidate the cache
PipelineProject invalidateBuildProject = PipelineProject.Builder.create(this, "InvalidateProject")
        .buildSpec(BuildSpec.fromObject(Map.of(
                "version", "0.2",
                "phases", Map.of(
                        "build", Map.of(
                                "commands", List.of("aws cloudfront create-invalidation --distribution-id ${CLOUDFRONT_ID} --paths \"/*\""))))))
        .environmentVariables(Map.of(
                "CLOUDFRONT_ID", BuildEnvironmentVariable.builder().value(distribution.getDistributionId()).build()))
        .build();

// Add Cloudfront invalidation permissions to the project
String distributionArn = String.format("arn:aws:cloudfront::%s:distribution/%s", this.account, distribution.getDistributionId());
invalidateBuildProject.addToRolePolicy(PolicyStatement.Builder.create()
        .resources(List.of(distributionArn))
        .actions(List.of("cloudfront:CreateInvalidation"))
        .build());

// Create the pipeline (here only the S3 deploy and Invalidate cache build)
Bucket deployBucket = new Bucket(this, "DeployBucket");
Artifact deployInput = new Artifact();
Pipeline.Builder.create(this, "Pipeline")
        .stages(List.of(StageProps.builder()
                .stageName("Deploy")
                .actions(List.of(
                    S3DeployAction.Builder.create()
                            .actionName("S3Deploy")
                            .bucket(deployBucket)
                            .input(deployInput)
                            .runOrder(1)
                            .build(),
                    CodeBuildAction.Builder.create()
                            .actionName("InvalidateCache")
                            .project(invalidateBuildProject)
                            .input(deployInput)
                            .runOrder(2)
                            .build()))
                .build()))
        .build();
csharp
// Install: dotnet add package Amazon.CDK.Lib
// Create a Cloudfront Web Distribution
using Amazon.CDK.AWS.CloudFront;
Distribution distribution;


// Create the build project that will invalidate the cache
var invalidateBuildProject = new PipelineProject(this, "InvalidateProject", new PipelineProjectProps {
    BuildSpec = BuildSpec.FromObject(new Dictionary<string, object> {
        { "version", "0.2" },
        { "phases", new Dictionary<string, IDictionary<string, string[]>> {
            { "build", new Struct {
                Commands = new [] { "aws cloudfront create-invalidation --distribution-id ${CLOUDFRONT_ID} --paths \"/*\"" }
            } }
        } }
    }),
    EnvironmentVariables = new Dictionary<string, BuildEnvironmentVariable> {
        { "CLOUDFRONT_ID", new BuildEnvironmentVariable { Value = distribution.DistributionId } }
    }
});

// Add Cloudfront invalidation permissions to the project
var distributionArn = $"arn:aws:cloudfront::{this.account}:distribution/{distribution.distributionId}";
invalidateBuildProject.AddToRolePolicy(new PolicyStatement(new PolicyStatementProps {
    Resources = new [] { distributionArn },
    Actions = new [] { "cloudfront:CreateInvalidation" }
}));

// Create the pipeline (here only the S3 deploy and Invalidate cache build)
var deployBucket = new Bucket(this, "DeployBucket");
var deployInput = new Artifact();
new Pipeline(this, "Pipeline", new PipelineProps {
    Stages = new [] { new StageProps {
        StageName = "Deploy",
        Actions = new [] {
            new S3DeployAction(new S3DeployActionProps {
                ActionName = "S3Deploy",
                Bucket = deployBucket,
                Input = deployInput,
                RunOrder = 1
            }),
            new CodeBuildAction(new CodeBuildActionProps {
                ActionName = "InvalidateCache",
                Project = invalidateBuildProject,
                Input = deployInput,
                RunOrder = 2
            }) }
    } }
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
// Create a Cloudfront Web Distribution
import cloudfront "github.com/aws/aws-cdk-go/awscdk"
var distribution Distribution


// Create the build project that will invalidate the cache
invalidateBuildProject := codebuild.NewPipelineProject(this, jsii.String("InvalidateProject"), &PipelineProjectProps{
	BuildSpec: codebuild.BuildSpec_FromObject(map[string]interface{}{
		"version": jsii.String("0.2"),
		"phases": map[string]map[string][]*string{
			"build": map[string][]*string{
				"commands": []*string{
					jsii.String("aws cloudfront create-invalidation --distribution-id ${CLOUDFRONT_ID} --paths \"/*\""),
				},
			},
		},
	}),
	EnvironmentVariables: map[string]BuildEnvironmentVariable{
		"CLOUDFRONT_ID": &BuildEnvironmentVariable{
			"value": distribution.distributionId,
		},
	},
})

// Add Cloudfront invalidation permissions to the project
distributionArn := fmt.Sprintf("arn:aws:cloudfront::%v:distribution/%v", this.Account, distribution.DistributionId)
invalidateBuildProject.addToRolePolicy(iam.NewPolicyStatement(&PolicyStatementProps{
	Resources: []*string{
		distributionArn,
	},
	Actions: []*string{
		jsii.String("cloudfront:CreateInvalidation"),
	},
}))

// Create the pipeline (here only the S3 deploy and Invalidate cache build)
deployBucket := s3.NewBucket(this, jsii.String("DeployBucket"))
deployInput := codepipeline.NewArtifact()
codepipeline.NewPipeline(this, jsii.String("Pipeline"), &PipelineProps{
	Stages: []StageProps{
		&StageProps{
			StageName: jsii.String("Deploy"),
			Actions: []IAction{
				codepipeline_actions.NewS3DeployAction(&S3DeployActionProps{
					ActionName: jsii.String("S3Deploy"),
					Bucket: deployBucket,
					Input: deployInput,
					RunOrder: jsii.Number(1),
				}),
				codepipeline_actions.NewCodeBuildAction(&CodeBuildActionProps{
					ActionName: jsii.String("InvalidateCache"),
					Project: invalidateBuildProject,
					Input: deployInput,
					RunOrder: jsii.Number(2),
				}),
			},
		},
	},
})

Initializer ​

ts
new CodeBuildAction(props: CodeBuildActionProps)
python
CodeBuildAction(props: CodeBuildActionProps)
java
new CodeBuildAction(CodeBuildActionProps props)
csharp
new CodeBuildAction(CodeBuildActionProps props)
go
NewCodeBuildAction(Props CodeBuildActionProps)

Properties ​

actionPropertiesActionPropertiesaction_propertiesActionPropertiesactionPropertiesActionPropertiesActionPropertiesActionPropertiesActionPropertiesActionPropertiesrequired#
The simple properties of the Action, like its Owner, name, etc.

Note that this accessor will be called before the bind callback.

Methods ​

bind(scope: Construct, stage: IStage, options: ActionBindOptions): ActionConfigdef bind(self, scope: Construct, stage: IStage, options: ActionBindOptions) -> ActionConfigpublic ActionConfig bind(Construct scope, IStage stage, ActionBindOptions options)public ActionConfig Bind(Construct scope, IStage stage, ActionBindOptions options)func Bind(Scope Construct, Stage IStage, Options ActionBindOptions) ActionConfig#
The callback invoked when this Action is added to a Pipeline.
onStateChange(name: string, target?: IRuleTarget, options?: RuleProps): Ruledef on_state_change(self, name: str, target: typing.Optional[IRuleTarget] = None, options: typing.Optional[RuleProps] = None) -> Rulepublic Rule onStateChange(String name, IRuleTarget target, RuleProps options)public Rule OnStateChange(string name, IRuleTarget? target = null, RuleProps? options = null)func OnStateChange(Name *string, Target IRuleTarget, Options RuleProps) Rule#
Creates an Event that will be triggered whenever the state of this Action changes.
variable(variableName: string): stringdef variable(self, variable_name: str) -> strpublic String variable(String variableName)public string Variable(string variableName)func Variable(VariableName *string) *string#
Reference a CodePipeline variable defined by the CodeBuild project this action points to.

Variables in CodeBuild actions are defined using the 'exported-variables' subsection of the 'env' section of the buildspec.

1 parameter

Parameters

  • variableNamevariable_namevariableNamevariableNameVariableName — the name of the variable to reference.