Skip to content
v2.274.0

CodeBuildStep Class ​

Run a script as a CodeBuild Project.

The BuildSpec must be available inline--it cannot reference a file on disk. If your current build instructions are in a file like buildspec.yml in your repository, extract them to a script (say, build.sh) and invoke that script as part of the build:

ts
new pipelines.CodeBuildStep('Synth', {
  commands: ['./build.sh'],
});

Example ​

ts
const pipeline = new pipelines.CodePipeline(this, 'Pipeline', {
  synth: new pipelines.ShellStep('Synth', {
    input: pipelines.CodePipelineSource.connection('my-org/my-app', 'main', {
      connectionArn:
        'arn:aws:codestar-connections:us-east-1:222222222222:connection/7d2469ff-514a-4e4f-9003-5ca4a43cdc41', // Created using the AWS console * });',
    }),
    commands: ['npm ci', 'npm run build', 'npx cdk synth'],
  }),

  // Turn this on because the pipeline uses Docker image assets
  dockerEnabledForSelfMutation: true,
});

pipeline.addWave('MyWave', {
  post: [
    new pipelines.CodeBuildStep('RunApproval', {
      commands: ['command-from-image'],
      buildEnvironment: {
        // The user of a Docker image asset in the pipeline requires turning on
        // 'dockerEnabledForSelfMutation'.
        buildImage: codebuild.LinuxBuildImage.fromAsset(this, 'Image', {
          directory: './docker-image',
        }),
      },
    }),
  ],
});
python
pipeline = pipelines.CodePipeline(self, "Pipeline",
    synth=pipelines.ShellStep("Synth",
        input=pipelines.CodePipelineSource.connection("my-org/my-app", "main",
            connection_arn="arn:aws:codestar-connections:us-east-1:222222222222:connection/7d2469ff-514a-4e4f-9003-5ca4a43cdc41"
        ),
        commands=["npm ci", "npm run build", "npx cdk synth"]
    ),

    # Turn this on because the pipeline uses Docker image assets
    docker_enabled_for_self_mutation=True
)

pipeline.add_wave("MyWave",
    post=[
        pipelines.CodeBuildStep("RunApproval",
            commands=["command-from-image"],
            build_environment=codebuild.BuildEnvironment(
                # The user of a Docker image asset in the pipeline requires turning on
                # 'dockerEnabledForSelfMutation'.
                build_image=codebuild.LinuxBuildImage.from_asset(self, "Image",
                    directory="./docker-image"
                )
            )
        )
    ]
)
java
CodePipeline pipeline = CodePipeline.Builder.create(this, "Pipeline")
        .synth(ShellStep.Builder.create("Synth")
                .input(CodePipelineSource.connection("my-org/my-app", "main", ConnectionSourceOptions.builder()
                        .connectionArn("arn:aws:codestar-connections:us-east-1:222222222222:connection/7d2469ff-514a-4e4f-9003-5ca4a43cdc41")
                        .build()))
                .commands(List.of("npm ci", "npm run build", "npx cdk synth"))
                .build())

        // Turn this on because the pipeline uses Docker image assets
        .dockerEnabledForSelfMutation(true)
        .build();

pipeline.addWave("MyWave", WaveOptions.builder()
        .post(List.of(
            CodeBuildStep.Builder.create("RunApproval")
                    .commands(List.of("command-from-image"))
                    .buildEnvironment(BuildEnvironment.builder()
                            // The user of a Docker image asset in the pipeline requires turning on
                            // 'dockerEnabledForSelfMutation'.
                            .buildImage(LinuxBuildImage.fromAsset(this, "Image", DockerImageAssetProps.builder()
                                    .directory("./docker-image")
                                    .build()))
                            .build())
                    .build()))
        .build());
csharp
// Install: dotnet add package Amazon.CDK.Lib
var pipeline = new CodePipeline(this, "Pipeline", new CodePipelineProps {
    Synth = new ShellStep("Synth", new ShellStepProps {
        Input = CodePipelineSource.Connection("my-org/my-app", "main", new ConnectionSourceOptions {
            ConnectionArn = "arn:aws:codestar-connections:us-east-1:222222222222:connection/7d2469ff-514a-4e4f-9003-5ca4a43cdc41"
        }),
        Commands = new [] { "npm ci", "npm run build", "npx cdk synth" }
    }),

    // Turn this on because the pipeline uses Docker image assets
    DockerEnabledForSelfMutation = true
});

pipeline.AddWave("MyWave", new WaveOptions {
    Post = new [] {
        new CodeBuildStep("RunApproval", new CodeBuildStepProps {
            Commands = new [] { "command-from-image" },
            BuildEnvironment = new BuildEnvironment {
                // The user of a Docker image asset in the pipeline requires turning on
                // 'dockerEnabledForSelfMutation'.
                BuildImage = LinuxBuildImage.FromAsset(this, "Image", new DockerImageAssetProps {
                    Directory = "./docker-image"
                })
            }
        }) }
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
pipeline := pipelines.NewCodePipeline(this, jsii.String("Pipeline"), &CodePipelineProps{
	Synth: pipelines.NewShellStep(jsii.String("Synth"), &ShellStepProps{
		Input: pipelines.CodePipelineSource_Connection(jsii.String("my-org/my-app"), jsii.String("main"), &ConnectionSourceOptions{
			ConnectionArn: jsii.String("arn:aws:codestar-connections:us-east-1:222222222222:connection/7d2469ff-514a-4e4f-9003-5ca4a43cdc41"),
		}),
		Commands: []*string{
			jsii.String("npm ci"),
			jsii.String("npm run build"),
			jsii.String("npx cdk synth"),
		},
	}),

	// Turn this on because the pipeline uses Docker image assets
	DockerEnabledForSelfMutation: jsii.Boolean(true),
})

pipeline.AddWave(jsii.String("MyWave"), &WaveOptions{
	Post: []Step{
		pipelines.NewCodeBuildStep(jsii.String("RunApproval"), &CodeBuildStepProps{
			Commands: []*string{
				jsii.String("command-from-image"),
			},
			BuildEnvironment: &BuildEnvironment{
				// The user of a Docker image asset in the pipeline requires turning on
				// 'dockerEnabledForSelfMutation'.
				BuildImage: codebuild.LinuxBuildImage_FromAsset(this, jsii.String("Image"), &DockerImageAssetProps{
					Directory: jsii.String("./docker-image"),
				}),
			},
		}),
	},
})

Initializer ​

ts
new CodeBuildStep(id: string, props: CodeBuildStepProps)
python
CodeBuildStep(id: str, props: CodeBuildStepProps)
java
new CodeBuildStep(String id, CodeBuildStepProps props)
csharp
new CodeBuildStep(string id, CodeBuildStepProps props)
go
NewCodeBuildStep(Id *string, Props CodeBuildStepProps)

Properties ​

actionRolemay be undefinedIRoleaction_rolemay be undefinedIRoleactionRolemay be undefinedIRoleActionRolemay be undefinedIRoleActionRolemay be undefinedIRole#
Custom execution role to be used for the Code Build Action.

Default: A role is automatically created

buildEnvironmentmay be undefinedBuildEnvironmentbuild_environmentmay be undefinedBuildEnvironmentbuildEnvironmentmay be undefinedBuildEnvironmentBuildEnvironmentmay be undefinedBuildEnvironmentBuildEnvironmentmay be undefinedBuildEnvironment#
Build environment.

Default: No value specified at construction time, use defaults

cachemay be undefinedCachecachemay be undefinedCachecachemay be undefinedCacheCachemay be undefinedCacheCachemay be undefinedCache#
Caching strategy to use.

Default: No cache

commandsstring[]commandstyping.List[str]commandsList<String>Commandsstring[]Commands*[]*string#
Commands to run.
consumedStackOutputsStackOutputReference[]consumed_stack_outputstyping.List[StackOutputReference]consumedStackOutputsList<StackOutputReference>ConsumedStackOutputsStackOutputReference[]ConsumedStackOutputs*[]StackOutputReference#
StackOutputReferences this step consumes.
dependenciesStep[]dependenciestyping.List[Step]dependenciesList<Step>DependenciesStep[]Dependencies*[]Step#
Return the steps this step depends on, based on the FileSets it requires.
dependencyFileSetsFileSet[]dependency_file_setstyping.List[FileSet]dependencyFileSetsList<FileSet>DependencyFileSetsFileSet[]DependencyFileSets*[]FileSet#
The list of FileSets consumed by this Step.
env{ [key: string]: string }envtyping.Mapping[str, str]envMap<String, String>EnvIDictionary<string, string>Env*map[string]*string#
Environment variables to set.

Default: No environment variables

envFromCfnOutputs{ [key: string]: StackOutputReference }env_from_cfn_outputstyping.Mapping[str, StackOutputReference]envFromCfnOutputsMap<String, StackOutputReference>EnvFromCfnOutputsIDictionary<string, StackOutputReference>EnvFromCfnOutputs*map[string]StackOutputReference#
Set environment variables based on Stack Outputs.

Default: No environment variables created from stack outputs

fileSystemLocationsmay be undefinedIFileSystemLocation[]file_system_locationsmay be undefinedtyping.List[IFileSystemLocation]fileSystemLocationsmay be undefinedList<IFileSystemLocation>FileSystemLocationsmay be undefinedIFileSystemLocation[]FileSystemLocationsmay be undefined*[]IFileSystemLocation#
ProjectFileSystemLocation objects for CodeBuild build projects.

Default: no file system locations

A ProjectFileSystemLocation object specifies the identifier, location, mountOptions, mountPoint, and type of a file system created using Amazon Elastic File System.

grantPrincipalIPrincipalgrant_principalIPrincipalgrantPrincipalIPrincipalGrantPrincipalIPrincipalGrantPrincipalIPrincipal#
The CodeBuild Project's principal.
idstringidstridStringIdstringId*string#
Identifier for this step.
inputsFileSetLocation[]inputstyping.List[FileSetLocation]inputsList<FileSetLocation>InputsFileSetLocation[]Inputs*[]FileSetLocation#
Input FileSets.

A list of (FileSet, directory) pairs, which are a copy of the input properties. This list should not be modified directly.

installCommandsstring[]install_commandstyping.List[str]installCommandsList<String>InstallCommandsstring[]InstallCommands*[]*string#
Installation commands to run before the regular commands.

Default: No installation commands

For deployment engines that support it, install commands will be classified differently in the job history from the regular commands.

isSourcebooleanis_sourceboolisSourceBooleanIsSourceboolIsSource*bool#
Whether or not this is a Source step.

What it means to be a Source step depends on the engine.

loggingmay be undefinedLoggingOptionsloggingmay be undefinedLoggingOptionsloggingmay be undefinedLoggingOptionsLoggingmay be undefinedLoggingOptionsLoggingmay be undefinedLoggingOptions#
Information about logs for CodeBuild projects.

Default: no log configuration is set

A CodeBuilde project can create logs in Amazon CloudWatch Logs, an S3 bucket, or both.

outputsFileSetLocation[]outputstyping.List[FileSetLocation]outputsList<FileSetLocation>OutputsFileSetLocation[]Outputs*[]FileSetLocation#
Output FileSets.

A list of (FileSet, directory) pairs, which are a copy of the input properties. This list should not be modified directly.

partialBuildSpecmay be undefinedBuildSpecpartial_build_specmay be undefinedBuildSpecpartialBuildSpecmay be undefinedBuildSpecPartialBuildSpecmay be undefinedBuildSpecPartialBuildSpecmay be undefinedBuildSpec#
Additional configuration that can only be configured via BuildSpec.

Default: Contains the exported variables

Contains exported variables

primaryOutputmay be undefinedFileSetprimary_outputmay be undefinedFileSetprimaryOutputmay be undefinedFileSetPrimaryOutputmay be undefinedFileSetPrimaryOutputmay be undefinedFileSet#
The primary FileSet produced by this Step.

Not all steps produce an output FileSet--if they do you can substitute the Step object for the FileSet object.

projectIProjectprojectIProjectprojectIProjectProjectIProjectProjectIProject#
CodeBuild Project generated for the pipeline.

Will only be available after the pipeline has been built.

projectNamemay be undefinedstringproject_namemay be undefinedstrprojectNamemay be undefinedStringProjectNamemay be undefinedstringProjectNamemay be undefined*string#
Name for the generated CodeBuild project.

Default: No value specified at construction time, use defaults

rolemay be undefinedIRolerolemay be undefinedIRolerolemay be undefinedIRoleRolemay be undefinedIRoleRolemay be undefinedIRole#
Custom execution role to be used for the CodeBuild project.

Default: No value specified at construction time, use defaults

rolePolicyStatementsmay be undefinedPolicyStatement[]role_policy_statementsmay be undefinedtyping.List[PolicyStatement]rolePolicyStatementsmay be undefinedList<PolicyStatement>RolePolicyStatementsmay be undefinedPolicyStatement[]RolePolicyStatementsmay be undefined*[]PolicyStatement#
Policy statements to add to role used during the synth.

Default: No value specified at construction time, use defaults

securityGroupsmay be undefinedISecurityGroup[]security_groupsmay be undefinedtyping.List[ISecurityGroup]securityGroupsmay be undefinedList<ISecurityGroup>SecurityGroupsmay be undefinedISecurityGroup[]SecurityGroupsmay be undefined*[]ISecurityGroup#
Which security group to associate with the script's project network interfaces.

Default: No value specified at construction time, use defaults

subnetSelectionmay be undefinedSubnetSelectionsubnet_selectionmay be undefinedSubnetSelectionsubnetSelectionmay be undefinedSubnetSelectionSubnetSelectionmay be undefinedSubnetSelectionSubnetSelectionmay be undefinedSubnetSelection#
Which subnets to use.

Default: No value specified at construction time, use defaults

timeoutmay be undefinedDurationtimeoutmay be undefinedDurationtimeoutmay be undefinedDurationTimeoutmay be undefinedDurationTimeoutmay be undefinedDuration= Duration.hours(1)#
The number of minutes after which AWS CodeBuild stops the build if it's not complete.

For valid values, see the timeoutInMinutes field in the AWS CodeBuild User Guide.

vpcmay be undefinedIVpcvpcmay be undefinedIVpcvpcmay be undefinedIVpcVpcmay be undefinedIVpcVpcmay be undefinedIVpc#
The VPC where to execute the SimpleSynth.

Default: No value specified at construction time, use defaults

Methods ​

addOutputDirectory(directory: string): FileSetdef add_output_directory(self, directory: str) -> FileSetpublic FileSet addOutputDirectory(String directory)public FileSet AddOutputDirectory(string directory)func AddOutputDirectory(Directory *string) FileSet#
Add an additional output FileSet based on a directory.
notes

After running the script, the contents of the given directory will be exported as a FileSet. Use the FileSet as the input to another step.

Multiple calls with the exact same directory name string (not normalized) will return the same FileSet.

addStepDependency(step: Step): voiddef add_step_dependency(self, step: Step) -> Nonepublic void addStepDependency(Step step)public void AddStepDependency(Step step)func AddStepDependency(Step Step)#
Add a dependency on another step.
exportedVariable(variableName: string): stringdef exported_variable(self, variable_name: str) -> strpublic String exportedVariable(String variableName)public string ExportedVariable(string variableName)func ExportedVariable(VariableName *string) *string#
Reference a CodePipeline variable defined by the CodeBuildStep.

The variable must be set in the shell of the CodeBuild step when it finishes its post_build phase.

1 parameter · example

Parameters

  • variableNamevariable_namevariableNamevariableNameVariableName — the name of the variable for reference.
ts
// Access the output of one CodeBuildStep in another CodeBuildStep
declare const pipeline: pipelines.CodePipeline;

const step1 = new pipelines.CodeBuildStep('Step1', {
  commands: ['export MY_VAR=hello'],
});

const step2 = new pipelines.CodeBuildStep('Step2', {
  env: {
    IMPORTED_VAR: step1.exportedVariable('MY_VAR'),
  },
  commands: ['echo $IMPORTED_VAR'],
});
primaryOutputDirectory(directory: string): FileSetdef primary_output_directory(self, directory: str) -> FileSetpublic FileSet primaryOutputDirectory(String directory)public FileSet PrimaryOutputDirectory(string directory)func PrimaryOutputDirectory(Directory *string) FileSet#
Configure the given output directory as primary output.

If no primary output has been configured yet, this directory will become the primary output of this ShellStep, otherwise this method will throw if the given directory is different than the currently configured primary output directory.

sequence(steps: Step[]): Step[]@staticmethod def sequence(steps: typing.List[Step]) -> typing.List[Step]public static List<Step> sequence(List<Step> steps)public static Step[] Sequence(Step[] steps)func Sequence(Steps *[]Step) *[]Stepstatic#
Define a sequence of steps to be executed in order.

If you need more fine-grained step ordering, use the addStepDependency() API. For example, if you want secondStep to occur after firstStep, call secondStep.addStepDependency(firstStep).

toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Return a string representation of this Step.