Skip to content
v2.275.0

AWS CodePipeline Actions ​

This package contains Actions that can be used in a CodePipeline.

ts
import * as codepipeline from 'aws-cdk-lib/aws-codepipeline';
import * as codepipeline_actions from 'aws-cdk-lib/aws-codepipeline-actions';
python
import aws_cdk.aws_codepipeline as codepipeline
import aws_cdk.aws_codepipeline_actions as codepipeline_actions
java
import software.amazon.awscdk.services.codepipeline.*;
import software.amazon.awscdk.services.codepipeline.actions.*;
csharp
using Amazon.CDK.AWS.CodePipeline;
using Amazon.CDK.AWS.CodePipeline.Actions;
go
import codepipeline "github.com/aws/aws-cdk-go/awscdk"
import codepipeline_actions "github.com/aws/aws-cdk-go/awscdk"

Sources ​

AWS CodeCommit ​

To use a CodeCommit Repository in a CodePipeline:

ts
const repo = new codecommit.Repository(this, 'Repo', {
  repositoryName: 'MyRepo',
});

const pipeline = new codepipeline.Pipeline(this, 'MyPipeline', {
  pipelineName: 'MyPipeline',
});
const sourceOutput = new codepipeline.Artifact();
const sourceAction = new codepipeline_actions.CodeCommitSourceAction({
  actionName: 'CodeCommit',
  repository: repo,
  output: sourceOutput,
});
pipeline.addStage({
  stageName: 'Source',
  actions: [sourceAction],
});
python
repo = codecommit.Repository(self, "Repo",
    repository_name="MyRepo"
)

pipeline = codepipeline.Pipeline(self, "MyPipeline",
    pipeline_name="MyPipeline"
)
source_output = codepipeline.Artifact()
source_action = codepipeline_actions.CodeCommitSourceAction(
    action_name="CodeCommit",
    repository=repo,
    output=source_output
)
pipeline.add_stage(
    stage_name="Source",
    actions=[source_action]
)
java
Repository repo = Repository.Builder.create(this, "Repo")
        .repositoryName("MyRepo")
        .build();

Pipeline pipeline = Pipeline.Builder.create(this, "MyPipeline")
        .pipelineName("MyPipeline")
        .build();
Artifact sourceOutput = new Artifact();
CodeCommitSourceAction sourceAction = CodeCommitSourceAction.Builder.create()
        .actionName("CodeCommit")
        .repository(repo)
        .output(sourceOutput)
        .build();
pipeline.addStage(StageOptions.builder()
        .stageName("Source")
        .actions(List.of(sourceAction))
        .build());
csharp
var repo = new Repository(this, "Repo", new RepositoryProps {
    RepositoryName = "MyRepo"
});

var pipeline = new Pipeline(this, "MyPipeline", new PipelineProps {
    PipelineName = "MyPipeline"
});
var sourceOutput = new Artifact();
var sourceAction = new CodeCommitSourceAction(new CodeCommitSourceActionProps {
    ActionName = "CodeCommit",
    Repository = repo,
    Output = sourceOutput
});
pipeline.AddStage(new StageOptions {
    StageName = "Source",
    Actions = new [] { sourceAction }
});
go
repo := codecommit.NewRepository(this, jsii.String("Repo"), &RepositoryProps{
	RepositoryName: jsii.String("MyRepo"),
})

pipeline := codepipeline.NewPipeline(this, jsii.String("MyPipeline"), &PipelineProps{
	PipelineName: jsii.String("MyPipeline"),
})
sourceOutput := codepipeline.NewArtifact()
sourceAction := codepipeline_actions.NewCodeCommitSourceAction(&CodeCommitSourceActionProps{
	ActionName: jsii.String("CodeCommit"),
	Repository: repo,
	Output: sourceOutput,
})
pipeline.AddStage(&StageOptions{
	StageName: jsii.String("Source"),
	Actions: []IAction{
		sourceAction,
	},
})

If you want to use existing role which can be used by on commit event rule. You can specify the role object in eventRole property.

ts
const eventRole = iam.Role.fromRoleArn(this, 'Event-role', 'roleArn');
declare const repo: codecommit.Repository;
const sourceAction = new codepipeline_actions.CodeCommitSourceAction({
  actionName: 'CodeCommit',
  repository: repo,
  output: new codepipeline.Artifact(),
  eventRole,
});
python
# repo: codecommit.Repository
event_role = iam.Role.from_role_arn(self, "Event-role", "roleArn")
source_action = codepipeline_actions.CodeCommitSourceAction(
    action_name="CodeCommit",
    repository=repo,
    output=codepipeline.Artifact(),
    event_role=event_role
)
java
Repository repo;
IRole eventRole = Role.fromRoleArn(this, "Event-role", "roleArn");
CodeCommitSourceAction sourceAction = CodeCommitSourceAction.Builder.create()
        .actionName("CodeCommit")
        .repository(repo)
        .output(new Artifact())
        .eventRole(eventRole)
        .build();
csharp
Repository repo;
var eventRole = Role.FromRoleArn(this, "Event-role", "roleArn");
var sourceAction = new CodeCommitSourceAction(new CodeCommitSourceActionProps {
    ActionName = "CodeCommit",
    Repository = repo,
    Output = new Artifact(),
    EventRole = eventRole
});
go
var repo Repository
eventRole := iam.Role_FromRoleArn(this, jsii.String("Event-role"), jsii.String("roleArn"))
sourceAction := codepipeline_actions.NewCodeCommitSourceAction(&CodeCommitSourceActionProps{
	ActionName: jsii.String("CodeCommit"),
	Repository: repo,
	Output: codepipeline.NewArtifact(),
	EventRole: EventRole,
})

If you want to clone the entire CodeCommit repository (only available for CodeBuild actions), you can set the codeBuildCloneOutput property to true:

ts
declare const project: codebuild.PipelineProject;
declare const repo: codecommit.Repository;
const sourceOutput = new codepipeline.Artifact();
const sourceAction = new codepipeline_actions.CodeCommitSourceAction({
  actionName: 'CodeCommit',
  repository: repo,
  output: sourceOutput,
  codeBuildCloneOutput: true,
});

const buildAction = new codepipeline_actions.CodeBuildAction({
  actionName: 'CodeBuild',
  project,
  input: sourceOutput, // The build action must use the CodeCommitSourceAction output as input.
  outputs: [new codepipeline.Artifact()], // optional
});
python
# project: codebuild.PipelineProject
# repo: codecommit.Repository

source_output = codepipeline.Artifact()
source_action = codepipeline_actions.CodeCommitSourceAction(
    action_name="CodeCommit",
    repository=repo,
    output=source_output,
    code_build_clone_output=True
)

build_action = codepipeline_actions.CodeBuildAction(
    action_name="CodeBuild",
    project=project,
    input=source_output,  # The build action must use the CodeCommitSourceAction output as input.
    outputs=[codepipeline.Artifact()]
)
java
PipelineProject project;
Repository repo;

Artifact sourceOutput = new Artifact();
CodeCommitSourceAction sourceAction = CodeCommitSourceAction.Builder.create()
        .actionName("CodeCommit")
        .repository(repo)
        .output(sourceOutput)
        .codeBuildCloneOutput(true)
        .build();

CodeBuildAction buildAction = CodeBuildAction.Builder.create()
        .actionName("CodeBuild")
        .project(project)
        .input(sourceOutput) // The build action must use the CodeCommitSourceAction output as input.
        .outputs(List.of(new Artifact()))
        .build();
csharp
PipelineProject project;
Repository repo;

var sourceOutput = new Artifact();
var sourceAction = new CodeCommitSourceAction(new CodeCommitSourceActionProps {
    ActionName = "CodeCommit",
    Repository = repo,
    Output = sourceOutput,
    CodeBuildCloneOutput = true
});

var buildAction = new CodeBuildAction(new CodeBuildActionProps {
    ActionName = "CodeBuild",
    Project = project,
    Input = sourceOutput,  // The build action must use the CodeCommitSourceAction output as input.
    Outputs = new [] { new Artifact() }
});
go
var project PipelineProject
var repo Repository

sourceOutput := codepipeline.NewArtifact()
sourceAction := codepipeline_actions.NewCodeCommitSourceAction(&CodeCommitSourceActionProps{
	ActionName: jsii.String("CodeCommit"),
	Repository: repo,
	Output: sourceOutput,
	CodeBuildCloneOutput: jsii.Boolean(true),
})

buildAction := codepipeline_actions.NewCodeBuildAction(&CodeBuildActionProps{
	ActionName: jsii.String("CodeBuild"),
	Project: Project,
	Input: sourceOutput,
	 // The build action must use the CodeCommitSourceAction output as input.
	Outputs: []Artifact{
		codepipeline.NewArtifact(),
	},
})

The CodeCommit source action emits variables:

ts
declare const project: codebuild.PipelineProject;
declare const repo: codecommit.Repository;
const sourceOutput = new codepipeline.Artifact();
const sourceAction = new codepipeline_actions.CodeCommitSourceAction({
  actionName: 'CodeCommit',
  repository: repo,
  output: sourceOutput,
  variablesNamespace: 'MyNamespace', // optional - by default, a name will be generated for you
});

// later:

new codepipeline_actions.CodeBuildAction({
  actionName: 'CodeBuild',
  project,
  input: sourceOutput,
  environmentVariables: {
    COMMIT_ID: {
      value: sourceAction.variables.commitId,
    },
  },
});
python
# project: codebuild.PipelineProject
# repo: codecommit.Repository

source_output = codepipeline.Artifact()
source_action = codepipeline_actions.CodeCommitSourceAction(
    action_name="CodeCommit",
    repository=repo,
    output=source_output,
    variables_namespace="MyNamespace"
)

# later:

codepipeline_actions.CodeBuildAction(
    action_name="CodeBuild",
    project=project,
    input=source_output,
    environment_variables={
        "COMMIT_ID": codebuild.BuildEnvironmentVariable(
            value=source_action.variables.commit_id
        )
    }
)
java
PipelineProject project;
Repository repo;

Artifact sourceOutput = new Artifact();
CodeCommitSourceAction sourceAction = CodeCommitSourceAction.Builder.create()
        .actionName("CodeCommit")
        .repository(repo)
        .output(sourceOutput)
        .variablesNamespace("MyNamespace")
        .build();

// later:

// later:
CodeBuildAction.Builder.create()
        .actionName("CodeBuild")
        .project(project)
        .input(sourceOutput)
        .environmentVariables(Map.of(
                "COMMIT_ID", BuildEnvironmentVariable.builder()
                        .value(sourceAction.getVariables().getCommitId())
                        .build()))
        .build();
csharp
PipelineProject project;
Repository repo;

var sourceOutput = new Artifact();
var sourceAction = new CodeCommitSourceAction(new CodeCommitSourceActionProps {
    ActionName = "CodeCommit",
    Repository = repo,
    Output = sourceOutput,
    VariablesNamespace = "MyNamespace"
});

// later:

// later:
new CodeBuildAction(new CodeBuildActionProps {
    ActionName = "CodeBuild",
    Project = project,
    Input = sourceOutput,
    EnvironmentVariables = new Dictionary<string, BuildEnvironmentVariable> {
        { "COMMIT_ID", new BuildEnvironmentVariable {
            Value = sourceAction.Variables.CommitId
        } }
    }
});
go
var project PipelineProject
var repo Repository

sourceOutput := codepipeline.NewArtifact()
sourceAction := codepipeline_actions.NewCodeCommitSourceAction(&CodeCommitSourceActionProps{
	ActionName: jsii.String("CodeCommit"),
	Repository: repo,
	Output: sourceOutput,
	VariablesNamespace: jsii.String("MyNamespace"),
})

// later:

// later:
codepipeline_actions.NewCodeBuildAction(&CodeBuildActionProps{
	ActionName: jsii.String("CodeBuild"),
	Project: Project,
	Input: sourceOutput,
	EnvironmentVariables: map[string]BuildEnvironmentVariable{
		"COMMIT_ID": &BuildEnvironmentVariable{
			"value": sourceAction.variables.commitId,
		},
	},
})

If you want to use a custom event for your CodeCommitSourceAction, you can pass in a customEventRule which needs an event pattern (see here) and an IRuleTarget (see here)

ts
const eventPattern = {
  'detail-type': ['CodeCommit Repository State Change'],
  'resources': ['foo'],
  'source': ['aws.codecommit'],
  'detail': {
    referenceType: ['branch'],
    event: ['referenceCreated', 'referenceUpdated'],
    referenceName: ['master'],
  },
};
declare const repo: codecommit.Repository;
declare const lambdaFunction: lambda.Function;
const sourceOutput = new codepipeline.Artifact();
const sourceAction = new codepipeline_actions.CodeCommitSourceAction({
  actionName: 'CodeCommit',
  repository: repo,
  output: sourceOutput,
  customEventRule: {
    eventPattern,
    target: new targets.LambdaFunction(lambdaFunction),
  }
});
python
# repo: codecommit.Repository
# lambda_function: lambda.Function
event_pattern = {
    "detail-type": ["CodeCommit Repository State Change"],
    "resources": ["foo"],
    "source": ["aws.codecommit"],
    "detail": {
        "reference_type": ["branch"],
        "event": ["referenceCreated", "referenceUpdated"],
        "reference_name": ["master"]
    }
}
source_output = codepipeline.Artifact()
source_action = codepipeline_actions.CodeCommitSourceAction(
    action_name="CodeCommit",
    repository=repo,
    output=source_output,
    custom_event_rule={
        "event_pattern": event_pattern,
        "target": targets.LambdaFunction(lambda_function)
    }
)
java
Repository repo;
Function lambdaFunction;
Map<String, Object> eventPattern = Map.of(
        "detail-type", List.of("CodeCommit Repository State Change"),
        "resources", List.of("foo"),
        "source", List.of("aws.codecommit"),
        "detail", Map.of(
                "referenceType", List.of("branch"),
                "event", List.of("referenceCreated", "referenceUpdated"),
                "referenceName", List.of("master")));
Artifact sourceOutput = new Artifact();
CodeCommitSourceAction sourceAction = CodeCommitSourceAction.Builder.create()
        .actionName("CodeCommit")
        .repository(repo)
        .output(sourceOutput)
        .customEventRule(Map.of(
                "eventPattern", eventPattern,
                "target", new LambdaFunction(lambdaFunction)))
        .build();
csharp
Repository repo;
Function lambdaFunction;
IDictionary<string, object> eventPattern = new Dictionary<string, object> {
    { "detail-type", new [] { "CodeCommit Repository State Change" } },
    { "resources", new [] { "foo" } },
    { "source", new [] { "aws.codecommit" } },
    { "detail", new Dictionary<string, string[]> {
        { "referenceType", new [] { "branch" } },
        { "event", new [] { "referenceCreated", "referenceUpdated" } },
        { "referenceName", new [] { "master" } }
    } }
};
var sourceOutput = new Artifact();
var sourceAction = new CodeCommitSourceAction(new CodeCommitSourceActionProps {
    ActionName = "CodeCommit",
    Repository = repo,
    Output = sourceOutput,
    CustomEventRule = new Dictionary<string, object> {
        { "eventPattern", eventPattern },
        { "target", new LambdaFunction(lambdaFunction) }
    }
});
go
var repo Repository
var lambdaFunction Function
eventPattern := map[string]interface{}{
	"detail-type": []*string{
		jsii.String("CodeCommit Repository State Change"),
	},
	"resources": []*string{
		jsii.String("foo"),
	},
	"source": []*string{
		jsii.String("aws.codecommit"),
	},
	"detail": map[string][]*string{
		"referenceType": []*string{
			jsii.String("branch"),
		},
		"event": []*string{
			jsii.String("referenceCreated"),
			jsii.String("referenceUpdated"),
		},
		"referenceName": []*string{
			jsii.String("master"),
		},
	},
}
sourceOutput := codepipeline.NewArtifact()
sourceAction := codepipeline_actions.NewCodeCommitSourceAction(&CodeCommitSourceActionProps{
	ActionName: jsii.String("CodeCommit"),
	Repository: repo,
	Output: sourceOutput,
	CustomEventRule: map[string]interface{}{
		"eventPattern": eventPattern,
		"target": targets.NewLambdaFunction(lambdaFunction),
	},
})

GitHub ​

If you want to use a GitHub repository as the source, you must create:

  • A GitHub Access Token, with scopes repo and admin:repo_hook.
  • A Secrets Manager Secret with the value of the GitHub Access Token. Pick whatever name you want (for example my-github-token). This token can be stored either as Plaintext or as a Secret key/value. If you stored the token as Plaintext, set SecretValue.secretsManager('my-github-token') as the value of oauthToken. If you stored it as a Secret key/value, you must set SecretValue.secretsManager('my-github-token', { jsonField : 'my-github-token' }) as the value of oauthToken.

To use GitHub as the source of a CodePipeline:

ts
// Read the secret from Secrets Manager
const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const sourceOutput = new codepipeline.Artifact();
const sourceAction = new codepipeline_actions.GitHubSourceAction({
  actionName: 'GitHub_Source',
  owner: 'awslabs',
  repo: 'aws-cdk',
  oauthToken: SecretValue.secretsManager('my-github-token'),
  output: sourceOutput,
  branch: 'develop', // default: 'master'
});
pipeline.addStage({
  stageName: 'Source',
  actions: [sourceAction],
});
python
# Read the secret from Secrets Manager
pipeline = codepipeline.Pipeline(self, "MyPipeline")
source_output = codepipeline.Artifact()
source_action = codepipeline_actions.GitHubSourceAction(
    action_name="GitHub_Source",
    owner="awslabs",
    repo="aws-cdk",
    oauth_token=SecretValue.secrets_manager("my-github-token"),
    output=source_output,
    branch="develop"
)
pipeline.add_stage(
    stage_name="Source",
    actions=[source_action]
)
java
// Read the secret from Secrets Manager
Pipeline pipeline = new Pipeline(this, "MyPipeline");
Artifact sourceOutput = new Artifact();
GitHubSourceAction sourceAction = GitHubSourceAction.Builder.create()
        .actionName("GitHub_Source")
        .owner("awslabs")
        .repo("aws-cdk")
        .oauthToken(SecretValue.secretsManager("my-github-token"))
        .output(sourceOutput)
        .branch("develop")
        .build();
pipeline.addStage(StageOptions.builder()
        .stageName("Source")
        .actions(List.of(sourceAction))
        .build());
csharp
// Read the secret from Secrets Manager
var pipeline = new Pipeline(this, "MyPipeline");
var sourceOutput = new Artifact();
var sourceAction = new GitHubSourceAction(new GitHubSourceActionProps {
    ActionName = "GitHub_Source",
    Owner = "awslabs",
    Repo = "aws-cdk",
    OauthToken = SecretValue.SecretsManager("my-github-token"),
    Output = sourceOutput,
    Branch = "develop"
});
pipeline.AddStage(new StageOptions {
    StageName = "Source",
    Actions = new [] { sourceAction }
});
go
// Read the secret from Secrets Manager
pipeline := codepipeline.NewPipeline(this, jsii.String("MyPipeline"))
sourceOutput := codepipeline.NewArtifact()
sourceAction := codepipeline_actions.NewGitHubSourceAction(&GitHubSourceActionProps{
	ActionName: jsii.String("GitHub_Source"),
	Owner: jsii.String("awslabs"),
	Repo: jsii.String("aws-cdk"),
	OauthToken: awscdk.SecretValue_SecretsManager(jsii.String("my-github-token")),
	Output: sourceOutput,
	Branch: jsii.String("develop"),
})
pipeline.AddStage(&StageOptions{
	StageName: jsii.String("Source"),
	Actions: []IAction{
		sourceAction,
	},
})

The GitHub source action emits variables:

ts
declare const sourceOutput: codepipeline.Artifact;
declare const project: codebuild.PipelineProject;

const sourceAction = new codepipeline_actions.GitHubSourceAction({
  actionName: 'Github_Source',
  output: sourceOutput,
  owner: 'my-owner',
  repo: 'my-repo',
  oauthToken: SecretValue.secretsManager('my-github-token'),
  variablesNamespace: 'MyNamespace', // optional - by default, a name will be generated for you
});

// later:

new codepipeline_actions.CodeBuildAction({
  actionName: 'CodeBuild',
  project,
  input: sourceOutput,
  environmentVariables: {
    COMMIT_URL: {
      value: sourceAction.variables.commitUrl,
    },
  },
});
python
# source_output: codepipeline.Artifact
# project: codebuild.PipelineProject


source_action = codepipeline_actions.GitHubSourceAction(
    action_name="Github_Source",
    output=source_output,
    owner="my-owner",
    repo="my-repo",
    oauth_token=SecretValue.secrets_manager("my-github-token"),
    variables_namespace="MyNamespace"
)

# later:

codepipeline_actions.CodeBuildAction(
    action_name="CodeBuild",
    project=project,
    input=source_output,
    environment_variables={
        "COMMIT_URL": codebuild.BuildEnvironmentVariable(
            value=source_action.variables.commit_url
        )
    }
)
java
Artifact sourceOutput;
PipelineProject project;


GitHubSourceAction sourceAction = GitHubSourceAction.Builder.create()
        .actionName("Github_Source")
        .output(sourceOutput)
        .owner("my-owner")
        .repo("my-repo")
        .oauthToken(SecretValue.secretsManager("my-github-token"))
        .variablesNamespace("MyNamespace")
        .build();

// later:

// later:
CodeBuildAction.Builder.create()
        .actionName("CodeBuild")
        .project(project)
        .input(sourceOutput)
        .environmentVariables(Map.of(
                "COMMIT_URL", BuildEnvironmentVariable.builder()
                        .value(sourceAction.getVariables().getCommitUrl())
                        .build()))
        .build();
csharp
Artifact sourceOutput;
PipelineProject project;


var sourceAction = new GitHubSourceAction(new GitHubSourceActionProps {
    ActionName = "Github_Source",
    Output = sourceOutput,
    Owner = "my-owner",
    Repo = "my-repo",
    OauthToken = SecretValue.SecretsManager("my-github-token"),
    VariablesNamespace = "MyNamespace"
});

// later:

// later:
new CodeBuildAction(new CodeBuildActionProps {
    ActionName = "CodeBuild",
    Project = project,
    Input = sourceOutput,
    EnvironmentVariables = new Dictionary<string, BuildEnvironmentVariable> {
        { "COMMIT_URL", new BuildEnvironmentVariable {
            Value = sourceAction.Variables.CommitUrl
        } }
    }
});
go
var sourceOutput Artifact
var project PipelineProject


sourceAction := codepipeline_actions.NewGitHubSourceAction(&GitHubSourceActionProps{
	ActionName: jsii.String("Github_Source"),
	Output: sourceOutput,
	Owner: jsii.String("my-owner"),
	Repo: jsii.String("my-repo"),
	OauthToken: awscdk.SecretValue_SecretsManager(jsii.String("my-github-token")),
	VariablesNamespace: jsii.String("MyNamespace"),
})

// later:

// later:
codepipeline_actions.NewCodeBuildAction(&CodeBuildActionProps{
	ActionName: jsii.String("CodeBuild"),
	Project: Project,
	Input: sourceOutput,
	EnvironmentVariables: map[string]BuildEnvironmentVariable{
		"COMMIT_URL": &BuildEnvironmentVariable{
			"value": sourceAction.variables.commitUrl,
		},
	},
})

BitBucket ​

CodePipeline can use a BitBucket Git repository as a source:

Note: you have to manually connect CodePipeline through the AWS Console with your BitBucket account. This is a one-time operation for a given AWS account in a given region. The simplest way to do that is to either start creating a new CodePipeline, or edit an existing one, while being logged in to BitBucket. Choose BitBucket as the source, and grant CodePipeline permissions to your BitBucket account. Copy & paste the Connection ARN that you get in the console, or use the codestar-connections list-connections AWS CLI operation to find it. After that, you can safely abort creating or editing the pipeline - the connection has already been created.

ts
const sourceOutput = new codepipeline.Artifact();
const sourceAction = new codepipeline_actions.CodeStarConnectionsSourceAction({
  actionName: 'BitBucket_Source',
  owner: 'aws',
  repo: 'aws-cdk',
  output: sourceOutput,
  connectionArn: 'arn:aws:codestar-connections:us-east-1:123456789012:connection/12345678-abcd-12ab-34cdef5678gh',
});
python
source_output = codepipeline.Artifact()
source_action = codepipeline_actions.CodeStarConnectionsSourceAction(
    action_name="BitBucket_Source",
    owner="aws",
    repo="aws-cdk",
    output=source_output,
    connection_arn="arn:aws:codestar-connections:us-east-1:123456789012:connection/12345678-abcd-12ab-34cdef5678gh"
)
java
Artifact sourceOutput = new Artifact();
CodeStarConnectionsSourceAction sourceAction = CodeStarConnectionsSourceAction.Builder.create()
        .actionName("BitBucket_Source")
        .owner("aws")
        .repo("aws-cdk")
        .output(sourceOutput)
        .connectionArn("arn:aws:codestar-connections:us-east-1:123456789012:connection/12345678-abcd-12ab-34cdef5678gh")
        .build();
csharp
var sourceOutput = new Artifact();
var sourceAction = new CodeStarConnectionsSourceAction(new CodeStarConnectionsSourceActionProps {
    ActionName = "BitBucket_Source",
    Owner = "aws",
    Repo = "aws-cdk",
    Output = sourceOutput,
    ConnectionArn = "arn:aws:codestar-connections:us-east-1:123456789012:connection/12345678-abcd-12ab-34cdef5678gh"
});
go
sourceOutput := codepipeline.NewArtifact()
sourceAction := codepipeline_actions.NewCodeStarConnectionsSourceAction(&CodeStarConnectionsSourceActionProps{
	ActionName: jsii.String("BitBucket_Source"),
	Owner: jsii.String("aws"),
	Repo: jsii.String("aws-cdk"),
	Output: sourceOutput,
	ConnectionArn: jsii.String("arn:aws:codestar-connections:us-east-1:123456789012:connection/12345678-abcd-12ab-34cdef5678gh"),
})

You can also use the CodeStarConnectionsSourceAction to connect to GitHub, in the same way (you just have to select GitHub as the source when creating the connection in the console).

Similarly to GitHubSourceAction, CodeStarConnectionsSourceAction also emits the variables:

ts
declare const project: codebuild.Project;

const sourceOutput = new codepipeline.Artifact();
const sourceAction = new codepipeline_actions.CodeStarConnectionsSourceAction({
  actionName: 'BitBucket_Source',
  owner: 'aws',
  repo: 'aws-cdk',
  output: sourceOutput,
  connectionArn: 'arn:aws:codestar-connections:us-east-1:123456789012:connection/12345678-abcd-12ab-34cdef5678gh',
  variablesNamespace: 'SomeSpace', // optional - by default, a name will be generated for you
});

// later:

new codepipeline_actions.CodeBuildAction({
  actionName: 'CodeBuild',
  project,
  input: sourceOutput,
  environmentVariables: {
    COMMIT_ID: {
      value: sourceAction.variables.commitId,
    },
  },
});
python
# project: codebuild.Project


source_output = codepipeline.Artifact()
source_action = codepipeline_actions.CodeStarConnectionsSourceAction(
    action_name="BitBucket_Source",
    owner="aws",
    repo="aws-cdk",
    output=source_output,
    connection_arn="arn:aws:codestar-connections:us-east-1:123456789012:connection/12345678-abcd-12ab-34cdef5678gh",
    variables_namespace="SomeSpace"
)

# later:

codepipeline_actions.CodeBuildAction(
    action_name="CodeBuild",
    project=project,
    input=source_output,
    environment_variables={
        "COMMIT_ID": codebuild.BuildEnvironmentVariable(
            value=source_action.variables.commit_id
        )
    }
)
java
Project project;


Artifact sourceOutput = new Artifact();
CodeStarConnectionsSourceAction sourceAction = CodeStarConnectionsSourceAction.Builder.create()
        .actionName("BitBucket_Source")
        .owner("aws")
        .repo("aws-cdk")
        .output(sourceOutput)
        .connectionArn("arn:aws:codestar-connections:us-east-1:123456789012:connection/12345678-abcd-12ab-34cdef5678gh")
        .variablesNamespace("SomeSpace")
        .build();

// later:

// later:
CodeBuildAction.Builder.create()
        .actionName("CodeBuild")
        .project(project)
        .input(sourceOutput)
        .environmentVariables(Map.of(
                "COMMIT_ID", BuildEnvironmentVariable.builder()
                        .value(sourceAction.getVariables().getCommitId())
                        .build()))
        .build();
csharp
Project project;


var sourceOutput = new Artifact();
var sourceAction = new CodeStarConnectionsSourceAction(new CodeStarConnectionsSourceActionProps {
    ActionName = "BitBucket_Source",
    Owner = "aws",
    Repo = "aws-cdk",
    Output = sourceOutput,
    ConnectionArn = "arn:aws:codestar-connections:us-east-1:123456789012:connection/12345678-abcd-12ab-34cdef5678gh",
    VariablesNamespace = "SomeSpace"
});

// later:

// later:
new CodeBuildAction(new CodeBuildActionProps {
    ActionName = "CodeBuild",
    Project = project,
    Input = sourceOutput,
    EnvironmentVariables = new Dictionary<string, BuildEnvironmentVariable> {
        { "COMMIT_ID", new BuildEnvironmentVariable {
            Value = sourceAction.Variables.CommitId
        } }
    }
});
go
var project Project


sourceOutput := codepipeline.NewArtifact()
sourceAction := codepipeline_actions.NewCodeStarConnectionsSourceAction(&CodeStarConnectionsSourceActionProps{
	ActionName: jsii.String("BitBucket_Source"),
	Owner: jsii.String("aws"),
	Repo: jsii.String("aws-cdk"),
	Output: sourceOutput,
	ConnectionArn: jsii.String("arn:aws:codestar-connections:us-east-1:123456789012:connection/12345678-abcd-12ab-34cdef5678gh"),
	VariablesNamespace: jsii.String("SomeSpace"),
})

// later:

// later:
codepipeline_actions.NewCodeBuildAction(&CodeBuildActionProps{
	ActionName: jsii.String("CodeBuild"),
	Project: Project,
	Input: sourceOutput,
	EnvironmentVariables: map[string]BuildEnvironmentVariable{
		"COMMIT_ID": &BuildEnvironmentVariable{
			"value": sourceAction.variables.commitId,
		},
	},
})

AWS S3 Source ​

To use an S3 Bucket as a source in CodePipeline:

ts
const sourceBucket = new s3.Bucket(this, 'MyBucket', {
  versioned: true, // a Bucket used as a source in CodePipeline must be versioned
});

const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const sourceOutput = new codepipeline.Artifact();
const sourceAction = new codepipeline_actions.S3SourceAction({
  actionName: 'S3Source',
  bucket: sourceBucket,
  bucketKey: 'path/to/file.zip',
  output: sourceOutput,
});
pipeline.addStage({
  stageName: 'Source',
  actions: [sourceAction],
});
python
source_bucket = s3.Bucket(self, "MyBucket",
    versioned=True
)

pipeline = codepipeline.Pipeline(self, "MyPipeline")
source_output = codepipeline.Artifact()
source_action = codepipeline_actions.S3SourceAction(
    action_name="S3Source",
    bucket=source_bucket,
    bucket_key="path/to/file.zip",
    output=source_output
)
pipeline.add_stage(
    stage_name="Source",
    actions=[source_action]
)
java
Bucket sourceBucket = Bucket.Builder.create(this, "MyBucket")
        .versioned(true)
        .build();

Pipeline pipeline = new Pipeline(this, "MyPipeline");
Artifact sourceOutput = new Artifact();
S3SourceAction sourceAction = S3SourceAction.Builder.create()
        .actionName("S3Source")
        .bucket(sourceBucket)
        .bucketKey("path/to/file.zip")
        .output(sourceOutput)
        .build();
pipeline.addStage(StageOptions.builder()
        .stageName("Source")
        .actions(List.of(sourceAction))
        .build());
csharp
var sourceBucket = new Bucket(this, "MyBucket", new BucketProps {
    Versioned = true
});

var pipeline = new Pipeline(this, "MyPipeline");
var sourceOutput = new Artifact();
var sourceAction = new S3SourceAction(new S3SourceActionProps {
    ActionName = "S3Source",
    Bucket = sourceBucket,
    BucketKey = "path/to/file.zip",
    Output = sourceOutput
});
pipeline.AddStage(new StageOptions {
    StageName = "Source",
    Actions = new [] { sourceAction }
});
go
sourceBucket := s3.NewBucket(this, jsii.String("MyBucket"), &BucketProps{
	Versioned: jsii.Boolean(true),
})

pipeline := codepipeline.NewPipeline(this, jsii.String("MyPipeline"))
sourceOutput := codepipeline.NewArtifact()
sourceAction := codepipeline_actions.NewS3SourceAction(&S3SourceActionProps{
	ActionName: jsii.String("S3Source"),
	Bucket: sourceBucket,
	BucketKey: jsii.String("path/to/file.zip"),
	Output: sourceOutput,
})
pipeline.AddStage(&StageOptions{
	StageName: jsii.String("Source"),
	Actions: []IAction{
		sourceAction,
	},
})

The region of the action will be determined by the region the bucket itself is in. When using a newly created bucket, that region will be taken from the stack the bucket belongs to; for an imported bucket, you can specify the region explicitly:

ts
const sourceBucket = s3.Bucket.fromBucketAttributes(this, 'SourceBucket', {
  bucketName: 'amzn-s3-demo-bucket',
  region: 'ap-southeast-1',
});
python
source_bucket = s3.Bucket.from_bucket_attributes(self, "SourceBucket",
    bucket_name="amzn-s3-demo-bucket",
    region="ap-southeast-1"
)
java
IBucket sourceBucket = Bucket.fromBucketAttributes(this, "SourceBucket", BucketAttributes.builder()
        .bucketName("amzn-s3-demo-bucket")
        .region("ap-southeast-1")
        .build());
csharp
var sourceBucket = Bucket.FromBucketAttributes(this, "SourceBucket", new BucketAttributes {
    BucketName = "amzn-s3-demo-bucket",
    Region = "ap-southeast-1"
});
go
sourceBucket := s3.Bucket_FromBucketAttributes(this, jsii.String("SourceBucket"), &BucketAttributes{
	BucketName: jsii.String("amzn-s3-demo-bucket"),
	Region: jsii.String("ap-southeast-1"),
})

By default, the Pipeline will poll the Bucket to detect changes. You can change that behavior to use CloudWatch Events by setting the trigger property to S3Trigger.EVENTS (it's S3Trigger.POLL by default). If you do that, make sure the source Bucket is part of an AWS CloudTrail Trail - otherwise, the CloudWatch Events will not be emitted, and your Pipeline will not react to changes in the Bucket. You can do it through the CDK:

ts
import * as cloudtrail from 'aws-cdk-lib/aws-cloudtrail';

declare const sourceBucket: s3.Bucket;
const sourceOutput = new codepipeline.Artifact();
const key = 'some/key.zip';
const trail = new cloudtrail.Trail(this, 'CloudTrail');
trail.addS3EventSelector([{
  bucket: sourceBucket,
  objectPrefix: key,
}], {
  readWriteType: cloudtrail.ReadWriteType.WRITE_ONLY,
});
const sourceAction = new codepipeline_actions.S3SourceAction({
  actionName: 'S3Source',
  bucketKey: key,
  bucket: sourceBucket,
  output: sourceOutput,
  trigger: codepipeline_actions.S3Trigger.EVENTS, // default: S3Trigger.POLL
});
python
import aws_cdk.aws_cloudtrail as cloudtrail

# source_bucket: s3.Bucket

source_output = codepipeline.Artifact()
key = "some/key.zip"
trail = cloudtrail.Trail(self, "CloudTrail")
trail.add_s3_event_selector([cloudtrail.S3EventSelector(
    bucket=source_bucket,
    object_prefix=key
)],
    read_write_type=cloudtrail.ReadWriteType.WRITE_ONLY
)
source_action = codepipeline_actions.S3SourceAction(
    action_name="S3Source",
    bucket_key=key,
    bucket=source_bucket,
    output=source_output,
    trigger=codepipeline_actions.S3Trigger.EVENTS
)
java
import software.amazon.awscdk.services.cloudtrail.*;

Bucket sourceBucket;

Artifact sourceOutput = new Artifact();
String key = "some/key.zip";
Trail trail = new Trail(this, "CloudTrail");
trail.addS3EventSelector(List.of(S3EventSelector.builder()
        .bucket(sourceBucket)
        .objectPrefix(key)
        .build()), AddEventSelectorOptions.builder()
        .readWriteType(ReadWriteType.WRITE_ONLY)
        .build());
S3SourceAction sourceAction = S3SourceAction.Builder.create()
        .actionName("S3Source")
        .bucketKey(key)
        .bucket(sourceBucket)
        .output(sourceOutput)
        .trigger(S3Trigger.EVENTS)
        .build();
csharp
using Amazon.CDK.AWS.CloudTrail;

Bucket sourceBucket;

var sourceOutput = new Artifact();
var key = "some/key.zip";
var trail = new Trail(this, "CloudTrail");
trail.AddS3EventSelector(new [] { new S3EventSelector {
    Bucket = sourceBucket,
    ObjectPrefix = key
} }, new AddEventSelectorOptions {
    ReadWriteType = ReadWriteType.WRITE_ONLY
});
var sourceAction = new S3SourceAction(new S3SourceActionProps {
    ActionName = "S3Source",
    BucketKey = key,
    Bucket = sourceBucket,
    Output = sourceOutput,
    Trigger = S3Trigger.EVENTS
});
go
import "github.com/aws/aws-cdk-go/awscdk"

var sourceBucket Bucket

sourceOutput := codepipeline.NewArtifact()
key := "some/key.zip"
trail := cloudtrail.NewTrail(this, jsii.String("CloudTrail"))
trail.AddS3EventSelector([]S3EventSelector{
	&S3EventSelector{
		Bucket: sourceBucket,
		ObjectPrefix: key,
	},
}, &AddEventSelectorOptions{
	ReadWriteType: cloudtrail.ReadWriteType_WRITE_ONLY,
})
sourceAction := codepipeline_actions.NewS3SourceAction(&S3SourceActionProps{
	ActionName: jsii.String("S3Source"),
	BucketKey: key,
	Bucket: sourceBucket,
	Output: sourceOutput,
	Trigger: codepipeline_actions.S3Trigger_EVENTS,
})

The S3 source action emits variables:

ts
const key = 'some/key.zip';
declare const sourceBucket: s3.Bucket;
const sourceOutput = new codepipeline.Artifact();
const sourceAction = new codepipeline_actions.S3SourceAction({
  actionName: 'S3Source',
  bucketKey: key,
  bucket: sourceBucket,
  output: sourceOutput,
  variablesNamespace: 'MyNamespace', // optional - by default, a name will be generated for you
});

// later:
declare const project: codebuild.PipelineProject;
new codepipeline_actions.CodeBuildAction({
  actionName: 'CodeBuild',
  project,
  input: sourceOutput,
  environmentVariables: {
    VERSION_ID: {
      value: sourceAction.variables.versionId,
    },
  },
});
python
# source_bucket: s3.Bucket

# later:
# project: codebuild.PipelineProject
key = "some/key.zip"
source_output = codepipeline.Artifact()
source_action = codepipeline_actions.S3SourceAction(
    action_name="S3Source",
    bucket_key=key,
    bucket=source_bucket,
    output=source_output,
    variables_namespace="MyNamespace"
)
codepipeline_actions.CodeBuildAction(
    action_name="CodeBuild",
    project=project,
    input=source_output,
    environment_variables={
        "VERSION_ID": codebuild.BuildEnvironmentVariable(
            value=source_action.variables.version_id
        )
    }
)
java
Bucket sourceBucket;

// later:
PipelineProject project;
String key = "some/key.zip";
Artifact sourceOutput = new Artifact();
S3SourceAction sourceAction = S3SourceAction.Builder.create()
        .actionName("S3Source")
        .bucketKey(key)
        .bucket(sourceBucket)
        .output(sourceOutput)
        .variablesNamespace("MyNamespace")
        .build();
CodeBuildAction.Builder.create()
        .actionName("CodeBuild")
        .project(project)
        .input(sourceOutput)
        .environmentVariables(Map.of(
                "VERSION_ID", BuildEnvironmentVariable.builder()
                        .value(sourceAction.getVariables().getVersionId())
                        .build()))
        .build();
csharp
Bucket sourceBucket;

// later:
PipelineProject project;
var key = "some/key.zip";
var sourceOutput = new Artifact();
var sourceAction = new S3SourceAction(new S3SourceActionProps {
    ActionName = "S3Source",
    BucketKey = key,
    Bucket = sourceBucket,
    Output = sourceOutput,
    VariablesNamespace = "MyNamespace"
});
new CodeBuildAction(new CodeBuildActionProps {
    ActionName = "CodeBuild",
    Project = project,
    Input = sourceOutput,
    EnvironmentVariables = new Dictionary<string, BuildEnvironmentVariable> {
        { "VERSION_ID", new BuildEnvironmentVariable {
            Value = sourceAction.Variables.VersionId
        } }
    }
});
go
var sourceBucket Bucket

// later:
var project PipelineProject
key := "some/key.zip"
sourceOutput := codepipeline.NewArtifact()
sourceAction := codepipeline_actions.NewS3SourceAction(&S3SourceActionProps{
	ActionName: jsii.String("S3Source"),
	BucketKey: key,
	Bucket: sourceBucket,
	Output: sourceOutput,
	VariablesNamespace: jsii.String("MyNamespace"),
})
codepipeline_actions.NewCodeBuildAction(&CodeBuildActionProps{
	ActionName: jsii.String("CodeBuild"),
	Project: Project,
	Input: sourceOutput,
	EnvironmentVariables: map[string]BuildEnvironmentVariable{
		"VERSION_ID": &BuildEnvironmentVariable{
			"value": sourceAction.variables.versionId,
		},
	},
})

AWS ECR ​

To use an ECR Repository as a source in a Pipeline:

ts
import * as ecr from 'aws-cdk-lib/aws-ecr';

declare const ecrRepository: ecr.Repository;
const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const sourceOutput = new codepipeline.Artifact();
const sourceAction = new codepipeline_actions.EcrSourceAction({
  actionName: 'ECR',
  repository: ecrRepository,
  imageTag: 'some-tag', // optional, default: 'latest'
  output: sourceOutput,
});
pipeline.addStage({
  stageName: 'Source',
  actions: [sourceAction],
});
python
import aws_cdk.aws_ecr as ecr

# ecr_repository: ecr.Repository

pipeline = codepipeline.Pipeline(self, "MyPipeline")
source_output = codepipeline.Artifact()
source_action = codepipeline_actions.EcrSourceAction(
    action_name="ECR",
    repository=ecr_repository,
    image_tag="some-tag",  # optional, default: 'latest'
    output=source_output
)
pipeline.add_stage(
    stage_name="Source",
    actions=[source_action]
)
java
import software.amazon.awscdk.services.ecr.*;

Repository ecrRepository;

Pipeline pipeline = new Pipeline(this, "MyPipeline");
Artifact sourceOutput = new Artifact();
EcrSourceAction sourceAction = EcrSourceAction.Builder.create()
        .actionName("ECR")
        .repository(ecrRepository)
        .imageTag("some-tag") // optional, default: 'latest'
        .output(sourceOutput)
        .build();
pipeline.addStage(StageOptions.builder()
        .stageName("Source")
        .actions(List.of(sourceAction))
        .build());
csharp
using Amazon.CDK.AWS.ECR;

Repository ecrRepository;

var pipeline = new Pipeline(this, "MyPipeline");
var sourceOutput = new Artifact();
var sourceAction = new EcrSourceAction(new EcrSourceActionProps {
    ActionName = "ECR",
    Repository = ecrRepository,
    ImageTag = "some-tag",  // optional, default: 'latest'
    Output = sourceOutput
});
pipeline.AddStage(new StageOptions {
    StageName = "Source",
    Actions = new [] { sourceAction }
});
go
import ecr "github.com/aws/aws-cdk-go/awscdk"

var ecrRepository Repository

pipeline := codepipeline.NewPipeline(this, jsii.String("MyPipeline"))
sourceOutput := codepipeline.NewArtifact()
sourceAction := codepipeline_actions.NewEcrSourceAction(&EcrSourceActionProps{
	ActionName: jsii.String("ECR"),
	Repository: ecrRepository,
	ImageTag: jsii.String("some-tag"),
	 // optional, default: 'latest'
	Output: sourceOutput,
})
pipeline.AddStage(&StageOptions{
	StageName: jsii.String("Source"),
	Actions: []IAction{
		sourceAction,
	},
})

The ECR source action emits variables:

ts
import * as ecr from 'aws-cdk-lib/aws-ecr';

const sourceOutput = new codepipeline.Artifact();
declare const ecrRepository: ecr.Repository;
const sourceAction = new codepipeline_actions.EcrSourceAction({
  actionName: 'Source',
  output: sourceOutput,
  repository: ecrRepository,
  variablesNamespace: 'MyNamespace', // optional - by default, a name will be generated for you
});

// later:
declare const project: codebuild.PipelineProject;
new codepipeline_actions.CodeBuildAction({
  actionName: 'CodeBuild',
  project,
  input: sourceOutput,
  environmentVariables: {
    IMAGE_URI: {
      value: sourceAction.variables.imageUri,
    },
  },
});
python
import aws_cdk.aws_ecr as ecr
# ecr_repository: ecr.Repository

# later:
# project: codebuild.PipelineProject


source_output = codepipeline.Artifact()
source_action = codepipeline_actions.EcrSourceAction(
    action_name="Source",
    output=source_output,
    repository=ecr_repository,
    variables_namespace="MyNamespace"
)
codepipeline_actions.CodeBuildAction(
    action_name="CodeBuild",
    project=project,
    input=source_output,
    environment_variables={
        "IMAGE_URI": codebuild.BuildEnvironmentVariable(
            value=source_action.variables.image_uri
        )
    }
)
java
import software.amazon.awscdk.services.ecr.*;
Repository ecrRepository;

// later:
PipelineProject project;


Artifact sourceOutput = new Artifact();
EcrSourceAction sourceAction = EcrSourceAction.Builder.create()
        .actionName("Source")
        .output(sourceOutput)
        .repository(ecrRepository)
        .variablesNamespace("MyNamespace")
        .build();
CodeBuildAction.Builder.create()
        .actionName("CodeBuild")
        .project(project)
        .input(sourceOutput)
        .environmentVariables(Map.of(
                "IMAGE_URI", BuildEnvironmentVariable.builder()
                        .value(sourceAction.getVariables().getImageUri())
                        .build()))
        .build();
csharp
using Amazon.CDK.AWS.ECR;
Repository ecrRepository;

// later:
PipelineProject project;


var sourceOutput = new Artifact();
var sourceAction = new EcrSourceAction(new EcrSourceActionProps {
    ActionName = "Source",
    Output = sourceOutput,
    Repository = ecrRepository,
    VariablesNamespace = "MyNamespace"
});
new CodeBuildAction(new CodeBuildActionProps {
    ActionName = "CodeBuild",
    Project = project,
    Input = sourceOutput,
    EnvironmentVariables = new Dictionary<string, BuildEnvironmentVariable> {
        { "IMAGE_URI", new BuildEnvironmentVariable {
            Value = sourceAction.Variables.ImageUri
        } }
    }
});
go
import ecr "github.com/aws/aws-cdk-go/awscdk"
var ecrRepository Repository

// later:
var project PipelineProject


sourceOutput := codepipeline.NewArtifact()
sourceAction := codepipeline_actions.NewEcrSourceAction(&EcrSourceActionProps{
	ActionName: jsii.String("Source"),
	Output: sourceOutput,
	Repository: ecrRepository,
	VariablesNamespace: jsii.String("MyNamespace"),
})
codepipeline_actions.NewCodeBuildAction(&CodeBuildActionProps{
	ActionName: jsii.String("CodeBuild"),
	Project: Project,
	Input: sourceOutput,
	EnvironmentVariables: map[string]BuildEnvironmentVariable{
		"IMAGE_URI": &BuildEnvironmentVariable{
			"value": sourceAction.variables.imageUri,
		},
	},
})

Build & test ​

AWS CodeBuild ​

Example of a CodeBuild Project used in a Pipeline, alongside CodeCommit:

ts
declare const project: codebuild.PipelineProject;
const repository = new codecommit.Repository(this, 'MyRepository', {
  repositoryName: 'MyRepository',
});
const project = new codebuild.PipelineProject(this, 'MyProject');

const sourceOutput = new codepipeline.Artifact();
const sourceAction = new codepipeline_actions.CodeCommitSourceAction({
  actionName: 'CodeCommit',
  repository,
  output: sourceOutput,
});
const buildAction = new codepipeline_actions.CodeBuildAction({
  actionName: 'CodeBuild',
  project,
  input: sourceOutput,
  outputs: [new codepipeline.Artifact()], // optional
  executeBatchBuild: true, // optional, defaults to false
  combineBatchBuildArtifacts: true, // optional, defaults to false
});

new codepipeline.Pipeline(this, 'MyPipeline', {
  stages: [
    {
      stageName: 'Source',
      actions: [sourceAction],
    },
    {
      stageName: 'Build',
      actions: [buildAction],
    },
  ],
});
python
# project: codebuild.PipelineProject

repository = codecommit.Repository(self, "MyRepository",
    repository_name="MyRepository"
)
project = codebuild.PipelineProject(self, "MyProject")

source_output = codepipeline.Artifact()
source_action = codepipeline_actions.CodeCommitSourceAction(
    action_name="CodeCommit",
    repository=repository,
    output=source_output
)
build_action = codepipeline_actions.CodeBuildAction(
    action_name="CodeBuild",
    project=project,
    input=source_output,
    outputs=[codepipeline.Artifact()],  # optional
    execute_batch_build=True,  # optional, defaults to false
    combine_batch_build_artifacts=True
)

codepipeline.Pipeline(self, "MyPipeline",
    stages=[codepipeline.StageProps(
        stage_name="Source",
        actions=[source_action]
    ), codepipeline.StageProps(
        stage_name="Build",
        actions=[build_action]
    )
    ]
)
java
PipelineProject project;

Repository repository = Repository.Builder.create(this, "MyRepository")
        .repositoryName("MyRepository")
        .build();
PipelineProject project = new PipelineProject(this, "MyProject");

Artifact sourceOutput = new Artifact();
CodeCommitSourceAction sourceAction = CodeCommitSourceAction.Builder.create()
        .actionName("CodeCommit")
        .repository(repository)
        .output(sourceOutput)
        .build();
CodeBuildAction buildAction = CodeBuildAction.Builder.create()
        .actionName("CodeBuild")
        .project(project)
        .input(sourceOutput)
        .outputs(List.of(new Artifact())) // optional
        .executeBatchBuild(true) // optional, defaults to false
        .combineBatchBuildArtifacts(true)
        .build();

Pipeline.Builder.create(this, "MyPipeline")
        .stages(List.of(StageProps.builder()
                .stageName("Source")
                .actions(List.of(sourceAction))
                .build(), StageProps.builder()
                .stageName("Build")
                .actions(List.of(buildAction))
                .build()))
        .build();
csharp
PipelineProject project;

var repository = new Repository(this, "MyRepository", new RepositoryProps {
    RepositoryName = "MyRepository"
});
var project = new PipelineProject(this, "MyProject");

var sourceOutput = new Artifact();
var sourceAction = new CodeCommitSourceAction(new CodeCommitSourceActionProps {
    ActionName = "CodeCommit",
    Repository = repository,
    Output = sourceOutput
});
var buildAction = new CodeBuildAction(new CodeBuildActionProps {
    ActionName = "CodeBuild",
    Project = project,
    Input = sourceOutput,
    Outputs = new [] { new Artifact() },  // optional
    ExecuteBatchBuild = true,  // optional, defaults to false
    CombineBatchBuildArtifacts = true
});

new Pipeline(this, "MyPipeline", new PipelineProps {
    Stages = new [] { new StageProps {
        StageName = "Source",
        Actions = new [] { sourceAction }
    }, new StageProps {
        StageName = "Build",
        Actions = new [] { buildAction }
    } }
});
go
var project PipelineProject

repository := codecommit.NewRepository(this, jsii.String("MyRepository"), &RepositoryProps{
	RepositoryName: jsii.String("MyRepository"),
})
project := codebuild.NewPipelineProject(this, jsii.String("MyProject"))

sourceOutput := codepipeline.NewArtifact()
sourceAction := codepipeline_actions.NewCodeCommitSourceAction(&CodeCommitSourceActionProps{
	ActionName: jsii.String("CodeCommit"),
	Repository: Repository,
	Output: sourceOutput,
})
buildAction := codepipeline_actions.NewCodeBuildAction(&CodeBuildActionProps{
	ActionName: jsii.String("CodeBuild"),
	Project: Project,
	Input: sourceOutput,
	Outputs: []Artifact{
		codepipeline.NewArtifact(),
	},
	 // optional
	ExecuteBatchBuild: jsii.Boolean(true),
	 // optional, defaults to false
	CombineBatchBuildArtifacts: jsii.Boolean(true),
})

codepipeline.NewPipeline(this, jsii.String("MyPipeline"), &PipelineProps{
	Stages: []StageProps{
		&StageProps{
			StageName: jsii.String("Source"),
			Actions: []IAction{
				sourceAction,
			},
		},
		&StageProps{
			StageName: jsii.String("Build"),
			Actions: []IAction{
				buildAction,
			},
		},
	},
})

The default category of the CodeBuild Action is Build; if you want a Test Action instead, override the type property:

ts
declare const project: codebuild.PipelineProject;
const sourceOutput = new codepipeline.Artifact();
const testAction = new codepipeline_actions.CodeBuildAction({
  actionName: 'IntegrationTest',
  project,
  input: sourceOutput,
  type: codepipeline_actions.CodeBuildActionType.TEST, // default is BUILD
});
python
# project: codebuild.PipelineProject

source_output = codepipeline.Artifact()
test_action = codepipeline_actions.CodeBuildAction(
    action_name="IntegrationTest",
    project=project,
    input=source_output,
    type=codepipeline_actions.CodeBuildActionType.TEST
)
java
PipelineProject project;

Artifact sourceOutput = new Artifact();
CodeBuildAction testAction = CodeBuildAction.Builder.create()
        .actionName("IntegrationTest")
        .project(project)
        .input(sourceOutput)
        .type(CodeBuildActionType.TEST)
        .build();
csharp
PipelineProject project;

var sourceOutput = new Artifact();
var testAction = new CodeBuildAction(new CodeBuildActionProps {
    ActionName = "IntegrationTest",
    Project = project,
    Input = sourceOutput,
    Type = CodeBuildActionType.TEST
});
go
var project PipelineProject

sourceOutput := codepipeline.NewArtifact()
testAction := codepipeline_actions.NewCodeBuildAction(&CodeBuildActionProps{
	ActionName: jsii.String("IntegrationTest"),
	Project: Project,
	Input: sourceOutput,
	Type: codepipeline_actions.CodeBuildActionType_TEST,
})

Multiple inputs and outputs ​

When you want to have multiple inputs and/or outputs for a Project used in a Pipeline, instead of using the secondarySources and secondaryArtifacts properties of the Project class, you need to use the extraInputs and outputs properties of the CodeBuild CodePipeline Actions. Example:

ts
declare const repository1: codecommit.Repository;
const sourceOutput1 = new codepipeline.Artifact();
const sourceAction1 = new codepipeline_actions.CodeCommitSourceAction({
  actionName: 'Source1',
  repository: repository1,
  output: sourceOutput1,
});
declare const repository2: codecommit.Repository;
const sourceOutput2 = new codepipeline.Artifact('source2');
const sourceAction2 = new codepipeline_actions.CodeCommitSourceAction({
  actionName: 'Source2',
  repository: repository2,
  output: sourceOutput2,
});

declare const project: codebuild.PipelineProject;
const buildAction = new codepipeline_actions.CodeBuildAction({
  actionName: 'Build',
  project,
  input: sourceOutput1,
  extraInputs: [
    sourceOutput2, // this is where 'source2' comes from
  ],
  outputs: [
    new codepipeline.Artifact('artifact1'), // for better buildspec readability - see below
    new codepipeline.Artifact('artifact2'),
  ],
});
python
# repository1: codecommit.Repository
# repository2: codecommit.Repository

# project: codebuild.PipelineProject

source_output1 = codepipeline.Artifact()
source_action1 = codepipeline_actions.CodeCommitSourceAction(
    action_name="Source1",
    repository=repository1,
    output=source_output1
)
source_output2 = codepipeline.Artifact("source2")
source_action2 = codepipeline_actions.CodeCommitSourceAction(
    action_name="Source2",
    repository=repository2,
    output=source_output2
)
build_action = codepipeline_actions.CodeBuildAction(
    action_name="Build",
    project=project,
    input=source_output1,
    extra_inputs=[source_output2
    ],
    outputs=[
        codepipeline.Artifact("artifact1"),  # for better buildspec readability - see below
        codepipeline.Artifact("artifact2")
    ]
)
java
Repository repository1;
Repository repository2;

PipelineProject project;

Artifact sourceOutput1 = new Artifact();
CodeCommitSourceAction sourceAction1 = CodeCommitSourceAction.Builder.create()
        .actionName("Source1")
        .repository(repository1)
        .output(sourceOutput1)
        .build();
Artifact sourceOutput2 = new Artifact("source2");
CodeCommitSourceAction sourceAction2 = CodeCommitSourceAction.Builder.create()
        .actionName("Source2")
        .repository(repository2)
        .output(sourceOutput2)
        .build();
CodeBuildAction buildAction = CodeBuildAction.Builder.create()
        .actionName("Build")
        .project(project)
        .input(sourceOutput1)
        .extraInputs(List.of(sourceOutput2))
        .outputs(List.of(
            new Artifact("artifact1"),  // for better buildspec readability - see below
            new Artifact("artifact2")))
        .build();
csharp
Repository repository1;
Repository repository2;

PipelineProject project;

var sourceOutput1 = new Artifact();
var sourceAction1 = new CodeCommitSourceAction(new CodeCommitSourceActionProps {
    ActionName = "Source1",
    Repository = repository1,
    Output = sourceOutput1
});
var sourceOutput2 = new Artifact("source2");
var sourceAction2 = new CodeCommitSourceAction(new CodeCommitSourceActionProps {
    ActionName = "Source2",
    Repository = repository2,
    Output = sourceOutput2
});
var buildAction = new CodeBuildAction(new CodeBuildActionProps {
    ActionName = "Build",
    Project = project,
    Input = sourceOutput1,
    ExtraInputs = new [] { sourceOutput2 },
    Outputs = new [] {
        new Artifact("artifact1"),  // for better buildspec readability - see below
        new Artifact("artifact2") }
});
go
var repository1 Repository
var repository2 Repository

var project PipelineProject

sourceOutput1 := codepipeline.NewArtifact()
sourceAction1 := codepipeline_actions.NewCodeCommitSourceAction(&CodeCommitSourceActionProps{
	ActionName: jsii.String("Source1"),
	Repository: repository1,
	Output: sourceOutput1,
})
sourceOutput2 := codepipeline.NewArtifact(jsii.String("source2"))
sourceAction2 := codepipeline_actions.NewCodeCommitSourceAction(&CodeCommitSourceActionProps{
	ActionName: jsii.String("Source2"),
	Repository: repository2,
	Output: sourceOutput2,
})
buildAction := codepipeline_actions.NewCodeBuildAction(&CodeBuildActionProps{
	ActionName: jsii.String("Build"),
	Project: Project,
	Input: sourceOutput1,
	ExtraInputs: []Artifact{
		sourceOutput2,
	},
	Outputs: []Artifact{
		codepipeline.NewArtifact(jsii.String("artifact1")),
		 // for better buildspec readability - see below
		codepipeline.NewArtifact(jsii.String("artifact2")),
	},
})

Note: when a CodeBuild Action in a Pipeline has more than one output, it only uses the secondary-artifacts field of the buildspec, never the primary output specification directly under artifacts. Because of that, it pays to explicitly name all output artifacts of that Action, like we did above, so that you know what name to use in the buildspec.

Example buildspec for the above project:

ts
const project = new codebuild.PipelineProject(this, 'MyProject', {
  buildSpec: codebuild.BuildSpec.fromObject({
    version: '0.2',
    phases: {
      build: {
        commands: [
          // By default, you're in a directory with the contents of the repository from sourceAction1.
          // Use the CODEBUILD_SRC_DIR_source2 environment variable
          // to get a path to the directory with the contents of the second input repository.
        ],
      },
    },
    artifacts: {
      'secondary-artifacts': {
        'artifact1': {
          // primary Action output artifact,
          // available as buildAction.outputArtifact
        },
        'artifact2': {
          // additional output artifact,
          // available as buildAction.additionalOutputArtifact('artifact2')
        },
      },
    },
  }),
  // ...
});
python
project = codebuild.PipelineProject(self, "MyProject",
    build_spec=codebuild.BuildSpec.from_object({
        "version": "0.2",
        "phases": {
            "build": {
                "commands": []
            }
        },
        "artifacts": {
            "secondary-artifacts": {
                "artifact1": {},
                "artifact2": {}
            }
        }
    })
)
java
PipelineProject project = PipelineProject.Builder.create(this, "MyProject")
        .buildSpec(BuildSpec.fromObject(Map.of(
                "version", "0.2",
                "phases", Map.of(
                        "build", Map.of(
                                "commands", List.of())),
                "artifacts", Map.of(
                        "secondary-artifacts", Map.of(
                                "artifact1", Map.of(),
                                "artifact2", Map.of())))))
        .build();
csharp
var project = new PipelineProject(this, "MyProject", new PipelineProjectProps {
    BuildSpec = BuildSpec.FromObject(new Dictionary<string, object> {
        { "version", "0.2" },
        { "phases", new Dictionary<string, IDictionary<string, object[]>> {
            { "build", new Struct {
                Commands = new [] {  }
            } }
        } },
        { "artifacts", new Dictionary<string, IDictionary<string, IDictionary<string, object>>> {
            { "secondary-artifacts", new Struct {
                Artifact1 = new Struct { },
                Artifact2 = new Struct { }
            } }
        } }
    })
});
go
project := codebuild.NewPipelineProject(this, jsii.String("MyProject"), &PipelineProjectProps{
	BuildSpec: codebuild.BuildSpec_FromObject(map[string]interface{}{
		"version": jsii.String("0.2"),
		"phases": map[string]map[string][]interface{}{
			"build": map[string][]interface{}{
				"commands": []interface{}{
				},
			},
		},
		"artifacts": map[string]map[string]map[string]interface{}{
			"secondary-artifacts": map[string]map[string]interface{}{
				"artifact1": map[string]interface{}{
				},
				"artifact2": map[string]interface{}{
				},
			},
		},
	}),
})

Variables ​

The CodeBuild action emits variables. Unlike many other actions, the variables are not static, but dynamic, defined in the buildspec, in the 'exported-variables' subsection of the 'env' section. Example:

ts
const sourceOutput = new codepipeline.Artifact();
const buildAction = new codepipeline_actions.CodeBuildAction({
  actionName: 'Build1',
  input: sourceOutput,
  project: new codebuild.PipelineProject(this, 'Project', {
    buildSpec: codebuild.BuildSpec.fromObject({
      version: '0.2',
      env: {
        'exported-variables': [
          'MY_VAR',
        ],
      },
      phases: {
        build: {
          commands: 'export MY_VAR="some value"',
        },
      },
    }),
  }),
  variablesNamespace: 'MyNamespace', // optional - by default, a name will be generated for you
});

// later:
declare const project: codebuild.PipelineProject;
new codepipeline_actions.CodeBuildAction({
  actionName: 'CodeBuild',
  project,
  input: sourceOutput,
  environmentVariables: {
    MyVar: {
      value: buildAction.variable('MY_VAR'),
    },
  },
});
python
# later:
# project: codebuild.PipelineProject
source_output = codepipeline.Artifact()
build_action = codepipeline_actions.CodeBuildAction(
    action_name="Build1",
    input=source_output,
    project=codebuild.PipelineProject(self, "Project",
        build_spec=codebuild.BuildSpec.from_object({
            "version": "0.2",
            "env": {
                "exported-variables": ["MY_VAR"
                ]
            },
            "phases": {
                "build": {
                    "commands": "export MY_VAR=\"some value\""
                }
            }
        })
    ),
    variables_namespace="MyNamespace"
)
codepipeline_actions.CodeBuildAction(
    action_name="CodeBuild",
    project=project,
    input=source_output,
    environment_variables={
        "MyVar": codebuild.BuildEnvironmentVariable(
            value=build_action.variable("MY_VAR")
        )
    }
)
java
// later:
PipelineProject project;
Artifact sourceOutput = new Artifact();
CodeBuildAction buildAction = CodeBuildAction.Builder.create()
        .actionName("Build1")
        .input(sourceOutput)
        .project(PipelineProject.Builder.create(this, "Project")
                .buildSpec(BuildSpec.fromObject(Map.of(
                        "version", "0.2",
                        "env", Map.of(
                                "exported-variables", List.of("MY_VAR")),
                        "phases", Map.of(
                                "build", Map.of(
                                        "commands", "export MY_VAR=\"some value\"")))))
                .build())
        .variablesNamespace("MyNamespace")
        .build();
CodeBuildAction.Builder.create()
        .actionName("CodeBuild")
        .project(project)
        .input(sourceOutput)
        .environmentVariables(Map.of(
                "MyVar", BuildEnvironmentVariable.builder()
                        .value(buildAction.variable("MY_VAR"))
                        .build()))
        .build();
csharp
// later:
PipelineProject project;
var sourceOutput = new Artifact();
var buildAction = new CodeBuildAction(new CodeBuildActionProps {
    ActionName = "Build1",
    Input = sourceOutput,
    Project = new PipelineProject(this, "Project", new PipelineProjectProps {
        BuildSpec = BuildSpec.FromObject(new Dictionary<string, object> {
            { "version", "0.2" },
            { "env", new Dictionary<string, string[]> {
                { "exported-variables", new [] { "MY_VAR" } }
            } },
            { "phases", new Dictionary<string, IDictionary<string, string>> {
                { "build", new Struct {
                    Commands = "export MY_VAR=\"some value\""
                } }
            } }
        })
    }),
    VariablesNamespace = "MyNamespace"
});
new CodeBuildAction(new CodeBuildActionProps {
    ActionName = "CodeBuild",
    Project = project,
    Input = sourceOutput,
    EnvironmentVariables = new Dictionary<string, BuildEnvironmentVariable> {
        { "MyVar", new BuildEnvironmentVariable {
            Value = buildAction.Variable("MY_VAR")
        } }
    }
});
go
// later:
var project PipelineProject
sourceOutput := codepipeline.NewArtifact()
buildAction := codepipeline_actions.NewCodeBuildAction(&CodeBuildActionProps{
	ActionName: jsii.String("Build1"),
	Input: sourceOutput,
	Project: codebuild.NewPipelineProject(this, jsii.String("Project"), &PipelineProjectProps{
		BuildSpec: codebuild.BuildSpec_FromObject(map[string]interface{}{
			"version": jsii.String("0.2"),
			"env": map[string][]*string{
				"exported-variables": []*string{
					jsii.String("MY_VAR"),
				},
			},
			"phases": map[string]map[string]*string{
				"build": map[string]*string{
					"commands": jsii.String("export MY_VAR=\"some value\""),
				},
			},
		}),
	}),
	VariablesNamespace: jsii.String("MyNamespace"),
})
codepipeline_actions.NewCodeBuildAction(&CodeBuildActionProps{
	ActionName: jsii.String("CodeBuild"),
	Project: Project,
	Input: sourceOutput,
	EnvironmentVariables: map[string]BuildEnvironmentVariable{
		"MyVar": &BuildEnvironmentVariable{
			"value": buildAction.variable(jsii.String("MY_VAR")),
		},
	},
})

Jenkins ​

In order to use Jenkins Actions in the Pipeline, you first need to create a JenkinsProvider:

ts
const jenkinsProvider = new codepipeline_actions.JenkinsProvider(this, 'JenkinsProvider', {
  providerName: 'MyJenkinsProvider',
  serverUrl: 'http://my-jenkins.com:8080',
  version: '2', // optional, default: '1'
});
python
jenkins_provider = codepipeline_actions.JenkinsProvider(self, "JenkinsProvider",
    provider_name="MyJenkinsProvider",
    server_url="http://my-jenkins.com:8080",
    version="2"
)
java
JenkinsProvider jenkinsProvider = JenkinsProvider.Builder.create(this, "JenkinsProvider")
        .providerName("MyJenkinsProvider")
        .serverUrl("http://my-jenkins.com:8080")
        .version("2")
        .build();
csharp
var jenkinsProvider = new JenkinsProvider(this, "JenkinsProvider", new JenkinsProviderProps {
    ProviderName = "MyJenkinsProvider",
    ServerUrl = "http://my-jenkins.com:8080",
    Version = "2"
});
go
jenkinsProvider := codepipeline_actions.NewJenkinsProvider(this, jsii.String("JenkinsProvider"), &JenkinsProviderProps{
	ProviderName: jsii.String("MyJenkinsProvider"),
	ServerUrl: jsii.String("http://my-jenkins.com:8080"),
	Version: jsii.String("2"),
})

If you've registered a Jenkins provider in a different CDK app, or outside the CDK (in the CodePipeline AWS Console, for example), you can import it:

ts
const jenkinsProvider = codepipeline_actions.JenkinsProvider.fromJenkinsProviderAttributes(this, 'JenkinsProvider', {
  providerName: 'MyJenkinsProvider',
  serverUrl: 'http://my-jenkins.com:8080',
  version: '2', // optional, default: '1'
});
python
jenkins_provider = codepipeline_actions.JenkinsProvider.from_jenkins_provider_attributes(self, "JenkinsProvider",
    provider_name="MyJenkinsProvider",
    server_url="http://my-jenkins.com:8080",
    version="2"
)
java
IJenkinsProvider jenkinsProvider = JenkinsProvider.fromJenkinsProviderAttributes(this, "JenkinsProvider", JenkinsProviderAttributes.builder()
        .providerName("MyJenkinsProvider")
        .serverUrl("http://my-jenkins.com:8080")
        .version("2")
        .build());
csharp
var jenkinsProvider = JenkinsProvider.FromJenkinsProviderAttributes(this, "JenkinsProvider", new JenkinsProviderAttributes {
    ProviderName = "MyJenkinsProvider",
    ServerUrl = "http://my-jenkins.com:8080",
    Version = "2"
});
go
jenkinsProvider := codepipeline_actions.JenkinsProvider_FromJenkinsProviderAttributes(this, jsii.String("JenkinsProvider"), &JenkinsProviderAttributes{
	ProviderName: jsii.String("MyJenkinsProvider"),
	ServerUrl: jsii.String("http://my-jenkins.com:8080"),
	Version: jsii.String("2"),
})

Note that a Jenkins provider (identified by the provider name-category(build/test)-version tuple) must always be registered in the given account, in the given AWS region, before it can be used in CodePipeline.

With a JenkinsProvider, we can create a Jenkins Action:

ts
declare const jenkinsProvider: codepipeline_actions.JenkinsProvider;
const buildAction = new codepipeline_actions.JenkinsAction({
  actionName: 'JenkinsBuild',
  jenkinsProvider: jenkinsProvider,
  projectName: 'MyProject',
  type: codepipeline_actions.JenkinsActionType.BUILD,
});
python
# jenkins_provider: codepipeline_actions.JenkinsProvider

build_action = codepipeline_actions.JenkinsAction(
    action_name="JenkinsBuild",
    jenkins_provider=jenkins_provider,
    project_name="MyProject",
    type=codepipeline_actions.JenkinsActionType.BUILD
)
java
JenkinsProvider jenkinsProvider;

JenkinsAction buildAction = JenkinsAction.Builder.create()
        .actionName("JenkinsBuild")
        .jenkinsProvider(jenkinsProvider)
        .projectName("MyProject")
        .type(JenkinsActionType.BUILD)
        .build();
csharp
JenkinsProvider jenkinsProvider;

var buildAction = new JenkinsAction(new JenkinsActionProps {
    ActionName = "JenkinsBuild",
    JenkinsProvider = jenkinsProvider,
    ProjectName = "MyProject",
    Type = JenkinsActionType.BUILD
});
go
var jenkinsProvider JenkinsProvider

buildAction := codepipeline_actions.NewJenkinsAction(&JenkinsActionProps{
	ActionName: jsii.String("JenkinsBuild"),
	JenkinsProvider: jenkinsProvider,
	ProjectName: jsii.String("MyProject"),
	Type: codepipeline_actions.JenkinsActionType_BUILD,
})

Build ​

ECR Build And Publish ​

This build action ECRBuildAndPublish allows you to automate building and pushing a new image when a change occurs in your source.

This action builds based on a specified Docker file location and pushes the image. This build action is not the same as the Amazon ECR source action in CodePipeline, which triggers pipeline when a change occurs in your Amazon ECR source repository.

For information about the ECRBuildAndPublish build action, see ECRBuildAndPublish build action reference.

ts
import * as ecr from 'aws-cdk-lib/aws-ecr';

declare const pipeline: codepipeline.Pipeline;
declare const repository: ecr.IRepository;

const sourceOutput = new codepipeline.Artifact();
// your source repository
const sourceAction = new codepipeline_actions.CodeStarConnectionsSourceAction({
  actionName: 'CodeStarConnectionsSourceAction',
  output: sourceOutput,
  connectionArn: 'your-connection-arn',
  owner: 'your-owner',
  repo: 'your-repo',
});

const buildAction = new codepipeline_actions.EcrBuildAndPublishAction({
  actionName: 'EcrBuildAndPublishAction',
  repositoryName: repository.repositoryName,
  registryType: codepipeline_actions.RegistryType.PRIVATE,
  dockerfileDirectoryPath: './my-dir', // The path indicates ./my-dir/Dockerfile in the source repository
  imageTags: ['my-tag-1', 'my-tag-2'],
  input: sourceOutput,
});

pipeline.addStage({
  stageName: 'Source',
  actions: [sourceAction],
});
pipeline.addStage({
  stageName: 'Build',
  actions: [buildAction],
});
python
import aws_cdk.aws_ecr as ecr

# pipeline: codepipeline.Pipeline
# repository: ecr.IRepository


source_output = codepipeline.Artifact()
# your source repository
source_action = codepipeline_actions.CodeStarConnectionsSourceAction(
    action_name="CodeStarConnectionsSourceAction",
    output=source_output,
    connection_arn="your-connection-arn",
    owner="your-owner",
    repo="your-repo"
)

build_action = codepipeline_actions.EcrBuildAndPublishAction(
    action_name="EcrBuildAndPublishAction",
    repository_name=repository.repository_name,
    registry_type=codepipeline_actions.RegistryType.PRIVATE,
    dockerfile_directory_path="./my-dir",  # The path indicates ./my-dir/Dockerfile in the source repository
    image_tags=["my-tag-1", "my-tag-2"],
    input=source_output
)

pipeline.add_stage(
    stage_name="Source",
    actions=[source_action]
)
pipeline.add_stage(
    stage_name="Build",
    actions=[build_action]
)
java
import software.amazon.awscdk.services.ecr.*;

Pipeline pipeline;
IRepository repository;


Artifact sourceOutput = new Artifact();
// your source repository
CodeStarConnectionsSourceAction sourceAction = CodeStarConnectionsSourceAction.Builder.create()
        .actionName("CodeStarConnectionsSourceAction")
        .output(sourceOutput)
        .connectionArn("your-connection-arn")
        .owner("your-owner")
        .repo("your-repo")
        .build();

EcrBuildAndPublishAction buildAction = EcrBuildAndPublishAction.Builder.create()
        .actionName("EcrBuildAndPublishAction")
        .repositoryName(repository.getRepositoryName())
        .registryType(RegistryType.PRIVATE)
        .dockerfileDirectoryPath("./my-dir") // The path indicates ./my-dir/Dockerfile in the source repository
        .imageTags(List.of("my-tag-1", "my-tag-2"))
        .input(sourceOutput)
        .build();

pipeline.addStage(StageOptions.builder()
        .stageName("Source")
        .actions(List.of(sourceAction))
        .build());
pipeline.addStage(StageOptions.builder()
        .stageName("Build")
        .actions(List.of(buildAction))
        .build());
csharp
using Amazon.CDK.AWS.ECR;

Pipeline pipeline;
IRepository repository;


var sourceOutput = new Artifact();
// your source repository
var sourceAction = new CodeStarConnectionsSourceAction(new CodeStarConnectionsSourceActionProps {
    ActionName = "CodeStarConnectionsSourceAction",
    Output = sourceOutput,
    ConnectionArn = "your-connection-arn",
    Owner = "your-owner",
    Repo = "your-repo"
});

var buildAction = new EcrBuildAndPublishAction(new EcrBuildAndPublishActionProps {
    ActionName = "EcrBuildAndPublishAction",
    RepositoryName = repository.RepositoryName,
    RegistryType = RegistryType.PRIVATE,
    DockerfileDirectoryPath = "./my-dir",  // The path indicates ./my-dir/Dockerfile in the source repository
    ImageTags = new [] { "my-tag-1", "my-tag-2" },
    Input = sourceOutput
});

pipeline.AddStage(new StageOptions {
    StageName = "Source",
    Actions = new [] { sourceAction }
});
pipeline.AddStage(new StageOptions {
    StageName = "Build",
    Actions = new [] { buildAction }
});
go
import ecr "github.com/aws/aws-cdk-go/awscdk"

var pipeline Pipeline
var repository IRepository


sourceOutput := codepipeline.NewArtifact()
// your source repository
sourceAction := codepipeline_actions.NewCodeStarConnectionsSourceAction(&CodeStarConnectionsSourceActionProps{
	ActionName: jsii.String("CodeStarConnectionsSourceAction"),
	Output: sourceOutput,
	ConnectionArn: jsii.String("your-connection-arn"),
	Owner: jsii.String("your-owner"),
	Repo: jsii.String("your-repo"),
})

buildAction := codepipeline_actions.NewEcrBuildAndPublishAction(&EcrBuildAndPublishActionProps{
	ActionName: jsii.String("EcrBuildAndPublishAction"),
	RepositoryName: repository.RepositoryName,
	RegistryType: codepipeline_actions.RegistryType_PRIVATE,
	DockerfileDirectoryPath: jsii.String("./my-dir"),
	 // The path indicates ./my-dir/Dockerfile in the source repository
	ImageTags: []*string{
		jsii.String("my-tag-1"),
		jsii.String("my-tag-2"),
	},
	Input: sourceOutput,
})

pipeline.AddStage(&StageOptions{
	StageName: jsii.String("Source"),
	Actions: []IAction{
		sourceAction,
	},
})
pipeline.AddStage(&StageOptions{
	StageName: jsii.String("Build"),
	Actions: []IAction{
		buildAction,
	},
})

Deploy ​

AWS CloudFormation ​

This module contains Actions that allows you to deploy to CloudFormation from AWS CodePipeline.

For example, the following code fragment defines a pipeline that automatically deploys a CloudFormation template directly from a CodeCommit repository, with a manual approval step in between to confirm the changes:

ts
// Source stage: read from repository
const repo = new codecommit.Repository(stack, 'TemplateRepo', {
  repositoryName: 'template-repo',
});
const sourceOutput = new codepipeline.Artifact('SourceArtifact');
const source = new cpactions.CodeCommitSourceAction({
  actionName: 'Source',
  repository: repo,
  output: sourceOutput,
  trigger: cpactions.CodeCommitTrigger.POLL,
});
const sourceStage = {
  stageName: 'Source',
  actions: [source],
};

// Deployment stage: create and deploy changeset with manual approval
const stackName = 'OurStack';
const changeSetName = 'StagedChangeSet';

const prodStage = {
  stageName: 'Deploy',
  actions: [
    new cpactions.CloudFormationCreateReplaceChangeSetAction({
      actionName: 'PrepareChanges',
      stackName,
      changeSetName,
      adminPermissions: true,
      templatePath: sourceOutput.atPath('template.yaml'),
      runOrder: 1,
    }),
    new cpactions.ManualApprovalAction({
      actionName: 'ApproveChanges',
      runOrder: 2,
    }),
    new cpactions.CloudFormationExecuteChangeSetAction({
      actionName: 'ExecuteChanges',
      stackName,
      changeSetName,
      runOrder: 3,
    }),
  ],
};

new codepipeline.Pipeline(stack, 'Pipeline', {
  crossAccountKeys: true,
  stages: [
    sourceStage,
    prodStage,
  ],
});
python
# Source stage: read from repository
repo = codecommit.Repository(stack, "TemplateRepo",
    repository_name="template-repo"
)
source_output = codepipeline.Artifact("SourceArtifact")
source = cpactions.CodeCommitSourceAction(
    action_name="Source",
    repository=repo,
    output=source_output,
    trigger=cpactions.CodeCommitTrigger.POLL
)
source_stage = {
    "stage_name": "Source",
    "actions": [source]
}

# Deployment stage: create and deploy changeset with manual approval
stack_name = "OurStack"
change_set_name = "StagedChangeSet"

prod_stage = {
    "stage_name": "Deploy",
    "actions": [
        cpactions.CloudFormationCreateReplaceChangeSetAction(
            action_name="PrepareChanges",
            stack_name=stack_name,
            change_set_name=change_set_name,
            admin_permissions=True,
            template_path=source_output.at_path("template.yaml"),
            run_order=1
        ),
        cpactions.ManualApprovalAction(
            action_name="ApproveChanges",
            run_order=2
        ),
        cpactions.CloudFormationExecuteChangeSetAction(
            action_name="ExecuteChanges",
            stack_name=stack_name,
            change_set_name=change_set_name,
            run_order=3
        )
    ]
}

codepipeline.Pipeline(stack, "Pipeline",
    cross_account_keys=True,
    stages=[source_stage, prod_stage
    ]
)
java
// Source stage: read from repository
Repository repo = Repository.Builder.create(stack, "TemplateRepo")
        .repositoryName("template-repo")
        .build();
Artifact sourceOutput = new Artifact("SourceArtifact");
CodeCommitSourceAction source = CodeCommitSourceAction.Builder.create()
        .actionName("Source")
        .repository(repo)
        .output(sourceOutput)
        .trigger(CodeCommitTrigger.POLL)
        .build();
Map<String, Object> sourceStage = Map.of(
        "stageName", "Source",
        "actions", List.of(source));

// Deployment stage: create and deploy changeset with manual approval
String stackName = "OurStack";
String changeSetName = "StagedChangeSet";

Map<String, Object> prodStage = Map.of(
        "stageName", "Deploy",
        "actions", List.of(
            CloudFormationCreateReplaceChangeSetAction.Builder.create()
                    .actionName("PrepareChanges")
                    .stackName(stackName)
                    .changeSetName(changeSetName)
                    .adminPermissions(true)
                    .templatePath(sourceOutput.atPath("template.yaml"))
                    .runOrder(1)
                    .build(),
            ManualApprovalAction.Builder.create()
                    .actionName("ApproveChanges")
                    .runOrder(2)
                    .build(),
            CloudFormationExecuteChangeSetAction.Builder.create()
                    .actionName("ExecuteChanges")
                    .stackName(stackName)
                    .changeSetName(changeSetName)
                    .runOrder(3)
                    .build()));

Pipeline.Builder.create(stack, "Pipeline")
        .crossAccountKeys(true)
        .stages(List.of(sourceStage, prodStage))
        .build();
csharp
// Source stage: read from repository
var repo = new Repository(stack, "TemplateRepo", new RepositoryProps {
    RepositoryName = "template-repo"
});
var sourceOutput = new Artifact("SourceArtifact");
var source = new CodeCommitSourceAction(new CodeCommitSourceActionProps {
    ActionName = "Source",
    Repository = repo,
    Output = sourceOutput,
    Trigger = CodeCommitTrigger.POLL
});
IDictionary<string, object> sourceStage = new Dictionary<string, object> {
    { "stageName", "Source" },
    { "actions", new [] { source } }
};

// Deployment stage: create and deploy changeset with manual approval
var stackName = "OurStack";
var changeSetName = "StagedChangeSet";

IDictionary<string, object> prodStage = new Dictionary<string, object> {
    { "stageName", "Deploy" },
    { "actions", new [] {
        new CloudFormationCreateReplaceChangeSetAction(new CloudFormationCreateReplaceChangeSetActionProps {
            ActionName = "PrepareChanges",
            StackName = stackName,
            ChangeSetName = changeSetName,
            AdminPermissions = true,
            TemplatePath = sourceOutput.AtPath("template.yaml"),
            RunOrder = 1
        }),
        new ManualApprovalAction(new ManualApprovalActionProps {
            ActionName = "ApproveChanges",
            RunOrder = 2
        }),
        new CloudFormationExecuteChangeSetAction(new CloudFormationExecuteChangeSetActionProps {
            ActionName = "ExecuteChanges",
            StackName = stackName,
            ChangeSetName = changeSetName,
            RunOrder = 3
        }) } }
};

new Pipeline(stack, "Pipeline", new PipelineProps {
    CrossAccountKeys = true,
    Stages = new [] { sourceStage, prodStage }
});
go
// Source stage: read from repository
repo := codecommit.NewRepository(stack, jsii.String("TemplateRepo"), &RepositoryProps{
	RepositoryName: jsii.String("template-repo"),
})
sourceOutput := codepipeline.NewArtifact(jsii.String("SourceArtifact"))
source := cpactions.NewCodeCommitSourceAction(&CodeCommitSourceActionProps{
	ActionName: jsii.String("Source"),
	Repository: repo,
	Output: sourceOutput,
	Trigger: cpactions.CodeCommitTrigger_POLL,
})
sourceStage := map[string]interface{}{
	"stageName": jsii.String("Source"),
	"actions": []CodeCommitSourceAction{
		source,
	},
}

// Deployment stage: create and deploy changeset with manual approval
stackName := "OurStack"
changeSetName := "StagedChangeSet"

prodStage := map[string]interface{}{
	"stageName": jsii.String("Deploy"),
	"actions": []interface{}{
		cpactions.NewCloudFormationCreateReplaceChangeSetAction(&CloudFormationCreateReplaceChangeSetActionProps{
			"actionName": jsii.String("PrepareChanges"),
			"stackName": jsii.String(stackName),
			"changeSetName": jsii.String(changeSetName),
			"adminPermissions": jsii.Boolean(true),
			"templatePath": sourceOutput.atPath(jsii.String("template.yaml")),
			"runOrder": jsii.Number(1),
		}),
		cpactions.NewManualApprovalAction(&ManualApprovalActionProps{
			"actionName": jsii.String("ApproveChanges"),
			"runOrder": jsii.Number(2),
		}),
		cpactions.NewCloudFormationExecuteChangeSetAction(&CloudFormationExecuteChangeSetActionProps{
			"actionName": jsii.String("ExecuteChanges"),
			"stackName": jsii.String(stackName),
			"changeSetName": jsii.String(changeSetName),
			"runOrder": jsii.Number(3),
		}),
	},
}

codepipeline.NewPipeline(stack, jsii.String("Pipeline"), &PipelineProps{
	CrossAccountKeys: jsii.Boolean(true),
	Stages: []StageProps{
		sourceStage,
		prodStage,
	},
})

See the AWS documentation for more details about using CloudFormation in CodePipeline.

Actions for updating individual CloudFormation Stacks ​

This package contains the following CloudFormation actions:

  • CloudFormationCreateUpdateStackAction - Deploy a CloudFormation template directly from the pipeline. The indicated stack is created, or updated if it already exists. If the stack is in a failure state, deployment will fail (unless replaceOnFailure is set to true, in which case it will be destroyed and recreated).
  • CloudFormationDeleteStackAction - Delete the stack with the given name.
  • CloudFormationCreateReplaceChangeSetAction - Prepare a change set to be applied later. You will typically use change sets if you want to manually verify the changes that are being staged, or if you want to separate the people (or system) preparing the changes from the people (or system) applying the changes.
  • CloudFormationExecuteChangeSetAction - Execute a change set prepared previously.

Actions for deploying CloudFormation StackSets to multiple accounts ​

You can use CloudFormation StackSets to deploy the same CloudFormation template to multiple accounts in a managed way. If you use AWS Organizations, StackSets can be deployed to all accounts in a particular Organizational Unit (OU), and even automatically to new accounts as soon as they are added to a particular OU. For more information, see the Working with StackSets section of the CloudFormation developer guide.

The actions available for updating StackSets are:

  • CloudFormationDeployStackSetAction - Create or update a CloudFormation StackSet directly from the pipeline, optionally immediately create and update Stack Instances as well.
  • CloudFormationDeployStackInstancesAction - Update outdated Stack Instances using the current version of the StackSet.

Here's an example of using both of these actions:

ts
declare const pipeline: codepipeline.Pipeline;
declare const sourceOutput: codepipeline.Artifact;

pipeline.addStage({
  stageName: 'DeployStackSets',
  actions: [
    // First, update the StackSet itself with the newest template
    new codepipeline_actions.CloudFormationDeployStackSetAction({
      actionName: 'UpdateStackSet',
      runOrder: 1,
      stackSetName: 'MyStackSet',
      template: codepipeline_actions.StackSetTemplate.fromArtifactPath(sourceOutput.atPath('template.yaml')),

      // Change this to 'StackSetDeploymentModel.organizations()' if you want to deploy to OUs
      deploymentModel: codepipeline_actions.StackSetDeploymentModel.selfManaged(),
      // This deploys to a set of accounts
      stackInstances: codepipeline_actions.StackInstances.inAccounts(['111111111111'], ['us-east-1', 'eu-west-1']),
    }),

    // Afterwards, update/create additional instances in other accounts
    new codepipeline_actions.CloudFormationDeployStackInstancesAction({
      actionName: 'AddMoreInstances',
      runOrder: 2,
      stackSetName: 'MyStackSet',
      stackInstances: codepipeline_actions.StackInstances.inAccounts(
        ['222222222222', '333333333333'],
        ['us-east-1', 'eu-west-1']
      ),
    }),
  ],
});
python
# pipeline: codepipeline.Pipeline
# source_output: codepipeline.Artifact


pipeline.add_stage(
    stage_name="DeployStackSets",
    actions=[
        # First, update the StackSet itself with the newest template
        codepipeline_actions.CloudFormationDeployStackSetAction(
            action_name="UpdateStackSet",
            run_order=1,
            stack_set_name="MyStackSet",
            template=codepipeline_actions.StackSetTemplate.from_artifact_path(source_output.at_path("template.yaml")),

            # Change this to 'StackSetDeploymentModel.organizations()' if you want to deploy to OUs
            deployment_model=codepipeline_actions.StackSetDeploymentModel.self_managed(),
            # This deploys to a set of accounts
            stack_instances=codepipeline_actions.StackInstances.in_accounts(["111111111111"], ["us-east-1", "eu-west-1"])
        ),

        # Afterwards, update/create additional instances in other accounts
        codepipeline_actions.CloudFormationDeployStackInstancesAction(
            action_name="AddMoreInstances",
            run_order=2,
            stack_set_name="MyStackSet",
            stack_instances=codepipeline_actions.StackInstances.in_accounts(["222222222222", "333333333333"], ["us-east-1", "eu-west-1"])
        )
    ]
)
java
Pipeline pipeline;
Artifact sourceOutput;


pipeline.addStage(StageOptions.builder()
        .stageName("DeployStackSets")
        .actions(List.of(
            // First, update the StackSet itself with the newest template
            CloudFormationDeployStackSetAction.Builder.create()
                    .actionName("UpdateStackSet")
                    .runOrder(1)
                    .stackSetName("MyStackSet")
                    .template(StackSetTemplate.fromArtifactPath(sourceOutput.atPath("template.yaml")))

                    // Change this to 'StackSetDeploymentModel.organizations()' if you want to deploy to OUs
                    .deploymentModel(StackSetDeploymentModel.selfManaged())
                    // This deploys to a set of accounts
                    .stackInstances(StackInstances.inAccounts(List.of("111111111111"), List.of("us-east-1", "eu-west-1")))
                    .build(),

            // Afterwards, update/create additional instances in other accounts
            CloudFormationDeployStackInstancesAction.Builder.create()
                    .actionName("AddMoreInstances")
                    .runOrder(2)
                    .stackSetName("MyStackSet")
                    .stackInstances(StackInstances.inAccounts(List.of("222222222222", "333333333333"), List.of("us-east-1", "eu-west-1")))
                    .build()))
        .build());
csharp
Pipeline pipeline;
Artifact sourceOutput;


pipeline.AddStage(new StageOptions {
    StageName = "DeployStackSets",
    Actions = new [] {
        // First, update the StackSet itself with the newest template
        new CloudFormationDeployStackSetAction(new CloudFormationDeployStackSetActionProps {
            ActionName = "UpdateStackSet",
            RunOrder = 1,
            StackSetName = "MyStackSet",
            Template = StackSetTemplate.FromArtifactPath(sourceOutput.AtPath("template.yaml")),

            // Change this to 'StackSetDeploymentModel.organizations()' if you want to deploy to OUs
            DeploymentModel = StackSetDeploymentModel.SelfManaged(),
            // This deploys to a set of accounts
            StackInstances = StackInstances.InAccounts(new [] { "111111111111" }, new [] { "us-east-1", "eu-west-1" })
        }),

        // Afterwards, update/create additional instances in other accounts
        new CloudFormationDeployStackInstancesAction(new CloudFormationDeployStackInstancesActionProps {
            ActionName = "AddMoreInstances",
            RunOrder = 2,
            StackSetName = "MyStackSet",
            StackInstances = StackInstances.InAccounts(new [] { "222222222222", "333333333333" }, new [] { "us-east-1", "eu-west-1" })
        }) }
});
go
var pipeline Pipeline
var sourceOutput Artifact


pipeline.AddStage(&StageOptions{
	StageName: jsii.String("DeployStackSets"),
	Actions: []IAction{
		// First, update the StackSet itself with the newest template
		codepipeline_actions.NewCloudFormationDeployStackSetAction(&CloudFormationDeployStackSetActionProps{
			ActionName: jsii.String("UpdateStackSet"),
			RunOrder: jsii.Number(1),
			StackSetName: jsii.String("MyStackSet"),
			Template: codepipeline_actions.StackSetTemplate_FromArtifactPath(sourceOutput.AtPath(jsii.String("template.yaml"))),

			// Change this to 'StackSetDeploymentModel.organizations()' if you want to deploy to OUs
			DeploymentModel: codepipeline_actions.StackSetDeploymentModel_SelfManaged(),
			// This deploys to a set of accounts
			StackInstances: codepipeline_actions.StackInstances_InAccounts([]*string{
				jsii.String("111111111111"),
			}, []*string{
				jsii.String("us-east-1"),
				jsii.String("eu-west-1"),
			}),
		}),

		// Afterwards, update/create additional instances in other accounts
		codepipeline_actions.NewCloudFormationDeployStackInstancesAction(&CloudFormationDeployStackInstancesActionProps{
			ActionName: jsii.String("AddMoreInstances"),
			RunOrder: jsii.Number(2),
			StackSetName: jsii.String("MyStackSet"),
			StackInstances: codepipeline_actions.StackInstances_*InAccounts([]*string{
				jsii.String("222222222222"),
				jsii.String("333333333333"),
			}, []*string{
				jsii.String("us-east-1"),
				jsii.String("eu-west-1"),
			}),
		}),
	},
})

Lambda deployed through CodePipeline ​

If you want to deploy your Lambda through CodePipeline, and you don't use assets (for example, because your CDK code and Lambda code are separate), you can use a special Lambda Code class, CfnParametersCode. Note that your Lambda must be in a different Stack than your Pipeline. The Lambda itself will be deployed, alongside the entire Stack it belongs to, using a CloudFormation CodePipeline Action. Example:

ts
const lambdaStack = new cdk.Stack(app, 'LambdaStack');
const lambdaCode = lambda.Code.fromCfnParameters();
new lambda.Function(lambdaStack, 'Lambda', {
  code: lambdaCode,
  handler: 'index.handler',
  runtime: lambda.Runtime.NODEJS_LATEST,
});
// other resources that your Lambda needs, added to the lambdaStack...

const pipelineStack = new cdk.Stack(app, 'PipelineStack');
const pipeline = new codepipeline.Pipeline(pipelineStack, 'Pipeline', {
  crossAccountKeys: true,
});

// add the source code repository containing this code to your Pipeline,
// and the source code of the Lambda Function, if they're separate
const cdkSourceOutput = new codepipeline.Artifact();
const cdkSourceAction = new codepipeline_actions.CodeCommitSourceAction({
  repository: new codecommit.Repository(pipelineStack, 'CdkCodeRepo', {
    repositoryName: 'CdkCodeRepo',
  }),
  actionName: 'CdkCode_Source',
  output: cdkSourceOutput,
});
const lambdaSourceOutput = new codepipeline.Artifact();
const lambdaSourceAction = new codepipeline_actions.CodeCommitSourceAction({
  repository: new codecommit.Repository(pipelineStack, 'LambdaCodeRepo', {
    repositoryName: 'LambdaCodeRepo',
  }),
  actionName: 'LambdaCode_Source',
  output: lambdaSourceOutput,
});
pipeline.addStage({
  stageName: 'Source',
  actions: [cdkSourceAction, lambdaSourceAction],
});

// synthesize the Lambda CDK template, using CodeBuild
// the below values are just examples, assuming your CDK code is in TypeScript/JavaScript -
// adjust the build environment and/or commands accordingly
const cdkBuildProject = new codebuild.Project(pipelineStack, 'CdkBuildProject', {
  environment: {
    buildImage: codebuild.LinuxBuildImage.STANDARD_7_0,
  },
  buildSpec: codebuild.BuildSpec.fromObject({
    version: '0.2',
    phases: {
      install: {
        commands: 'npm install',
      },
      build: {
        commands: [
          'npm run build',
          'npm run cdk synth LambdaStack -- -o .',
        ],
      },
    },
    artifacts: {
      files: 'LambdaStack.template.yaml',
    },
  }),
});
const cdkBuildOutput = new codepipeline.Artifact();
const cdkBuildAction = new codepipeline_actions.CodeBuildAction({
  actionName: 'CDK_Build',
  project: cdkBuildProject,
  input: cdkSourceOutput,
  outputs: [cdkBuildOutput],
});

// build your Lambda code, using CodeBuild
// again, this example assumes your Lambda is written in TypeScript/JavaScript -
// make sure to adjust the build environment and/or commands if they don't match your specific situation
const lambdaBuildProject = new codebuild.Project(pipelineStack, 'LambdaBuildProject', {
  environment: {
    buildImage: codebuild.LinuxBuildImage.STANDARD_7_0,
  },
  buildSpec: codebuild.BuildSpec.fromObject({
    version: '0.2',
    phases: {
      install: {
        commands: 'npm install',
      },
      build: {
        commands: 'npm run build',
      },
    },
    artifacts: {
      files: [
        'index.js',
        'node_modules/**/*',
      ],
    },
  }),
});
const lambdaBuildOutput = new codepipeline.Artifact();
const lambdaBuildAction = new codepipeline_actions.CodeBuildAction({
  actionName: 'Lambda_Build',
  project: lambdaBuildProject,
  input: lambdaSourceOutput,
  outputs: [lambdaBuildOutput],
});

pipeline.addStage({
  stageName: 'Build',
  actions: [cdkBuildAction, lambdaBuildAction],
});

// finally, deploy your Lambda Stack
pipeline.addStage({
  stageName: 'Deploy',
  actions: [
    new codepipeline_actions.CloudFormationCreateUpdateStackAction({
      actionName: 'Lambda_CFN_Deploy',
      templatePath: cdkBuildOutput.atPath('LambdaStack.template.yaml'),
      stackName: 'LambdaStackDeployedName',
      adminPermissions: true,
      parameterOverrides: lambdaCode.assign(lambdaBuildOutput.s3Location),
      extraInputs: [
        lambdaBuildOutput,
      ],
    }),
  ],
});
python
lambda_stack = cdk.Stack(app, "LambdaStack")
lambda_code = lambda_.Code.from_cfn_parameters()
lambda_.Function(lambda_stack, "Lambda",
    code=lambda_code,
    handler="index.handler",
    runtime=lambda_.Runtime.NODEJS_LATEST
)
# other resources that your Lambda needs, added to the lambdaStack...

pipeline_stack = cdk.Stack(app, "PipelineStack")
pipeline = codepipeline.Pipeline(pipeline_stack, "Pipeline",
    cross_account_keys=True
)

# add the source code repository containing this code to your Pipeline,
# and the source code of the Lambda Function, if they're separate
cdk_source_output = codepipeline.Artifact()
cdk_source_action = codepipeline_actions.CodeCommitSourceAction(
    repository=codecommit.Repository(pipeline_stack, "CdkCodeRepo",
        repository_name="CdkCodeRepo"
    ),
    action_name="CdkCode_Source",
    output=cdk_source_output
)
lambda_source_output = codepipeline.Artifact()
lambda_source_action = codepipeline_actions.CodeCommitSourceAction(
    repository=codecommit.Repository(pipeline_stack, "LambdaCodeRepo",
        repository_name="LambdaCodeRepo"
    ),
    action_name="LambdaCode_Source",
    output=lambda_source_output
)
pipeline.add_stage(
    stage_name="Source",
    actions=[cdk_source_action, lambda_source_action]
)

# synthesize the Lambda CDK template, using CodeBuild
# the below values are just examples, assuming your CDK code is in TypeScript/JavaScript -
# adjust the build environment and/or commands accordingly
cdk_build_project = codebuild.Project(pipeline_stack, "CdkBuildProject",
    environment=codebuild.BuildEnvironment(
        build_image=codebuild.LinuxBuildImage.STANDARD_7_0
    ),
    build_spec=codebuild.BuildSpec.from_object({
        "version": "0.2",
        "phases": {
            "install": {
                "commands": "npm install"
            },
            "build": {
                "commands": ["npm run build", "npm run cdk synth LambdaStack -- -o ."
                ]
            }
        },
        "artifacts": {
            "files": "LambdaStack.template.yaml"
        }
    })
)
cdk_build_output = codepipeline.Artifact()
cdk_build_action = codepipeline_actions.CodeBuildAction(
    action_name="CDK_Build",
    project=cdk_build_project,
    input=cdk_source_output,
    outputs=[cdk_build_output]
)

# build your Lambda code, using CodeBuild
# again, this example assumes your Lambda is written in TypeScript/JavaScript -
# make sure to adjust the build environment and/or commands if they don't match your specific situation
lambda_build_project = codebuild.Project(pipeline_stack, "LambdaBuildProject",
    environment=codebuild.BuildEnvironment(
        build_image=codebuild.LinuxBuildImage.STANDARD_7_0
    ),
    build_spec=codebuild.BuildSpec.from_object({
        "version": "0.2",
        "phases": {
            "install": {
                "commands": "npm install"
            },
            "build": {
                "commands": "npm run build"
            }
        },
        "artifacts": {
            "files": ["index.js", "node_modules/**/*"
            ]
        }
    })
)
lambda_build_output = codepipeline.Artifact()
lambda_build_action = codepipeline_actions.CodeBuildAction(
    action_name="Lambda_Build",
    project=lambda_build_project,
    input=lambda_source_output,
    outputs=[lambda_build_output]
)

pipeline.add_stage(
    stage_name="Build",
    actions=[cdk_build_action, lambda_build_action]
)

# finally, deploy your Lambda Stack
pipeline.add_stage(
    stage_name="Deploy",
    actions=[
        codepipeline_actions.CloudFormationCreateUpdateStackAction(
            action_name="Lambda_CFN_Deploy",
            template_path=cdk_build_output.at_path("LambdaStack.template.yaml"),
            stack_name="LambdaStackDeployedName",
            admin_permissions=True,
            parameter_overrides=lambda_code.assign(lambda_build_output.s3_location),
            extra_inputs=[lambda_build_output
            ]
        )
    ]
)
java
Stack lambdaStack = new Stack(app, "LambdaStack");
CfnParametersCode lambdaCode = Code.fromCfnParameters();
Function.Builder.create(lambdaStack, "Lambda")
        .code(lambdaCode)
        .handler("index.handler")
        .runtime(Runtime.NODEJS_LATEST)
        .build();
// other resources that your Lambda needs, added to the lambdaStack...

Stack pipelineStack = new Stack(app, "PipelineStack");
Pipeline pipeline = Pipeline.Builder.create(pipelineStack, "Pipeline")
        .crossAccountKeys(true)
        .build();

// add the source code repository containing this code to your Pipeline,
// and the source code of the Lambda Function, if they're separate
Artifact cdkSourceOutput = new Artifact();
CodeCommitSourceAction cdkSourceAction = CodeCommitSourceAction.Builder.create()
        .repository(Repository.Builder.create(pipelineStack, "CdkCodeRepo")
                .repositoryName("CdkCodeRepo")
                .build())
        .actionName("CdkCode_Source")
        .output(cdkSourceOutput)
        .build();
Artifact lambdaSourceOutput = new Artifact();
CodeCommitSourceAction lambdaSourceAction = CodeCommitSourceAction.Builder.create()
        .repository(Repository.Builder.create(pipelineStack, "LambdaCodeRepo")
                .repositoryName("LambdaCodeRepo")
                .build())
        .actionName("LambdaCode_Source")
        .output(lambdaSourceOutput)
        .build();
pipeline.addStage(StageOptions.builder()
        .stageName("Source")
        .actions(List.of(cdkSourceAction, lambdaSourceAction))
        .build());

// synthesize the Lambda CDK template, using CodeBuild
// the below values are just examples, assuming your CDK code is in TypeScript/JavaScript -
// adjust the build environment and/or commands accordingly
Project cdkBuildProject = Project.Builder.create(pipelineStack, "CdkBuildProject")
        .environment(BuildEnvironment.builder()
                .buildImage(LinuxBuildImage.STANDARD_7_0)
                .build())
        .buildSpec(BuildSpec.fromObject(Map.of(
                "version", "0.2",
                "phases", Map.of(
                        "install", Map.of(
                                "commands", "npm install"),
                        "build", Map.of(
                                "commands", List.of("npm run build", "npm run cdk synth LambdaStack -- -o ."))),
                "artifacts", Map.of(
                        "files", "LambdaStack.template.yaml"))))
        .build();
Artifact cdkBuildOutput = new Artifact();
CodeBuildAction cdkBuildAction = CodeBuildAction.Builder.create()
        .actionName("CDK_Build")
        .project(cdkBuildProject)
        .input(cdkSourceOutput)
        .outputs(List.of(cdkBuildOutput))
        .build();

// build your Lambda code, using CodeBuild
// again, this example assumes your Lambda is written in TypeScript/JavaScript -
// make sure to adjust the build environment and/or commands if they don't match your specific situation
Project lambdaBuildProject = Project.Builder.create(pipelineStack, "LambdaBuildProject")
        .environment(BuildEnvironment.builder()
                .buildImage(LinuxBuildImage.STANDARD_7_0)
                .build())
        .buildSpec(BuildSpec.fromObject(Map.of(
                "version", "0.2",
                "phases", Map.of(
                        "install", Map.of(
                                "commands", "npm install"),
                        "build", Map.of(
                                "commands", "npm run build")),
                "artifacts", Map.of(
                        "files", List.of("index.js", "node_modules/**/*")))))
        .build();
Artifact lambdaBuildOutput = new Artifact();
CodeBuildAction lambdaBuildAction = CodeBuildAction.Builder.create()
        .actionName("Lambda_Build")
        .project(lambdaBuildProject)
        .input(lambdaSourceOutput)
        .outputs(List.of(lambdaBuildOutput))
        .build();

pipeline.addStage(StageOptions.builder()
        .stageName("Build")
        .actions(List.of(cdkBuildAction, lambdaBuildAction))
        .build());

// finally, deploy your Lambda Stack
pipeline.addStage(StageOptions.builder()
        .stageName("Deploy")
        .actions(List.of(
            CloudFormationCreateUpdateStackAction.Builder.create()
                    .actionName("Lambda_CFN_Deploy")
                    .templatePath(cdkBuildOutput.atPath("LambdaStack.template.yaml"))
                    .stackName("LambdaStackDeployedName")
                    .adminPermissions(true)
                    .parameterOverrides(lambdaCode.assign(lambdaBuildOutput.getS3Location()))
                    .extraInputs(List.of(lambdaBuildOutput))
                    .build()))
        .build());
csharp
var lambdaStack = new Stack(app, "LambdaStack");
var lambdaCode = Code.FromCfnParameters();
new Function(lambdaStack, "Lambda", new FunctionProps {
    Code = lambdaCode,
    Handler = "index.handler",
    Runtime = Runtime.NODEJS_LATEST
});
// other resources that your Lambda needs, added to the lambdaStack...

var pipelineStack = new Stack(app, "PipelineStack");
var pipeline = new Pipeline(pipelineStack, "Pipeline", new PipelineProps {
    CrossAccountKeys = true
});

// add the source code repository containing this code to your Pipeline,
// and the source code of the Lambda Function, if they're separate
var cdkSourceOutput = new Artifact();
var cdkSourceAction = new CodeCommitSourceAction(new CodeCommitSourceActionProps {
    Repository = new Repository(pipelineStack, "CdkCodeRepo", new RepositoryProps {
        RepositoryName = "CdkCodeRepo"
    }),
    ActionName = "CdkCode_Source",
    Output = cdkSourceOutput
});
var lambdaSourceOutput = new Artifact();
var lambdaSourceAction = new CodeCommitSourceAction(new CodeCommitSourceActionProps {
    Repository = new Repository(pipelineStack, "LambdaCodeRepo", new RepositoryProps {
        RepositoryName = "LambdaCodeRepo"
    }),
    ActionName = "LambdaCode_Source",
    Output = lambdaSourceOutput
});
pipeline.AddStage(new StageOptions {
    StageName = "Source",
    Actions = new [] { cdkSourceAction, lambdaSourceAction }
});

// synthesize the Lambda CDK template, using CodeBuild
// the below values are just examples, assuming your CDK code is in TypeScript/JavaScript -
// adjust the build environment and/or commands accordingly
var cdkBuildProject = new Project(pipelineStack, "CdkBuildProject", new ProjectProps {
    Environment = new BuildEnvironment {
        BuildImage = LinuxBuildImage.STANDARD_7_0
    },
    BuildSpec = BuildSpec.FromObject(new Dictionary<string, object> {
        { "version", "0.2" },
        { "phases", new Dictionary<string, IDictionary<string, string>> {
            { "install", new Struct {
                Commands = "npm install"
            } },
            { "build", new Struct {
                Commands = new [] { "npm run build", "npm run cdk synth LambdaStack -- -o ." }
            } }
        } },
        { "artifacts", new Dictionary<string, string> {
            { "files", "LambdaStack.template.yaml" }
        } }
    })
});
var cdkBuildOutput = new Artifact();
var cdkBuildAction = new CodeBuildAction(new CodeBuildActionProps {
    ActionName = "CDK_Build",
    Project = cdkBuildProject,
    Input = cdkSourceOutput,
    Outputs = new [] { cdkBuildOutput }
});

// build your Lambda code, using CodeBuild
// again, this example assumes your Lambda is written in TypeScript/JavaScript -
// make sure to adjust the build environment and/or commands if they don't match your specific situation
var lambdaBuildProject = new Project(pipelineStack, "LambdaBuildProject", new ProjectProps {
    Environment = new BuildEnvironment {
        BuildImage = LinuxBuildImage.STANDARD_7_0
    },
    BuildSpec = BuildSpec.FromObject(new Dictionary<string, object> {
        { "version", "0.2" },
        { "phases", new Dictionary<string, IDictionary<string, string>> {
            { "install", new Struct {
                Commands = "npm install"
            } },
            { "build", new Struct {
                Commands = "npm run build"
            } }
        } },
        { "artifacts", new Dictionary<string, string[]> {
            { "files", new [] { "index.js", "node_modules/**/*" } }
        } }
    })
});
var lambdaBuildOutput = new Artifact();
var lambdaBuildAction = new CodeBuildAction(new CodeBuildActionProps {
    ActionName = "Lambda_Build",
    Project = lambdaBuildProject,
    Input = lambdaSourceOutput,
    Outputs = new [] { lambdaBuildOutput }
});

pipeline.AddStage(new StageOptions {
    StageName = "Build",
    Actions = new [] { cdkBuildAction, lambdaBuildAction }
});

// finally, deploy your Lambda Stack
pipeline.AddStage(new StageOptions {
    StageName = "Deploy",
    Actions = new [] {
        new CloudFormationCreateUpdateStackAction(new CloudFormationCreateUpdateStackActionProps {
            ActionName = "Lambda_CFN_Deploy",
            TemplatePath = cdkBuildOutput.AtPath("LambdaStack.template.yaml"),
            StackName = "LambdaStackDeployedName",
            AdminPermissions = true,
            ParameterOverrides = lambdaCode.Assign(lambdaBuildOutput.S3Location),
            ExtraInputs = new [] { lambdaBuildOutput }
        }) }
});
go
lambdaStack := cdk.NewStack(app, jsii.String("LambdaStack"))
lambdaCode := lambda.Code_FromCfnParameters()
lambda.NewFunction(lambdaStack, jsii.String("Lambda"), &FunctionProps{
	Code: lambdaCode,
	Handler: jsii.String("index.handler"),
	Runtime: lambda.Runtime_NODEJS_LATEST(),
})
// other resources that your Lambda needs, added to the lambdaStack...

pipelineStack := cdk.NewStack(app, jsii.String("PipelineStack"))
pipeline := codepipeline.NewPipeline(pipelineStack, jsii.String("Pipeline"), &PipelineProps{
	CrossAccountKeys: jsii.Boolean(true),
})

// add the source code repository containing this code to your Pipeline,
// and the source code of the Lambda Function, if they're separate
cdkSourceOutput := codepipeline.NewArtifact()
cdkSourceAction := codepipeline_actions.NewCodeCommitSourceAction(&CodeCommitSourceActionProps{
	Repository: codecommit.NewRepository(pipelineStack, jsii.String("CdkCodeRepo"), &RepositoryProps{
		RepositoryName: jsii.String("CdkCodeRepo"),
	}),
	ActionName: jsii.String("CdkCode_Source"),
	Output: cdkSourceOutput,
})
lambdaSourceOutput := codepipeline.NewArtifact()
lambdaSourceAction := codepipeline_actions.NewCodeCommitSourceAction(&CodeCommitSourceActionProps{
	Repository: codecommit.NewRepository(pipelineStack, jsii.String("LambdaCodeRepo"), &RepositoryProps{
		RepositoryName: jsii.String("LambdaCodeRepo"),
	}),
	ActionName: jsii.String("LambdaCode_Source"),
	Output: lambdaSourceOutput,
})
pipeline.AddStage(&StageOptions{
	StageName: jsii.String("Source"),
	Actions: []IAction{
		cdkSourceAction,
		lambdaSourceAction,
	},
})

// synthesize the Lambda CDK template, using CodeBuild
// the below values are just examples, assuming your CDK code is in TypeScript/JavaScript -
// adjust the build environment and/or commands accordingly
cdkBuildProject := codebuild.NewProject(pipelineStack, jsii.String("CdkBuildProject"), &ProjectProps{
	Environment: &BuildEnvironment{
		BuildImage: codebuild.LinuxBuildImage_STANDARD_7_0(),
	},
	BuildSpec: codebuild.BuildSpec_FromObject(map[string]interface{}{
		"version": jsii.String("0.2"),
		"phases": map[string]map[string]*string{
			"install": map[string]*string{
				"commands": jsii.String("npm install"),
			},
			"build": map[string][]*string{
				"commands": []*string{
					jsii.String("npm run build"),
					jsii.String("npm run cdk synth LambdaStack -- -o ."),
				},
			},
		},
		"artifacts": map[string]*string{
			"files": jsii.String("LambdaStack.template.yaml"),
		},
	}),
})
cdkBuildOutput := codepipeline.NewArtifact()
cdkBuildAction := codepipeline_actions.NewCodeBuildAction(&CodeBuildActionProps{
	ActionName: jsii.String("CDK_Build"),
	Project: cdkBuildProject,
	Input: cdkSourceOutput,
	Outputs: []Artifact{
		cdkBuildOutput,
	},
})

// build your Lambda code, using CodeBuild
// again, this example assumes your Lambda is written in TypeScript/JavaScript -
// make sure to adjust the build environment and/or commands if they don't match your specific situation
lambdaBuildProject := codebuild.NewProject(pipelineStack, jsii.String("LambdaBuildProject"), &ProjectProps{
	Environment: &BuildEnvironment{
		BuildImage: codebuild.LinuxBuildImage_STANDARD_7_0(),
	},
	BuildSpec: codebuild.BuildSpec_*FromObject(map[string]interface{}{
		"version": jsii.String("0.2"),
		"phases": map[string]map[string]*string{
			"install": map[string]*string{
				"commands": jsii.String("npm install"),
			},
			"build": map[string]*string{
				"commands": jsii.String("npm run build"),
			},
		},
		"artifacts": map[string][]*string{
			"files": []*string{
				jsii.String("index.js"),
				jsii.String("node_modules/**/*"),
			},
		},
	}),
})
lambdaBuildOutput := codepipeline.NewArtifact()
lambdaBuildAction := codepipeline_actions.NewCodeBuildAction(&CodeBuildActionProps{
	ActionName: jsii.String("Lambda_Build"),
	Project: lambdaBuildProject,
	Input: lambdaSourceOutput,
	Outputs: []Artifact{
		lambdaBuildOutput,
	},
})

pipeline.AddStage(&StageOptions{
	StageName: jsii.String("Build"),
	Actions: []IAction{
		cdkBuildAction,
		lambdaBuildAction,
	},
})

// finally, deploy your Lambda Stack
pipeline.AddStage(&StageOptions{
	StageName: jsii.String("Deploy"),
	Actions: []IAction{
		codepipeline_actions.NewCloudFormationCreateUpdateStackAction(&CloudFormationCreateUpdateStackActionProps{
			ActionName: jsii.String("Lambda_CFN_Deploy"),
			TemplatePath: cdkBuildOutput.AtPath(jsii.String("LambdaStack.template.yaml")),
			StackName: jsii.String("LambdaStackDeployedName"),
			AdminPermissions: jsii.Boolean(true),
			ParameterOverrides: lambdaCode.Assign(lambdaBuildOutput.s3Location),
			ExtraInputs: []Artifact{
				lambdaBuildOutput,
			},
		}),
	},
})

Cross-account actions ​

If you want to update stacks in a different account, pass the account property when creating the action:

ts
const sourceOutput = new codepipeline.Artifact();
new codepipeline_actions.CloudFormationCreateUpdateStackAction({
  actionName: 'CloudFormationCreateUpdate',
  stackName: 'MyStackName',
  adminPermissions: true,
  templatePath: sourceOutput.atPath('template.yaml'),
  account: '123456789012',
});
python
source_output = codepipeline.Artifact()
codepipeline_actions.CloudFormationCreateUpdateStackAction(
    action_name="CloudFormationCreateUpdate",
    stack_name="MyStackName",
    admin_permissions=True,
    template_path=source_output.at_path("template.yaml"),
    account="123456789012"
)
java
Artifact sourceOutput = new Artifact();
CloudFormationCreateUpdateStackAction.Builder.create()
        .actionName("CloudFormationCreateUpdate")
        .stackName("MyStackName")
        .adminPermissions(true)
        .templatePath(sourceOutput.atPath("template.yaml"))
        .account("123456789012")
        .build();
csharp
var sourceOutput = new Artifact();
new CloudFormationCreateUpdateStackAction(new CloudFormationCreateUpdateStackActionProps {
    ActionName = "CloudFormationCreateUpdate",
    StackName = "MyStackName",
    AdminPermissions = true,
    TemplatePath = sourceOutput.AtPath("template.yaml"),
    Account = "123456789012"
});
go
sourceOutput := codepipeline.NewArtifact()
codepipeline_actions.NewCloudFormationCreateUpdateStackAction(&CloudFormationCreateUpdateStackActionProps{
	ActionName: jsii.String("CloudFormationCreateUpdate"),
	StackName: jsii.String("MyStackName"),
	AdminPermissions: jsii.Boolean(true),
	TemplatePath: sourceOutput.AtPath(jsii.String("template.yaml")),
	Account: jsii.String("123456789012"),
})

This will create a new stack, called <PipelineStackName>-support-123456789012, in your App, that will contain the role that the pipeline will assume in account 123456789012 before executing this action. This support stack will automatically be deployed before the stack containing the pipeline.

You can also pass a role explicitly when creating the action - in that case, the account property is ignored, and the action will operate in the same account the role belongs to:

ts
import { PhysicalName } from 'aws-cdk-lib';

// in stack for account 123456789012...
declare const otherAccountStack: Stack;
const actionRole = new iam.Role(otherAccountStack, 'ActionRole', {
  assumedBy: new iam.AccountPrincipal('123456789012'),
  // the role has to have a physical name set
  roleName: PhysicalName.GENERATE_IF_NEEDED,
});

// in the pipeline stack...
const sourceOutput = new codepipeline.Artifact();
new codepipeline_actions.CloudFormationCreateUpdateStackAction({
  actionName: 'CloudFormationCreateUpdate',
  stackName: 'MyStackName',
  adminPermissions: true,
  templatePath: sourceOutput.atPath('template.yaml'),
  role: actionRole, // this action will be cross-account as well
});
python
from aws_cdk import PhysicalName

# in stack for account 123456789012...
# other_account_stack: Stack

action_role = iam.Role(other_account_stack, "ActionRole",
    assumed_by=iam.AccountPrincipal("123456789012"),
    # the role has to have a physical name set
    role_name=PhysicalName.GENERATE_IF_NEEDED
)

# in the pipeline stack...
source_output = codepipeline.Artifact()
codepipeline_actions.CloudFormationCreateUpdateStackAction(
    action_name="CloudFormationCreateUpdate",
    stack_name="MyStackName",
    admin_permissions=True,
    template_path=source_output.at_path("template.yaml"),
    role=action_role
)
java
import software.amazon.awscdk.PhysicalName;

// in stack for account 123456789012...
Stack otherAccountStack;

Role actionRole = Role.Builder.create(otherAccountStack, "ActionRole")
        .assumedBy(new AccountPrincipal("123456789012"))
        // the role has to have a physical name set
        .roleName(PhysicalName.GENERATE_IF_NEEDED)
        .build();

// in the pipeline stack...
Artifact sourceOutput = new Artifact();
CloudFormationCreateUpdateStackAction.Builder.create()
        .actionName("CloudFormationCreateUpdate")
        .stackName("MyStackName")
        .adminPermissions(true)
        .templatePath(sourceOutput.atPath("template.yaml"))
        .role(actionRole)
        .build();
csharp
using Amazon.CDK;

// in stack for account 123456789012...
Stack otherAccountStack;

var actionRole = new Role(otherAccountStack, "ActionRole", new RoleProps {
    AssumedBy = new AccountPrincipal("123456789012"),
    // the role has to have a physical name set
    RoleName = PhysicalName.GENERATE_IF_NEEDED
});

// in the pipeline stack...
var sourceOutput = new Artifact();
new CloudFormationCreateUpdateStackAction(new CloudFormationCreateUpdateStackActionProps {
    ActionName = "CloudFormationCreateUpdate",
    StackName = "MyStackName",
    AdminPermissions = true,
    TemplatePath = sourceOutput.AtPath("template.yaml"),
    Role = actionRole
});
go
import "github.com/aws/aws-cdk-go/awscdk"

// in stack for account 123456789012...
var otherAccountStack Stack

actionRole := iam.NewRole(otherAccountStack, jsii.String("ActionRole"), &RoleProps{
	AssumedBy: iam.NewAccountPrincipal(jsii.String("123456789012")),
	// the role has to have a physical name set
	RoleName: awscdk.PhysicalName_GENERATE_IF_NEEDED(),
})

// in the pipeline stack...
sourceOutput := codepipeline.NewArtifact()
codepipeline_actions.NewCloudFormationCreateUpdateStackAction(&CloudFormationCreateUpdateStackActionProps{
	ActionName: jsii.String("CloudFormationCreateUpdate"),
	StackName: jsii.String("MyStackName"),
	AdminPermissions: jsii.Boolean(true),
	TemplatePath: sourceOutput.AtPath(jsii.String("template.yaml")),
	Role: actionRole,
})

AWS CodeDeploy ​

Server deployments ​

To use CodeDeploy for EC2/on-premise deployments in a Pipeline:

ts
const pipeline = new codepipeline.Pipeline(this, 'MyPipeline', {
  pipelineName: 'MyPipeline',
});

// add the source and build Stages to the Pipeline...
const buildOutput = new codepipeline.Artifact();
declare const deploymentGroup: codedeploy.ServerDeploymentGroup;
const deployAction = new codepipeline_actions.CodeDeployServerDeployAction({
  actionName: 'CodeDeploy',
  input: buildOutput,
  deploymentGroup,
});
pipeline.addStage({
  stageName: 'Deploy',
  actions: [deployAction],
});
python
# deployment_group: codedeploy.ServerDeploymentGroup
pipeline = codepipeline.Pipeline(self, "MyPipeline",
    pipeline_name="MyPipeline"
)

# add the source and build Stages to the Pipeline...
build_output = codepipeline.Artifact()
deploy_action = codepipeline_actions.CodeDeployServerDeployAction(
    action_name="CodeDeploy",
    input=build_output,
    deployment_group=deployment_group
)
pipeline.add_stage(
    stage_name="Deploy",
    actions=[deploy_action]
)
java
ServerDeploymentGroup deploymentGroup;
Pipeline pipeline = Pipeline.Builder.create(this, "MyPipeline")
        .pipelineName("MyPipeline")
        .build();

// add the source and build Stages to the Pipeline...
Artifact buildOutput = new Artifact();
CodeDeployServerDeployAction deployAction = CodeDeployServerDeployAction.Builder.create()
        .actionName("CodeDeploy")
        .input(buildOutput)
        .deploymentGroup(deploymentGroup)
        .build();
pipeline.addStage(StageOptions.builder()
        .stageName("Deploy")
        .actions(List.of(deployAction))
        .build());
csharp
ServerDeploymentGroup deploymentGroup;
var pipeline = new Pipeline(this, "MyPipeline", new PipelineProps {
    PipelineName = "MyPipeline"
});

// add the source and build Stages to the Pipeline...
var buildOutput = new Artifact();
var deployAction = new CodeDeployServerDeployAction(new CodeDeployServerDeployActionProps {
    ActionName = "CodeDeploy",
    Input = buildOutput,
    DeploymentGroup = deploymentGroup
});
pipeline.AddStage(new StageOptions {
    StageName = "Deploy",
    Actions = new [] { deployAction }
});
go
var deploymentGroup ServerDeploymentGroup
pipeline := codepipeline.NewPipeline(this, jsii.String("MyPipeline"), &PipelineProps{
	PipelineName: jsii.String("MyPipeline"),
})

// add the source and build Stages to the Pipeline...
buildOutput := codepipeline.NewArtifact()
deployAction := codepipeline_actions.NewCodeDeployServerDeployAction(&CodeDeployServerDeployActionProps{
	ActionName: jsii.String("CodeDeploy"),
	Input: buildOutput,
	DeploymentGroup: DeploymentGroup,
})
pipeline.AddStage(&StageOptions{
	StageName: jsii.String("Deploy"),
	Actions: []IAction{
		deployAction,
	},
})
Lambda deployments ​

To use CodeDeploy for blue-green Lambda deployments in a Pipeline:

ts
const lambdaCode = lambda.Code.fromCfnParameters();
const func = new lambda.Function(this, 'Lambda', {
  code: lambdaCode,
  handler: 'index.handler',
  runtime: lambda.Runtime.NODEJS_LATEST,
});
// used to make sure each CDK synthesis produces a different Version
const version = func.currentVersion;
const alias = new lambda.Alias(this, 'LambdaAlias', {
  aliasName: 'Prod',
  version,
});

new codedeploy.LambdaDeploymentGroup(this, 'DeploymentGroup', {
  alias,
  deploymentConfig: codedeploy.LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE,
});
python
lambda_code = lambda_.Code.from_cfn_parameters()
func = lambda_.Function(self, "Lambda",
    code=lambda_code,
    handler="index.handler",
    runtime=lambda_.Runtime.NODEJS_LATEST
)
# used to make sure each CDK synthesis produces a different Version
version = func.current_version
alias = lambda_.Alias(self, "LambdaAlias",
    alias_name="Prod",
    version=version
)

codedeploy.LambdaDeploymentGroup(self, "DeploymentGroup",
    alias=alias,
    deployment_config=codedeploy.LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE
)
java
CfnParametersCode lambdaCode = Code.fromCfnParameters();
Function func = Function.Builder.create(this, "Lambda")
        .code(lambdaCode)
        .handler("index.handler")
        .runtime(Runtime.NODEJS_LATEST)
        .build();
// used to make sure each CDK synthesis produces a different Version
Version version = func.getCurrentVersion();
Alias alias = Alias.Builder.create(this, "LambdaAlias")
        .aliasName("Prod")
        .version(version)
        .build();

LambdaDeploymentGroup.Builder.create(this, "DeploymentGroup")
        .alias(alias)
        .deploymentConfig(LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE)
        .build();
csharp
var lambdaCode = Code.FromCfnParameters();
var func = new Function(this, "Lambda", new FunctionProps {
    Code = lambdaCode,
    Handler = "index.handler",
    Runtime = Runtime.NODEJS_LATEST
});
// used to make sure each CDK synthesis produces a different Version
var version = func.CurrentVersion;
var alias = new Alias(this, "LambdaAlias", new AliasProps {
    AliasName = "Prod",
    Version = version
});

new LambdaDeploymentGroup(this, "DeploymentGroup", new LambdaDeploymentGroupProps {
    Alias = alias,
    DeploymentConfig = LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE
});
go
lambdaCode := lambda.Code_FromCfnParameters()
func := lambda.NewFunction(this, jsii.String("Lambda"), &FunctionProps{
	Code: lambdaCode,
	Handler: jsii.String("index.handler"),
	Runtime: lambda.Runtime_NODEJS_LATEST(),
})
// used to make sure each CDK synthesis produces a different Version
version := func.currentVersion
alias := lambda.NewAlias(this, jsii.String("LambdaAlias"), &AliasProps{
	AliasName: jsii.String("Prod"),
	Version: Version,
})

codedeploy.NewLambdaDeploymentGroup(this, jsii.String("DeploymentGroup"), &LambdaDeploymentGroupProps{
	Alias: Alias,
	DeploymentConfig: codedeploy.LambdaDeploymentConfig_LINEAR_10PERCENT_EVERY_1MINUTE(),
})

Then, you need to create your Pipeline Stack, where you will define your Pipeline, and deploy the lambdaStack using a CloudFormation CodePipeline Action (see above for a complete example).

ECS ​

CodePipeline can deploy an ECS service. The deploy Action receives one input Artifact which contains the image definition file:

ts
import * as ecs from 'aws-cdk-lib/aws-ecs';

declare const service: ecs.FargateService;
const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const buildOutput = new codepipeline.Artifact();
const deployStage = pipeline.addStage({
  stageName: 'Deploy',
  actions: [
    new codepipeline_actions.EcsDeployAction({
      actionName: 'DeployAction',
      service,
      // if your file is called imagedefinitions.json,
      // use the `input` property,
      // and leave out the `imageFile` property
      input: buildOutput,
      // if your file name is _not_ imagedefinitions.json,
      // use the `imageFile` property,
      // and leave out the `input` property
      imageFile: buildOutput.atPath('imageDef.json'),
      deploymentTimeout: Duration.minutes(60), // optional, default is 60 minutes
    }),
  ],
});
python
import aws_cdk.aws_ecs as ecs

# service: ecs.FargateService

pipeline = codepipeline.Pipeline(self, "MyPipeline")
build_output = codepipeline.Artifact()
deploy_stage = pipeline.add_stage(
    stage_name="Deploy",
    actions=[
        codepipeline_actions.EcsDeployAction(
            action_name="DeployAction",
            service=service,
            # if your file is called imagedefinitions.json,
            # use the `input` property,
            # and leave out the `imageFile` property
            input=build_output,
            # if your file name is _not_ imagedefinitions.json,
            # use the `imageFile` property,
            # and leave out the `input` property
            image_file=build_output.at_path("imageDef.json"),
            deployment_timeout=Duration.minutes(60)
        )
    ]
)
java
import software.amazon.awscdk.services.ecs.*;

FargateService service;

Pipeline pipeline = new Pipeline(this, "MyPipeline");
Artifact buildOutput = new Artifact();
IStage deployStage = pipeline.addStage(StageOptions.builder()
        .stageName("Deploy")
        .actions(List.of(
            EcsDeployAction.Builder.create()
                    .actionName("DeployAction")
                    .service(service)
                    // if your file is called imagedefinitions.json,
                    // use the `input` property,
                    // and leave out the `imageFile` property
                    .input(buildOutput)
                    // if your file name is _not_ imagedefinitions.json,
                    // use the `imageFile` property,
                    // and leave out the `input` property
                    .imageFile(buildOutput.atPath("imageDef.json"))
                    .deploymentTimeout(Duration.minutes(60))
                    .build()))
        .build());
csharp
using Amazon.CDK.AWS.ECS;

FargateService service;

var pipeline = new Pipeline(this, "MyPipeline");
var buildOutput = new Artifact();
var deployStage = pipeline.AddStage(new StageOptions {
    StageName = "Deploy",
    Actions = new [] {
        new EcsDeployAction(new EcsDeployActionProps {
            ActionName = "DeployAction",
            Service = service,
            // if your file is called imagedefinitions.json,
            // use the `input` property,
            // and leave out the `imageFile` property
            Input = buildOutput,
            // if your file name is _not_ imagedefinitions.json,
            // use the `imageFile` property,
            // and leave out the `input` property
            ImageFile = buildOutput.AtPath("imageDef.json"),
            DeploymentTimeout = Duration.Minutes(60)
        }) }
});
go
import ecs "github.com/aws/aws-cdk-go/awscdk"

var service FargateService

pipeline := codepipeline.NewPipeline(this, jsii.String("MyPipeline"))
buildOutput := codepipeline.NewArtifact()
deployStage := pipeline.AddStage(&StageOptions{
	StageName: jsii.String("Deploy"),
	Actions: []IAction{
		codepipeline_actions.NewEcsDeployAction(&EcsDeployActionProps{
			ActionName: jsii.String("DeployAction"),
			Service: *Service,
			// if your file is called imagedefinitions.json,
			// use the `input` property,
			// and leave out the `imageFile` property
			Input: buildOutput,
			// if your file name is _not_ imagedefinitions.json,
			// use the `imageFile` property,
			// and leave out the `input` property
			ImageFile: buildOutput.AtPath(jsii.String("imageDef.json")),
			DeploymentTimeout: awscdk.Duration_Minutes(jsii.Number(60)),
		}),
	},
})

Deploying ECS applications to existing services ​

CodePipeline can deploy to an existing ECS service which uses the ECS service ARN format that contains the Cluster name. This also works if the service is in a different account and/or region than the pipeline:

ts
import * as ecs from 'aws-cdk-lib/aws-ecs';

const service = ecs.BaseService.fromServiceArnWithCluster(this, 'EcsService',
  'arn:aws:ecs:us-east-1:123456789012:service/myClusterName/myServiceName'
);
const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const buildOutput = new codepipeline.Artifact();
// add source and build stages to the pipeline as usual...
const deployStage = pipeline.addStage({
  stageName: 'Deploy',
  actions: [
    new codepipeline_actions.EcsDeployAction({
      actionName: 'DeployAction',
      service: service,
      input: buildOutput,
    }),
  ],
});
python
import aws_cdk.aws_ecs as ecs


service = ecs.BaseService.from_service_arn_with_cluster(self, "EcsService", "arn:aws:ecs:us-east-1:123456789012:service/myClusterName/myServiceName")
pipeline = codepipeline.Pipeline(self, "MyPipeline")
build_output = codepipeline.Artifact()
# add source and build stages to the pipeline as usual...
deploy_stage = pipeline.add_stage(
    stage_name="Deploy",
    actions=[
        codepipeline_actions.EcsDeployAction(
            action_name="DeployAction",
            service=service,
            input=build_output
        )
    ]
)
java
import software.amazon.awscdk.services.ecs.*;


IBaseService service = BaseService.fromServiceArnWithCluster(this, "EcsService", "arn:aws:ecs:us-east-1:123456789012:service/myClusterName/myServiceName");
Pipeline pipeline = new Pipeline(this, "MyPipeline");
Artifact buildOutput = new Artifact();
// add source and build stages to the pipeline as usual...
IStage deployStage = pipeline.addStage(StageOptions.builder()
        .stageName("Deploy")
        .actions(List.of(
            EcsDeployAction.Builder.create()
                    .actionName("DeployAction")
                    .service(service)
                    .input(buildOutput)
                    .build()))
        .build());
csharp
using Amazon.CDK.AWS.ECS;


var service = BaseService.FromServiceArnWithCluster(this, "EcsService", "arn:aws:ecs:us-east-1:123456789012:service/myClusterName/myServiceName");
var pipeline = new Pipeline(this, "MyPipeline");
var buildOutput = new Artifact();
// add source and build stages to the pipeline as usual...
var deployStage = pipeline.AddStage(new StageOptions {
    StageName = "Deploy",
    Actions = new [] {
        new EcsDeployAction(new EcsDeployActionProps {
            ActionName = "DeployAction",
            Service = service,
            Input = buildOutput
        }) }
});
go
import ecs "github.com/aws/aws-cdk-go/awscdk"


service := ecs.BaseService_FromServiceArnWithCluster(this, jsii.String("EcsService"), jsii.String("arn:aws:ecs:us-east-1:123456789012:service/myClusterName/myServiceName"))
pipeline := codepipeline.NewPipeline(this, jsii.String("MyPipeline"))
buildOutput := codepipeline.NewArtifact()
// add source and build stages to the pipeline as usual...
deployStage := pipeline.AddStage(&StageOptions{
	StageName: jsii.String("Deploy"),
	Actions: []IAction{
		codepipeline_actions.NewEcsDeployAction(&EcsDeployActionProps{
			ActionName: jsii.String("DeployAction"),
			Service: service,
			Input: buildOutput,
		}),
	},
})

When deploying across accounts, especially in a CDK Pipelines self-mutating pipeline, it is recommended to provide the role property to the EcsDeployAction. The Role will need to have permissions assigned to it for ECS deployment. See the CodePipeline documentation for the permissions needed.

Deploying ECS applications stored in a separate source code repository ​

The idiomatic CDK way of deploying an ECS application is to have your Dockerfiles and your CDK code in the same source code repository, leveraging Docker Assets, and use the CDK Pipelines module.

However, if you want to deploy a Docker application whose source code is kept in a separate version control repository than the CDK code, you can use the TagParameterContainerImage class from the ECS module. Here's an example:

ts

/**
 * These are the construction properties for `EcsAppStack`.
 * They extend the standard Stack properties,
 * but also require providing the ContainerImage that the service will use.
 * That Image will be provided from the Stack containing the CodePipeline.
 */
export interface EcsAppStackProps extends cdk.StackProps {
  readonly image: ecs.ContainerImage;
}

/**
 * This is the Stack containing a simple ECS Service that uses the provided ContainerImage.
 */
export class EcsAppStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props: EcsAppStackProps) {
    super(scope, id, props);

    const taskDefinition = new ecs.TaskDefinition(this, 'TaskDefinition', {
      compatibility: ecs.Compatibility.FARGATE,
      cpu: '1024',
      memoryMiB: '2048',
    });
    taskDefinition.addContainer('AppContainer', {
      image: props.image,
    });
    new ecs.FargateService(this, 'EcsService', {
      taskDefinition,
      cluster: new ecs.Cluster(this, 'Cluster', {
        vpc: new ec2.Vpc(this, 'Vpc', {
          maxAzs: 1,
        }),
      }),
    });
  }
}

/**
 * This is the Stack containing the CodePipeline definition that deploys an ECS Service.
 */
export class PipelineStack extends cdk.Stack {
  public readonly tagParameterContainerImage: ecs.TagParameterContainerImage;

  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    /* ********** ECS part **************** */

    // this is the ECR repository where the built Docker image will be pushed
    const appEcrRepo = new ecr.Repository(this, 'EcsDeployRepository');
    // the build that creates the Docker image, and pushes it to the ECR repo
    const appCodeDockerBuild = new codebuild.PipelineProject(this, 'AppCodeDockerImageBuildAndPushProject', {
      environment: {
        // we need to run Docker
        privileged: true,
      },
      buildSpec: codebuild.BuildSpec.fromObject({
        version: '0.2',
        phases: {
          build: {
            commands: [
              // login to ECR first
              '$(aws ecr get-login --region $AWS_DEFAULT_REGION --no-include-email)',
              // if your application needs any build steps, they would be invoked here

              // build the image, and tag it with the commit hash
              // (CODEBUILD_RESOLVED_SOURCE_VERSION is a special environment variable available in CodeBuild)
              'docker build -t $REPOSITORY_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION .',
            ],
          },
          post_build: {
            commands: [
              // push the built image into the ECR repository
              'docker push $REPOSITORY_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION',
              // save the declared tag as an environment variable,
              // that is then exported below in the 'exported-variables' section as a CodePipeline Variable
              'export imageTag=$CODEBUILD_RESOLVED_SOURCE_VERSION',
            ],
          },
        },
        env: {
          // save the imageTag environment variable as a CodePipeline Variable
          'exported-variables': [
            'imageTag',
          ],
        },
      }),
      environmentVariables: {
        REPOSITORY_URI: {
          value: appEcrRepo.repositoryUri,
        },
      },
    });
    // needed for `docker push`
    appEcrRepo.grantPullPush(appCodeDockerBuild);
    // create the ContainerImage used for the ECS application Stack
    this.tagParameterContainerImage = new ecs.TagParameterContainerImage(appEcrRepo);

    const cdkCodeBuild = new codebuild.PipelineProject(this, 'CdkCodeBuildProject', {
      buildSpec: codebuild.BuildSpec.fromObject({
        version: '0.2',
        phases: {
          install: {
            commands: [
              'npm install',
            ],
          },
          build: {
            commands: [
              // synthesize the CDK code for the ECS application Stack
              'npx cdk synth --verbose',
            ],
          },
        },
        artifacts: {
          // store the entire Cloud Assembly as the output artifact
          'base-directory': 'cdk.out',
          'files': '**/*',
        },
      }),
    });

    /* ********** Pipeline part **************** */

    const appCodeSourceOutput = new codepipeline.Artifact();
    const cdkCodeSourceOutput = new codepipeline.Artifact();
    const cdkCodeBuildOutput = new codepipeline.Artifact();
    const appCodeBuildAction = new codepipeline_actions.CodeBuildAction({
      actionName: 'AppCodeDockerImageBuildAndPush',
      project: appCodeDockerBuild,
      input: appCodeSourceOutput,
    });
    new codepipeline.Pipeline(this, 'CodePipelineDeployingEcsApplication', {
      artifactBucket: new s3.Bucket(this, 'ArtifactBucket', {
        removalPolicy: cdk.RemovalPolicy.DESTROY,
      }),
      stages: [
        {
          stageName: 'Source',
          actions: [
            // this is the Action that takes the source of your application code
            new codepipeline_actions.CodeCommitSourceAction({
              actionName: 'AppCodeSource',
              repository: new codecommit.Repository(this, 'AppCodeSourceRepository', { repositoryName: 'AppCodeSourceRepository' }),
              output: appCodeSourceOutput,
            }),
            // this is the Action that takes the source of your CDK code
            // (which would probably include this Pipeline code as well)
            new codepipeline_actions.CodeCommitSourceAction({
              actionName: 'CdkCodeSource',
              repository: new codecommit.Repository(this, 'CdkCodeSourceRepository', { repositoryName: 'CdkCodeSourceRepository' }),
              output: cdkCodeSourceOutput,
            }),
          ],
        },
        {
          stageName: 'Build',
          actions: [
            appCodeBuildAction,
            new codepipeline_actions.CodeBuildAction({
              actionName: 'CdkCodeBuildAndSynth',
              project: cdkCodeBuild,
              input: cdkCodeSourceOutput,
              outputs: [cdkCodeBuildOutput],
            }),
          ],
        },
        {
          stageName: 'Deploy',
          actions: [
            new codepipeline_actions.CloudFormationCreateUpdateStackAction({
              actionName: 'CFN_Deploy',
              stackName: 'SampleEcsStackDeployedFromCodePipeline',
              // this name has to be the same name as used below in the CDK code for the application Stack
              templatePath: cdkCodeBuildOutput.atPath('EcsStackDeployedInPipeline.template.json'),
              adminPermissions: true,
              parameterOverrides: {
                // read the tag pushed to the ECR repository from the CodePipeline Variable saved by the application build step,
                // and pass it as the CloudFormation Parameter for the tag
                [this.tagParameterContainerImage.tagParameterName]: appCodeBuildAction.variable('imageTag'),
              },
            }),
          ],
        },
      ],
    });
  }
}

const app = new cdk.App();

// the CodePipeline Stack needs to be created first
const pipelineStack = new PipelineStack(app, 'aws-cdk-pipeline-ecs-separate-sources');
// we supply the image to the ECS application Stack from the CodePipeline Stack
new EcsAppStack(app, 'EcsStackDeployedInPipeline', {
  image: pipelineStack.tagParameterContainerImage,
});
python
#
# This is the Stack containing a simple ECS Service that uses the provided ContainerImage.
#
class EcsAppStack(cdk.Stack):
    def __init__(self, scope, id, *, image, description=None, env=None, stackName=None, tags=None, notificationArns=None, synthesizer=None, terminationProtection=None, analyticsReporting=None, crossRegionReferences=None, permissionsBoundary=None, suppressTemplateIndentation=None, propertyInjectors=None):
        super().__init__(scope, id, image=image, description=description, env=env, stackName=stackName, tags=tags, notificationArns=notificationArns, synthesizer=synthesizer, terminationProtection=terminationProtection, analyticsReporting=analyticsReporting, crossRegionReferences=crossRegionReferences, permissionsBoundary=permissionsBoundary, suppressTemplateIndentation=suppressTemplateIndentation, propertyInjectors=propertyInjectors)

        task_definition = ecs.TaskDefinition(self, "TaskDefinition",
            compatibility=ecs.Compatibility.FARGATE,
            cpu="1024",
            memory_mi_b="2048"
        )
        task_definition.add_container("AppContainer",
            image=image
        )
        ecs.FargateService(self, "EcsService",
            task_definition=task_definition,
            cluster=ecs.Cluster(self, "Cluster",
                vpc=ec2.Vpc(self, "Vpc",
                    max_azs=1
                )
            )
        )

#
# This is the Stack containing the CodePipeline definition that deploys an ECS Service.
#
class PipelineStack(cdk.Stack):

    def __init__(self, scope, id, *, description=None, env=None, stackName=None, tags=None, notificationArns=None, synthesizer=None, terminationProtection=None, analyticsReporting=None, crossRegionReferences=None, permissionsBoundary=None, suppressTemplateIndentation=None, propertyInjectors=None):
        super().__init__(scope, id, description=description, env=env, stackName=stackName, tags=tags, notificationArns=notificationArns, synthesizer=synthesizer, terminationProtection=terminationProtection, analyticsReporting=analyticsReporting, crossRegionReferences=crossRegionReferences, permissionsBoundary=permissionsBoundary, suppressTemplateIndentation=suppressTemplateIndentation, propertyInjectors=propertyInjectors)

        # ********* ECS part ****************

        # this is the ECR repository where the built Docker image will be pushed
        app_ecr_repo = ecr.Repository(self, "EcsDeployRepository")
        # the build that creates the Docker image, and pushes it to the ECR repo
        app_code_docker_build = codebuild.PipelineProject(self, "AppCodeDockerImageBuildAndPushProject",
            environment=codebuild.BuildEnvironment(
                # we need to run Docker
                privileged=True
            ),
            build_spec=codebuild.BuildSpec.from_object({
                "version": "0.2",
                "phases": {
                    "build": {
                        "commands": ["$(aws ecr get-login --region $AWS_DEFAULT_REGION --no-include-email)", "docker build -t $REPOSITORY_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION ."
                        ]
                    },
                    "post_build": {
                        "commands": ["docker push $REPOSITORY_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION", "export imageTag=$CODEBUILD_RESOLVED_SOURCE_VERSION"
                        ]
                    }
                },
                "env": {
                    # save the imageTag environment variable as a CodePipeline Variable
                    "exported-variables": ["imageTag"
                    ]
                }
            }),
            environment_variables={
                "REPOSITORY_URI": codebuild.BuildEnvironmentVariable(
                    value=app_ecr_repo.repository_uri
                )
            }
        )
        # needed for `docker push`
        app_ecr_repo.grant_pull_push(app_code_docker_build)
        # create the ContainerImage used for the ECS application Stack
        self.tag_parameter_container_image = ecs.TagParameterContainerImage(app_ecr_repo)

        cdk_code_build = codebuild.PipelineProject(self, "CdkCodeBuildProject",
            build_spec=codebuild.BuildSpec.from_object({
                "version": "0.2",
                "phases": {
                    "install": {
                        "commands": ["npm install"
                        ]
                    },
                    "build": {
                        "commands": ["npx cdk synth --verbose"
                        ]
                    }
                },
                "artifacts": {
                    # store the entire Cloud Assembly as the output artifact
                    "base-directory": "cdk.out",
                    "files": "**/*"
                }
            })
        )

        # ********* Pipeline part ****************

        app_code_source_output = codepipeline.Artifact()
        cdk_code_source_output = codepipeline.Artifact()
        cdk_code_build_output = codepipeline.Artifact()
        app_code_build_action = codepipeline_actions.CodeBuildAction(
            action_name="AppCodeDockerImageBuildAndPush",
            project=app_code_docker_build,
            input=app_code_source_output
        )
        codepipeline.Pipeline(self, "CodePipelineDeployingEcsApplication",
            artifact_bucket=s3.Bucket(self, "ArtifactBucket",
                removal_policy=cdk.RemovalPolicy.DESTROY
            ),
            stages=[codepipeline.StageProps(
                stage_name="Source",
                actions=[
                    # this is the Action that takes the source of your application code
                    codepipeline_actions.CodeCommitSourceAction(
                        action_name="AppCodeSource",
                        repository=codecommit.Repository(self, "AppCodeSourceRepository", repository_name="AppCodeSourceRepository"),
                        output=app_code_source_output
                    ),
                    # this is the Action that takes the source of your CDK code
                    # (which would probably include this Pipeline code as well)
                    codepipeline_actions.CodeCommitSourceAction(
                        action_name="CdkCodeSource",
                        repository=codecommit.Repository(self, "CdkCodeSourceRepository", repository_name="CdkCodeSourceRepository"),
                        output=cdk_code_source_output
                    )
                ]
            ), codepipeline.StageProps(
                stage_name="Build",
                actions=[app_code_build_action,
                    codepipeline_actions.CodeBuildAction(
                        action_name="CdkCodeBuildAndSynth",
                        project=cdk_code_build,
                        input=cdk_code_source_output,
                        outputs=[cdk_code_build_output]
                    )
                ]
            ), codepipeline.StageProps(
                stage_name="Deploy",
                actions=[
                    codepipeline_actions.CloudFormationCreateUpdateStackAction(
                        action_name="CFN_Deploy",
                        stack_name="SampleEcsStackDeployedFromCodePipeline",
                        # this name has to be the same name as used below in the CDK code for the application Stack
                        template_path=cdk_code_build_output.at_path("EcsStackDeployedInPipeline.template.json"),
                        admin_permissions=True,
                        parameter_overrides={
                            # read the tag pushed to the ECR repository from the CodePipeline Variable saved by the application build step,
                            # and pass it as the CloudFormation Parameter for the tag
                            "self.tag_parameter_container_image.tag_parameter_name": app_code_build_action.variable("imageTag")
                        }
                    )
                ]
            )
            ]
        )

app = cdk.App()

# the CodePipeline Stack needs to be created first
pipeline_stack = PipelineStack(app, "aws-cdk-pipeline-ecs-separate-sources")
# we supply the image to the ECS application Stack from the CodePipeline Stack
EcsAppStack(app, "EcsStackDeployedInPipeline",
    image=pipeline_stack.tag_parameter_container_image
)
java
/**
 * These are the construction properties for `EcsAppStack`.
 * They extend the standard Stack properties,
 * but also require providing the ContainerImage that the service will use.
 * That Image will be provided from the Stack containing the CodePipeline.
 */
public class EcsAppStackProps extends StackProps {
    private ContainerImage image;
    public ContainerImage getImage() {
        return this.image;
    }
    public EcsAppStackProps image(ContainerImage image) {
        this.image = image;
        return this;
    }
}

/**
 * This is the Stack containing a simple ECS Service that uses the provided ContainerImage.
 */
public class EcsAppStack extends Stack {
    public EcsAppStack(Construct scope, String id, EcsAppStackProps props) {
        super(scope, id, props);

        TaskDefinition taskDefinition = TaskDefinition.Builder.create(this, "TaskDefinition")
                .compatibility(Compatibility.FARGATE)
                .cpu("1024")
                .memoryMiB("2048")
                .build();
        taskDefinition.addContainer("AppContainer", ContainerDefinitionOptions.builder()
                .image(props.getImage())
                .build());
        FargateService.Builder.create(this, "EcsService")
                .taskDefinition(taskDefinition)
                .cluster(Cluster.Builder.create(this, "Cluster")
                        .vpc(Vpc.Builder.create(this, "Vpc")
                                .maxAzs(1)
                                .build())
                        .build())
                .build();
    }
}

/**
 * This is the Stack containing the CodePipeline definition that deploys an ECS Service.
 */
public class PipelineStack extends Stack {
    public final TagParameterContainerImage tagParameterContainerImage;

    public PipelineStack(Construct scope, String id) {
        this(scope, id, null);
    }

    public PipelineStack(Construct scope, String id, StackProps props) {
        super(scope, id, props);

        /* ********** ECS part **************** */

        // this is the ECR repository where the built Docker image will be pushed
        Repository appEcrRepo = new Repository(this, "EcsDeployRepository");
        // the build that creates the Docker image, and pushes it to the ECR repo
        PipelineProject appCodeDockerBuild = PipelineProject.Builder.create(this, "AppCodeDockerImageBuildAndPushProject")
                .environment(BuildEnvironment.builder()
                        // we need to run Docker
                        .privileged(true)
                        .build())
                .buildSpec(BuildSpec.fromObject(Map.of(
                        "version", "0.2",
                        "phases", Map.of(
                                "build", Map.of(
                                        "commands", List.of("$(aws ecr get-login --region $AWS_DEFAULT_REGION --no-include-email)", "docker build -t $REPOSITORY_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION .")),
                                "post_build", Map.of(
                                        "commands", List.of("docker push $REPOSITORY_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION", "export imageTag=$CODEBUILD_RESOLVED_SOURCE_VERSION"))),
                        "env", Map.of(
                                // save the imageTag environment variable as a CodePipeline Variable
                                "exported-variables", List.of("imageTag")))))
                .environmentVariables(Map.of(
                        "REPOSITORY_URI", BuildEnvironmentVariable.builder()
                                .value(appEcrRepo.getRepositoryUri())
                                .build()))
                .build();
        // needed for `docker push`
        appEcrRepo.grantPullPush(appCodeDockerBuild);
        // create the ContainerImage used for the ECS application Stack
        this.tagParameterContainerImage = new TagParameterContainerImage(appEcrRepo);

        PipelineProject cdkCodeBuild = PipelineProject.Builder.create(this, "CdkCodeBuildProject")
                .buildSpec(BuildSpec.fromObject(Map.of(
                        "version", "0.2",
                        "phases", Map.of(
                                "install", Map.of(
                                        "commands", List.of("npm install")),
                                "build", Map.of(
                                        "commands", List.of("npx cdk synth --verbose"))),
                        "artifacts", Map.of(
                                // store the entire Cloud Assembly as the output artifact
                                "base-directory", "cdk.out",
                                "files", "**/*"))))
                .build();

        /* ********** Pipeline part **************** */

        Artifact appCodeSourceOutput = new Artifact();
        Artifact cdkCodeSourceOutput = new Artifact();
        Artifact cdkCodeBuildOutput = new Artifact();
        CodeBuildAction appCodeBuildAction = CodeBuildAction.Builder.create()
                .actionName("AppCodeDockerImageBuildAndPush")
                .project(appCodeDockerBuild)
                .input(appCodeSourceOutput)
                .build();
        Pipeline.Builder.create(this, "CodePipelineDeployingEcsApplication")
                .artifactBucket(Bucket.Builder.create(this, "ArtifactBucket")
                        .removalPolicy(RemovalPolicy.DESTROY)
                        .build())
                .stages(List.of(StageProps.builder()
                        .stageName("Source")
                        .actions(List.of(
                            // this is the Action that takes the source of your application code
                            CodeCommitSourceAction.Builder.create()
                                    .actionName("AppCodeSource")
                                    .repository(Repository.Builder.create(this, "AppCodeSourceRepository").repositoryName("AppCodeSourceRepository").build())
                                    .output(appCodeSourceOutput)
                                    .build(),
                            // this is the Action that takes the source of your CDK code
                            // (which would probably include this Pipeline code as well)
                            CodeCommitSourceAction.Builder.create()
                                    .actionName("CdkCodeSource")
                                    .repository(Repository.Builder.create(this, "CdkCodeSourceRepository").repositoryName("CdkCodeSourceRepository").build())
                                    .output(cdkCodeSourceOutput)
                                    .build()))
                        .build(), StageProps.builder()
                        .stageName("Build")
                        .actions(List.of(appCodeBuildAction,
                            CodeBuildAction.Builder.create()
                                    .actionName("CdkCodeBuildAndSynth")
                                    .project(cdkCodeBuild)
                                    .input(cdkCodeSourceOutput)
                                    .outputs(List.of(cdkCodeBuildOutput))
                                    .build()))
                        .build(), StageProps.builder()
                        .stageName("Deploy")
                        .actions(List.of(
                            CloudFormationCreateUpdateStackAction.Builder.create()
                                    .actionName("CFN_Deploy")
                                    .stackName("SampleEcsStackDeployedFromCodePipeline")
                                    // this name has to be the same name as used below in the CDK code for the application Stack
                                    .templatePath(cdkCodeBuildOutput.atPath("EcsStackDeployedInPipeline.template.json"))
                                    .adminPermissions(true)
                                    .parameterOverrides(Map.of(
                                            // read the tag pushed to the ECR repository from the CodePipeline Variable saved by the application build step,
                                            // and pass it as the CloudFormation Parameter for the tag
                                            this.tagParameterContainerImage.getTagParameterName(), appCodeBuildAction.variable("imageTag")))
                                    .build()))
                        .build()))
                .build();
    }
}

App app = new App();

// the CodePipeline Stack needs to be created first
PipelineStack pipelineStack = new PipelineStack(app, "aws-cdk-pipeline-ecs-separate-sources");
// we supply the image to the ECS application Stack from the CodePipeline Stack
// we supply the image to the ECS application Stack from the CodePipeline Stack
new EcsAppStack(app, "EcsStackDeployedInPipeline", new EcsAppStackProps()
        .image(pipelineStack.getTagParameterContainerImage())
        );
csharp
/**
 * These are the construction properties for `EcsAppStack`.
 * They extend the standard Stack properties,
 * but also require providing the ContainerImage that the service will use.
 * That Image will be provided from the Stack containing the CodePipeline.
 */
class EcsAppStackProps : StackProps
{
    public ContainerImage Image { get; set; }
}

/**
 * This is the Stack containing a simple ECS Service that uses the provided ContainerImage.
 */
class EcsAppStack : Stack
{
    public EcsAppStack(Construct scope, string id, EcsAppStackProps props) : base(scope, id, props)
    {

        var taskDefinition = new TaskDefinition(this, "TaskDefinition", new TaskDefinitionProps {
            Compatibility = Compatibility.FARGATE,
            Cpu = "1024",
            MemoryMiB = "2048"
        });
        taskDefinition.AddContainer("AppContainer", new ContainerDefinitionOptions {
            Image = props.Image
        });
        new FargateService(this, "EcsService", new FargateServiceProps {
            TaskDefinition = taskDefinition,
            Cluster = new Cluster(this, "Cluster", new ClusterProps {
                Vpc = new Vpc(this, "Vpc", new VpcProps {
                    MaxAzs = 1
                })
            })
        });
    }
}

/**
 * This is the Stack containing the CodePipeline definition that deploys an ECS Service.
 */
class PipelineStack : Stack
{
    public TagParameterContainerImage TagParameterContainerImage { get; }

    public PipelineStack(Construct scope, string id, StackProps? props=null) : base(scope, id, props)
    {

        /* ********** ECS part **************** */

        // this is the ECR repository where the built Docker image will be pushed
        var appEcrRepo = new Repository(this, "EcsDeployRepository");
        // the build that creates the Docker image, and pushes it to the ECR repo
        var appCodeDockerBuild = new PipelineProject(this, "AppCodeDockerImageBuildAndPushProject", new PipelineProjectProps {
            Environment = new BuildEnvironment {
                // we need to run Docker
                Privileged = true
            },
            BuildSpec = BuildSpec.FromObject(new Dictionary<string, object> {
                { "version", "0.2" },
                { "phases", new Dictionary<string, IDictionary<string, string[]>> {
                    { "build", new Struct {
                        Commands = new [] { "$(aws ecr get-login --region $AWS_DEFAULT_REGION --no-include-email)", "docker build -t $REPOSITORY_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION ." }
                    } },
                    { "post_build", new Struct {
                        Commands = new [] { "docker push $REPOSITORY_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION", "export imageTag=$CODEBUILD_RESOLVED_SOURCE_VERSION" }
                    } }
                } },
                { "env", new Dictionary<string, string[]> {
                    // save the imageTag environment variable as a CodePipeline Variable
                    { "exported-variables", new [] { "imageTag" } }
                } }
            }),
            EnvironmentVariables = new Dictionary<string, BuildEnvironmentVariable> {
                { "REPOSITORY_URI", new BuildEnvironmentVariable {
                    Value = appEcrRepo.RepositoryUri
                } }
            }
        });
        // needed for `docker push`
        appEcrRepo.GrantPullPush(appCodeDockerBuild);
        // create the ContainerImage used for the ECS application Stack
        TagParameterContainerImage = new TagParameterContainerImage(appEcrRepo);

        var cdkCodeBuild = new PipelineProject(this, "CdkCodeBuildProject", new PipelineProjectProps {
            BuildSpec = BuildSpec.FromObject(new Dictionary<string, object> {
                { "version", "0.2" },
                { "phases", new Dictionary<string, IDictionary<string, string[]>> {
                    { "install", new Struct {
                        Commands = new [] { "npm install" }
                    } },
                    { "build", new Struct {
                        Commands = new [] { "npx cdk synth --verbose" }
                    } }
                } },
                { "artifacts", new Dictionary<string, string> {
                    // store the entire Cloud Assembly as the output artifact
                    { "base-directory", "cdk.out" },
                    { "files", "**/*" }
                } }
            })
        });

        /* ********** Pipeline part **************** */

        var appCodeSourceOutput = new Artifact();
        var cdkCodeSourceOutput = new Artifact();
        var cdkCodeBuildOutput = new Artifact();
        var appCodeBuildAction = new CodeBuildAction(new CodeBuildActionProps {
            ActionName = "AppCodeDockerImageBuildAndPush",
            Project = appCodeDockerBuild,
            Input = appCodeSourceOutput
        });
        new Pipeline(this, "CodePipelineDeployingEcsApplication", new PipelineProps {
            ArtifactBucket = new Bucket(this, "ArtifactBucket", new BucketProps {
                RemovalPolicy = RemovalPolicy.DESTROY
            }),
            Stages = new [] { new StageProps {
                StageName = "Source",
                Actions = new [] {
                    // this is the Action that takes the source of your application code
                    new CodeCommitSourceAction(new CodeCommitSourceActionProps {
                        ActionName = "AppCodeSource",
                        Repository = new Repository(this, "AppCodeSourceRepository", new RepositoryProps { RepositoryName = "AppCodeSourceRepository" }),
                        Output = appCodeSourceOutput
                    }),
                    // this is the Action that takes the source of your CDK code
                    // (which would probably include this Pipeline code as well)
                    new CodeCommitSourceAction(new CodeCommitSourceActionProps {
                        ActionName = "CdkCodeSource",
                        Repository = new Repository(this, "CdkCodeSourceRepository", new RepositoryProps { RepositoryName = "CdkCodeSourceRepository" }),
                        Output = cdkCodeSourceOutput
                    }) }
            }, new StageProps {
                StageName = "Build",
                Actions = new [] { appCodeBuildAction,
                    new CodeBuildAction(new CodeBuildActionProps {
                        ActionName = "CdkCodeBuildAndSynth",
                        Project = cdkCodeBuild,
                        Input = cdkCodeSourceOutput,
                        Outputs = new [] { cdkCodeBuildOutput }
                    }) }
            }, new StageProps {
                StageName = "Deploy",
                Actions = new [] {
                    new CloudFormationCreateUpdateStackAction(new CloudFormationCreateUpdateStackActionProps {
                        ActionName = "CFN_Deploy",
                        StackName = "SampleEcsStackDeployedFromCodePipeline",
                        // this name has to be the same name as used below in the CDK code for the application Stack
                        TemplatePath = cdkCodeBuildOutput.AtPath("EcsStackDeployedInPipeline.template.json"),
                        AdminPermissions = true,
                        ParameterOverrides = new Dictionary<string, object> {
                            // read the tag pushed to the ECR repository from the CodePipeline Variable saved by the application build step,
                            // and pass it as the CloudFormation Parameter for the tag
                            { TagParameterContainerImage.TagParameterName, appCodeBuildAction.Variable("imageTag") }
                        }
                    }) }
            } }
        });
    }
}

var app = new App();

// the CodePipeline Stack needs to be created first
var pipelineStack = new PipelineStack(app, "aws-cdk-pipeline-ecs-separate-sources");
// we supply the image to the ECS application Stack from the CodePipeline Stack
// we supply the image to the ECS application Stack from the CodePipeline Stack
new EcsAppStack(app, "EcsStackDeployedInPipeline", new EcsAppStackProps {
    Image = pipelineStack.TagParameterContainerImage
});
go
/**
 * These are the construction properties for `EcsAppStack`.
 * They extend the standard Stack properties,
 * but also require providing the ContainerImage that the service will use.
 * That Image will be provided from the Stack containing the CodePipeline.
 */
type EcsAppStackProps struct {
	StackProps
	image ContainerImage
}

/**
 * This is the Stack containing a simple ECS Service that uses the provided ContainerImage.
 */
type EcsAppStack struct {
	Stack
}

func NewEcsAppStack(scope Construct, id *string, props EcsAppStackProps) *EcsAppStack {
	this := &EcsAppStack{}
	cdk.NewStack_Override(this, scope, id, props)

	taskDefinition := ecs.NewTaskDefinition(this, jsii.String("TaskDefinition"), &TaskDefinitionProps{
		Compatibility: ecs.Compatibility_FARGATE,
		Cpu: jsii.String("1024"),
		MemoryMiB: jsii.String("2048"),
	})
	taskDefinition.AddContainer(jsii.String("AppContainer"), &ContainerDefinitionOptions{
		Image: props.image,
	})
	ecs.NewFargateService(this, jsii.String("EcsService"), &FargateServiceProps{
		TaskDefinition: TaskDefinition,
		Cluster: ecs.NewCluster(this, jsii.String("Cluster"), &ClusterProps{
			Vpc: ec2.NewVpc(this, jsii.String("Vpc"), &VpcProps{
				MaxAzs: jsii.Number(1),
			}),
		}),
	})
	return this
}

/**
 * This is the Stack containing the CodePipeline definition that deploys an ECS Service.
 */
type PipelineStack struct {
	Stack
	tagParameterContainerImage TagParameterContainerImage
}tagParameterContainerImage TagParameterContainerImage

func NewPipelineStack(scope Construct, id *string, props StackProps) *PipelineStack {
	this := &PipelineStack{}
	cdk.NewStack_Override(this, scope, id, props)

	/* ********** ECS part **************** */

	// this is the ECR repository where the built Docker image will be pushed
	appEcrRepo := ecr.NewRepository(this, jsii.String("EcsDeployRepository"))
	// the build that creates the Docker image, and pushes it to the ECR repo
	appCodeDockerBuild := codebuild.NewPipelineProject(this, jsii.String("AppCodeDockerImageBuildAndPushProject"), &PipelineProjectProps{
		Environment: &BuildEnvironment{
			// we need to run Docker
			Privileged: jsii.Boolean(true),
		},
		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 ecr get-login --region $AWS_DEFAULT_REGION --no-include-email)"),
						jsii.String("docker build -t $REPOSITORY_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION ."),
					},
				},
				"post_build": map[string][]*string{
					"commands": []*string{
						jsii.String("docker push $REPOSITORY_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION"),
						jsii.String("export imageTag=$CODEBUILD_RESOLVED_SOURCE_VERSION"),
					},
				},
			},
			"env": map[string][]*string{
				// save the imageTag environment variable as a CodePipeline Variable
				"exported-variables": []*string{
					jsii.String("imageTag"),
				},
			},
		}),
		EnvironmentVariables: map[string]BuildEnvironmentVariable{
			"REPOSITORY_URI": &BuildEnvironmentVariable{
				"value": appEcrRepo.repositoryUri,
			},
		},
	})
	// needed for `docker push`
	appEcrRepo.GrantPullPush(appCodeDockerBuild)
	// create the ContainerImage used for the ECS application Stack
	this.tagParameterContainerImage = ecs.NewTagParameterContainerImage(appEcrRepo)

	cdkCodeBuild := codebuild.NewPipelineProject(this, jsii.String("CdkCodeBuildProject"), &PipelineProjectProps{
		BuildSpec: codebuild.BuildSpec_*FromObject(map[string]interface{}{
			"version": jsii.String("0.2"),
			"phases": map[string]map[string][]*string{
				"install": map[string][]*string{
					"commands": []*string{
						jsii.String("npm install"),
					},
				},
				"build": map[string][]*string{
					"commands": []*string{
						jsii.String("npx cdk synth --verbose"),
					},
				},
			},
			"artifacts": map[string]*string{
				// store the entire Cloud Assembly as the output artifact
				"base-directory": jsii.String("cdk.out"),
				"files": jsii.String("**/*"),
			},
		}),
	})

	/* ********** Pipeline part **************** */

	appCodeSourceOutput := codepipeline.NewArtifact()
	cdkCodeSourceOutput := codepipeline.NewArtifact()
	cdkCodeBuildOutput := codepipeline.NewArtifact()
	appCodeBuildAction := codepipeline_actions.NewCodeBuildAction(&CodeBuildActionProps{
		ActionName: jsii.String("AppCodeDockerImageBuildAndPush"),
		Project: appCodeDockerBuild,
		Input: appCodeSourceOutput,
	})
	codepipeline.NewPipeline(this, jsii.String("CodePipelineDeployingEcsApplication"), &PipelineProps{
		ArtifactBucket: s3.NewBucket(this, jsii.String("ArtifactBucket"), &BucketProps{
			RemovalPolicy: cdk.RemovalPolicy_DESTROY,
		}),
		Stages: []StageProps{
			&StageProps{
				StageName: jsii.String("Source"),
				Actions: []IAction{
					// this is the Action that takes the source of your application code
					codepipeline_actions.NewCodeCommitSourceAction(&CodeCommitSourceActionProps{
						ActionName: jsii.String("AppCodeSource"),
						Repository: codecommit.NewRepository(this, jsii.String("AppCodeSourceRepository"), &RepositoryProps{
							RepositoryName: jsii.String("AppCodeSourceRepository"),
						}),
						Output: appCodeSourceOutput,
					}),
					// this is the Action that takes the source of your CDK code
					// (which would probably include this Pipeline code as well)
					codepipeline_actions.NewCodeCommitSourceAction(&CodeCommitSourceActionProps{
						ActionName: jsii.String("CdkCodeSource"),
						Repository: codecommit.NewRepository(this, jsii.String("CdkCodeSourceRepository"), &RepositoryProps{
							RepositoryName: jsii.String("CdkCodeSourceRepository"),
						}),
						Output: cdkCodeSourceOutput,
					}),
				},
			},
			&StageProps{
				StageName: jsii.String("Build"),
				Actions: []IAction{
					appCodeBuildAction,
					codepipeline_actions.NewCodeBuildAction(&CodeBuildActionProps{
						ActionName: jsii.String("CdkCodeBuildAndSynth"),
						Project: cdkCodeBuild,
						Input: cdkCodeSourceOutput,
						Outputs: []Artifact{
							cdkCodeBuildOutput,
						},
					}),
				},
			},
			&StageProps{
				StageName: jsii.String("Deploy"),
				Actions: []IAction{
					codepipeline_actions.NewCloudFormationCreateUpdateStackAction(&CloudFormationCreateUpdateStackActionProps{
						ActionName: jsii.String("CFN_Deploy"),
						StackName: jsii.String("SampleEcsStackDeployedFromCodePipeline"),
						// this name has to be the same name as used below in the CDK code for the application Stack
						TemplatePath: cdkCodeBuildOutput.AtPath(jsii.String("EcsStackDeployedInPipeline.template.json")),
						AdminPermissions: jsii.Boolean(true),
						ParameterOverrides: map[string]interface{}{
							// read the tag pushed to the ECR repository from the CodePipeline Variable saved by the application build step,
							// and pass it as the CloudFormation Parameter for the tag
							this.tagParameterContainerImage.tagParameterName: appCodeBuildAction.variable(jsii.String("imageTag")),
						},
					}),
				},
			},
		},
	})
	return this
}

app := cdk.NewApp()

// the CodePipeline Stack needs to be created first
pipelineStack := NewPipelineStack(app, jsii.String("aws-cdk-pipeline-ecs-separate-sources"))
// we supply the image to the ECS application Stack from the CodePipeline Stack
// we supply the image to the ECS application Stack from the CodePipeline Stack
NewEcsAppStack(app, jsii.String("EcsStackDeployedInPipeline"), &EcsAppStackProps{
	image: pipelineStack.tagParameterContainerImage,
})

Amazon EC2 ​

To deploy application code to Amazon EC2 Linux instances or Linux SSM-managed nodes:

Note This action is only supported for V2 type pipelines.

ts
const sourceOutput = new codepipeline.Artifact();

const pipeline = new codepipeline.Pipeline(this, 'MyPipeline', {
  pipelineType: codepipeline.PipelineType.V2,
});
const deployAction = new codepipeline_actions.Ec2DeployAction({
  actionName: 'Ec2Deploy',
  input: sourceOutput,
  instanceType: codepipeline_actions.Ec2InstanceType.EC2,
  instanceTagKey: 'Name',
  instanceTagValue: 'MyInstance',
  deploySpecifications: codepipeline_actions.Ec2DeploySpecifications.inline({
    targetDirectory: '/home/ec2-user/deploy',
    preScript: 'scripts/pre-deploy.sh',
    postScript: 'scripts/post-deploy.sh',
  }),
});
const deployStage = pipeline.addStage({
  stageName: 'Deploy',
  actions: [deployAction],
});
python
source_output = codepipeline.Artifact()

pipeline = codepipeline.Pipeline(self, "MyPipeline",
    pipeline_type=codepipeline.PipelineType.V2
)
deploy_action = codepipeline_actions.Ec2DeployAction(
    action_name="Ec2Deploy",
    input=source_output,
    instance_type=codepipeline_actions.Ec2InstanceType.EC2,
    instance_tag_key="Name",
    instance_tag_value="MyInstance",
    deploy_specifications=codepipeline_actions.Ec2DeploySpecifications.inline(
        target_directory="/home/ec2-user/deploy",
        pre_script="scripts/pre-deploy.sh",
        post_script="scripts/post-deploy.sh"
    )
)
deploy_stage = pipeline.add_stage(
    stage_name="Deploy",
    actions=[deploy_action]
)
java
Artifact sourceOutput = new Artifact();

Pipeline pipeline = Pipeline.Builder.create(this, "MyPipeline")
        .pipelineType(PipelineType.V2)
        .build();
Ec2DeployAction deployAction = Ec2DeployAction.Builder.create()
        .actionName("Ec2Deploy")
        .input(sourceOutput)
        .instanceType(Ec2InstanceType.EC2)
        .instanceTagKey("Name")
        .instanceTagValue("MyInstance")
        .deploySpecifications(Ec2DeploySpecifications.inline(Ec2DeploySpecificationsInlineProps.builder()
                .targetDirectory("/home/ec2-user/deploy")
                .preScript("scripts/pre-deploy.sh")
                .postScript("scripts/post-deploy.sh")
                .build()))
        .build();
IStage deployStage = pipeline.addStage(StageOptions.builder()
        .stageName("Deploy")
        .actions(List.of(deployAction))
        .build());
csharp
var sourceOutput = new Artifact();

var pipeline = new Pipeline(this, "MyPipeline", new PipelineProps {
    PipelineType = PipelineType.V2
});
var deployAction = new Ec2DeployAction(new Ec2DeployActionProps {
    ActionName = "Ec2Deploy",
    Input = sourceOutput,
    InstanceType = Ec2InstanceType.EC2,
    InstanceTagKey = "Name",
    InstanceTagValue = "MyInstance",
    DeploySpecifications = Ec2DeploySpecifications.Inline(new Ec2DeploySpecificationsInlineProps {
        TargetDirectory = "/home/ec2-user/deploy",
        PreScript = "scripts/pre-deploy.sh",
        PostScript = "scripts/post-deploy.sh"
    })
});
var deployStage = pipeline.AddStage(new StageOptions {
    StageName = "Deploy",
    Actions = new [] { deployAction }
});
go
sourceOutput := codepipeline.NewArtifact()

pipeline := codepipeline.NewPipeline(this, jsii.String("MyPipeline"), &PipelineProps{
	PipelineType: codepipeline.PipelineType_V2,
})
deployAction := codepipeline_actions.NewEc2DeployAction(&Ec2DeployActionProps{
	ActionName: jsii.String("Ec2Deploy"),
	Input: sourceOutput,
	InstanceType: codepipeline_actions.Ec2InstanceType_EC2,
	InstanceTagKey: jsii.String("Name"),
	InstanceTagValue: jsii.String("MyInstance"),
	DeploySpecifications: codepipeline_actions.Ec2DeploySpecifications_Inline(&Ec2DeploySpecificationsInlineProps{
		TargetDirectory: jsii.String("/home/ec2-user/deploy"),
		PreScript: jsii.String("scripts/pre-deploy.sh"),
		PostScript: jsii.String("scripts/post-deploy.sh"),
	}),
})
deployStage := pipeline.AddStage(&StageOptions{
	StageName: jsii.String("Deploy"),
	Actions: []IAction{
		deployAction,
	},
})

To learn more about using the EC2 deploy action in your pipeline, visit tutorial and documentation.

AWS S3 Deployment ​

To use an S3 Bucket as a deployment target in CodePipeline:

ts
import * as kms from 'aws-cdk-lib/aws-kms';

const sourceOutput = new codepipeline.Artifact();
const targetBucket = new s3.Bucket(this, 'MyBucket');
const key: kms.IKey = new kms.Key(this, 'EnvVarEncryptKey', {
  description: 'sample key',
});

const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const deployAction = new codepipeline_actions.S3DeployAction({
  actionName: 'S3Deploy',
  bucket: targetBucket,
  input: sourceOutput,
  encryptionKey: key,
});
const deployStage = pipeline.addStage({
  stageName: 'Deploy',
  actions: [deployAction],
});
python
import aws_cdk.aws_kms as kms


source_output = codepipeline.Artifact()
target_bucket = s3.Bucket(self, "MyBucket")
key = kms.Key(self, "EnvVarEncryptKey",
    description="sample key"
)

pipeline = codepipeline.Pipeline(self, "MyPipeline")
deploy_action = codepipeline_actions.S3DeployAction(
    action_name="S3Deploy",
    bucket=target_bucket,
    input=source_output,
    encryption_key=key
)
deploy_stage = pipeline.add_stage(
    stage_name="Deploy",
    actions=[deploy_action]
)
java
import software.amazon.awscdk.services.kms.*;


Artifact sourceOutput = new Artifact();
Bucket targetBucket = new Bucket(this, "MyBucket");
IKey key = Key.Builder.create(this, "EnvVarEncryptKey")
        .description("sample key")
        .build();

Pipeline pipeline = new Pipeline(this, "MyPipeline");
S3DeployAction deployAction = S3DeployAction.Builder.create()
        .actionName("S3Deploy")
        .bucket(targetBucket)
        .input(sourceOutput)
        .encryptionKey(key)
        .build();
IStage deployStage = pipeline.addStage(StageOptions.builder()
        .stageName("Deploy")
        .actions(List.of(deployAction))
        .build());
csharp
using Amazon.CDK.AWS.KMS;


var sourceOutput = new Artifact();
var targetBucket = new Bucket(this, "MyBucket");
var key = new Key(this, "EnvVarEncryptKey", new KeyProps {
    Description = "sample key"
});

var pipeline = new Pipeline(this, "MyPipeline");
var deployAction = new S3DeployAction(new S3DeployActionProps {
    ActionName = "S3Deploy",
    Bucket = targetBucket,
    Input = sourceOutput,
    EncryptionKey = key
});
var deployStage = pipeline.AddStage(new StageOptions {
    StageName = "Deploy",
    Actions = new [] { deployAction }
});
go
import kms "github.com/aws/aws-cdk-go/awscdk"


sourceOutput := codepipeline.NewArtifact()
targetBucket := s3.NewBucket(this, jsii.String("MyBucket"))
key := kms.NewKey(this, jsii.String("EnvVarEncryptKey"), &KeyProps{
	Description: jsii.String("sample key"),
})

pipeline := codepipeline.NewPipeline(this, jsii.String("MyPipeline"))
deployAction := codepipeline_actions.NewS3DeployAction(&S3DeployActionProps{
	ActionName: jsii.String("S3Deploy"),
	Bucket: targetBucket,
	Input: sourceOutput,
	EncryptionKey: key,
})
deployStage := pipeline.AddStage(&StageOptions{
	StageName: jsii.String("Deploy"),
	Actions: []IAction{
		deployAction,
	},
})

Invalidating the CloudFront cache when deploying to S3 ​

There is currently no native support in CodePipeline for invalidating a CloudFront cache after deployment. One workaround is to add another build step after the deploy step, and use the AWS CLI to invalidate the cache:

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
// 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
// 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),
				}),
			},
		},
	},
})

Elastic Beanstalk Deployment ​

To deploy an Elastic Beanstalk Application in CodePipeline:

ts
const sourceOutput = new codepipeline.Artifact();
const targetBucket = new s3.Bucket(this, 'MyBucket');

const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const deployAction = new codepipeline_actions.ElasticBeanstalkDeployAction({
  actionName: 'ElasticBeanstalkDeploy',
  input: sourceOutput,
  environmentName: 'envName',
  applicationName: 'appName',
});

const deployStage = pipeline.addStage({
  stageName: 'Deploy',
  actions: [deployAction],
});
python
source_output = codepipeline.Artifact()
target_bucket = s3.Bucket(self, "MyBucket")

pipeline = codepipeline.Pipeline(self, "MyPipeline")
deploy_action = codepipeline_actions.ElasticBeanstalkDeployAction(
    action_name="ElasticBeanstalkDeploy",
    input=source_output,
    environment_name="envName",
    application_name="appName"
)

deploy_stage = pipeline.add_stage(
    stage_name="Deploy",
    actions=[deploy_action]
)
java
Artifact sourceOutput = new Artifact();
Bucket targetBucket = new Bucket(this, "MyBucket");

Pipeline pipeline = new Pipeline(this, "MyPipeline");
ElasticBeanstalkDeployAction deployAction = ElasticBeanstalkDeployAction.Builder.create()
        .actionName("ElasticBeanstalkDeploy")
        .input(sourceOutput)
        .environmentName("envName")
        .applicationName("appName")
        .build();

IStage deployStage = pipeline.addStage(StageOptions.builder()
        .stageName("Deploy")
        .actions(List.of(deployAction))
        .build());
csharp
var sourceOutput = new Artifact();
var targetBucket = new Bucket(this, "MyBucket");

var pipeline = new Pipeline(this, "MyPipeline");
var deployAction = new ElasticBeanstalkDeployAction(new ElasticBeanstalkDeployActionProps {
    ActionName = "ElasticBeanstalkDeploy",
    Input = sourceOutput,
    EnvironmentName = "envName",
    ApplicationName = "appName"
});

var deployStage = pipeline.AddStage(new StageOptions {
    StageName = "Deploy",
    Actions = new [] { deployAction }
});
go
sourceOutput := codepipeline.NewArtifact()
targetBucket := s3.NewBucket(this, jsii.String("MyBucket"))

pipeline := codepipeline.NewPipeline(this, jsii.String("MyPipeline"))
deployAction := codepipeline_actions.NewElasticBeanstalkDeployAction(&ElasticBeanstalkDeployActionProps{
	ActionName: jsii.String("ElasticBeanstalkDeploy"),
	Input: sourceOutput,
	EnvironmentName: jsii.String("envName"),
	ApplicationName: jsii.String("appName"),
})

deployStage := pipeline.AddStage(&StageOptions{
	StageName: jsii.String("Deploy"),
	Actions: []IAction{
		deployAction,
	},
})

Alexa Skill ​

You can deploy to Alexa using CodePipeline with the following Action:

ts
// Read the secrets from ParameterStore
const clientId = SecretValue.secretsManager('AlexaClientId');
const clientSecret = SecretValue.secretsManager('AlexaClientSecret');
const refreshToken = SecretValue.secretsManager('AlexaRefreshToken');

// Add deploy action
const sourceOutput = new codepipeline.Artifact();
new codepipeline_actions.AlexaSkillDeployAction({
  actionName: 'DeploySkill',
  runOrder: 1,
  input: sourceOutput,
  clientId: clientId.toString(),
  clientSecret: clientSecret,
  refreshToken: refreshToken,
  skillId: 'amzn1.ask.skill.12345678-1234-1234-1234-123456789012',
});
python
# Read the secrets from ParameterStore
client_id = SecretValue.secrets_manager("AlexaClientId")
client_secret = SecretValue.secrets_manager("AlexaClientSecret")
refresh_token = SecretValue.secrets_manager("AlexaRefreshToken")

# Add deploy action
source_output = codepipeline.Artifact()
codepipeline_actions.AlexaSkillDeployAction(
    action_name="DeploySkill",
    run_order=1,
    input=source_output,
    client_id=client_id.to_string(),
    client_secret=client_secret,
    refresh_token=refresh_token,
    skill_id="amzn1.ask.skill.12345678-1234-1234-1234-123456789012"
)
java
// Read the secrets from ParameterStore
SecretValue clientId = SecretValue.secretsManager("AlexaClientId");
SecretValue clientSecret = SecretValue.secretsManager("AlexaClientSecret");
SecretValue refreshToken = SecretValue.secretsManager("AlexaRefreshToken");

// Add deploy action
Artifact sourceOutput = new Artifact();
AlexaSkillDeployAction.Builder.create()
        .actionName("DeploySkill")
        .runOrder(1)
        .input(sourceOutput)
        .clientId(clientId.toString())
        .clientSecret(clientSecret)
        .refreshToken(refreshToken)
        .skillId("amzn1.ask.skill.12345678-1234-1234-1234-123456789012")
        .build();
csharp
// Read the secrets from ParameterStore
var clientId = SecretValue.SecretsManager("AlexaClientId");
var clientSecret = SecretValue.SecretsManager("AlexaClientSecret");
var refreshToken = SecretValue.SecretsManager("AlexaRefreshToken");

// Add deploy action
var sourceOutput = new Artifact();
new AlexaSkillDeployAction(new AlexaSkillDeployActionProps {
    ActionName = "DeploySkill",
    RunOrder = 1,
    Input = sourceOutput,
    ClientId = clientId.ToString(),
    ClientSecret = clientSecret,
    RefreshToken = refreshToken,
    SkillId = "amzn1.ask.skill.12345678-1234-1234-1234-123456789012"
});
go
// Read the secrets from ParameterStore
clientId := awscdk.SecretValue_SecretsManager(jsii.String("AlexaClientId"))
clientSecret := awscdk.SecretValue_SecretsManager(jsii.String("AlexaClientSecret"))
refreshToken := awscdk.SecretValue_SecretsManager(jsii.String("AlexaRefreshToken"))

// Add deploy action
sourceOutput := codepipeline.NewArtifact()
codepipeline_actions.NewAlexaSkillDeployAction(&AlexaSkillDeployActionProps{
	ActionName: jsii.String("DeploySkill"),
	RunOrder: jsii.Number(1),
	Input: sourceOutput,
	ClientId: clientId.ToString(),
	ClientSecret: clientSecret,
	RefreshToken: refreshToken,
	SkillId: jsii.String("amzn1.ask.skill.12345678-1234-1234-1234-123456789012"),
})

If you need manifest overrides you can specify them as parameterOverridesArtifact in the action:

ts
// Deploy some CFN change set and store output
const executeOutput = new codepipeline.Artifact('CloudFormation');
const executeChangeSetAction = new codepipeline_actions.CloudFormationExecuteChangeSetAction({
  actionName: 'ExecuteChangesTest',
  runOrder: 2,
  stackName: 'MyStack',
  changeSetName: 'MyChangeSet',
  outputFileName: 'overrides.json',
  output: executeOutput,
});

// Provide CFN output as manifest overrides
const clientId = SecretValue.secretsManager('AlexaClientId');
const clientSecret = SecretValue.secretsManager('AlexaClientSecret');
const refreshToken = SecretValue.secretsManager('AlexaRefreshToken');
const sourceOutput = new codepipeline.Artifact();
new codepipeline_actions.AlexaSkillDeployAction({
  actionName: 'DeploySkill',
  runOrder: 1,
  input: sourceOutput,
  parameterOverridesArtifact: executeOutput,
  clientId: clientId.toString(),
  clientSecret: clientSecret,
  refreshToken: refreshToken,
  skillId: 'amzn1.ask.skill.12345678-1234-1234-1234-123456789012',
});
python
# Deploy some CFN change set and store output
execute_output = codepipeline.Artifact("CloudFormation")
execute_change_set_action = codepipeline_actions.CloudFormationExecuteChangeSetAction(
    action_name="ExecuteChangesTest",
    run_order=2,
    stack_name="MyStack",
    change_set_name="MyChangeSet",
    output_file_name="overrides.json",
    output=execute_output
)

# Provide CFN output as manifest overrides
client_id = SecretValue.secrets_manager("AlexaClientId")
client_secret = SecretValue.secrets_manager("AlexaClientSecret")
refresh_token = SecretValue.secrets_manager("AlexaRefreshToken")
source_output = codepipeline.Artifact()
codepipeline_actions.AlexaSkillDeployAction(
    action_name="DeploySkill",
    run_order=1,
    input=source_output,
    parameter_overrides_artifact=execute_output,
    client_id=client_id.to_string(),
    client_secret=client_secret,
    refresh_token=refresh_token,
    skill_id="amzn1.ask.skill.12345678-1234-1234-1234-123456789012"
)
java
// Deploy some CFN change set and store output
Artifact executeOutput = new Artifact("CloudFormation");
CloudFormationExecuteChangeSetAction executeChangeSetAction = CloudFormationExecuteChangeSetAction.Builder.create()
        .actionName("ExecuteChangesTest")
        .runOrder(2)
        .stackName("MyStack")
        .changeSetName("MyChangeSet")
        .outputFileName("overrides.json")
        .output(executeOutput)
        .build();

// Provide CFN output as manifest overrides
SecretValue clientId = SecretValue.secretsManager("AlexaClientId");
SecretValue clientSecret = SecretValue.secretsManager("AlexaClientSecret");
SecretValue refreshToken = SecretValue.secretsManager("AlexaRefreshToken");
Artifact sourceOutput = new Artifact();
AlexaSkillDeployAction.Builder.create()
        .actionName("DeploySkill")
        .runOrder(1)
        .input(sourceOutput)
        .parameterOverridesArtifact(executeOutput)
        .clientId(clientId.toString())
        .clientSecret(clientSecret)
        .refreshToken(refreshToken)
        .skillId("amzn1.ask.skill.12345678-1234-1234-1234-123456789012")
        .build();
csharp
// Deploy some CFN change set and store output
var executeOutput = new Artifact("CloudFormation");
var executeChangeSetAction = new CloudFormationExecuteChangeSetAction(new CloudFormationExecuteChangeSetActionProps {
    ActionName = "ExecuteChangesTest",
    RunOrder = 2,
    StackName = "MyStack",
    ChangeSetName = "MyChangeSet",
    OutputFileName = "overrides.json",
    Output = executeOutput
});

// Provide CFN output as manifest overrides
var clientId = SecretValue.SecretsManager("AlexaClientId");
var clientSecret = SecretValue.SecretsManager("AlexaClientSecret");
var refreshToken = SecretValue.SecretsManager("AlexaRefreshToken");
var sourceOutput = new Artifact();
new AlexaSkillDeployAction(new AlexaSkillDeployActionProps {
    ActionName = "DeploySkill",
    RunOrder = 1,
    Input = sourceOutput,
    ParameterOverridesArtifact = executeOutput,
    ClientId = clientId.ToString(),
    ClientSecret = clientSecret,
    RefreshToken = refreshToken,
    SkillId = "amzn1.ask.skill.12345678-1234-1234-1234-123456789012"
});
go
// Deploy some CFN change set and store output
executeOutput := codepipeline.NewArtifact(jsii.String("CloudFormation"))
executeChangeSetAction := codepipeline_actions.NewCloudFormationExecuteChangeSetAction(&CloudFormationExecuteChangeSetActionProps{
	ActionName: jsii.String("ExecuteChangesTest"),
	RunOrder: jsii.Number(2),
	StackName: jsii.String("MyStack"),
	ChangeSetName: jsii.String("MyChangeSet"),
	OutputFileName: jsii.String("overrides.json"),
	Output: executeOutput,
})

// Provide CFN output as manifest overrides
clientId := awscdk.SecretValue_SecretsManager(jsii.String("AlexaClientId"))
clientSecret := awscdk.SecretValue_SecretsManager(jsii.String("AlexaClientSecret"))
refreshToken := awscdk.SecretValue_SecretsManager(jsii.String("AlexaRefreshToken"))
sourceOutput := codepipeline.NewArtifact()
codepipeline_actions.NewAlexaSkillDeployAction(&AlexaSkillDeployActionProps{
	ActionName: jsii.String("DeploySkill"),
	RunOrder: jsii.Number(1),
	Input: sourceOutput,
	ParameterOverridesArtifact: executeOutput,
	ClientId: clientId.ToString(),
	ClientSecret: clientSecret,
	RefreshToken: refreshToken,
	SkillId: jsii.String("amzn1.ask.skill.12345678-1234-1234-1234-123456789012"),
})

AWS Service Catalog ​

You can deploy a CloudFormation template to an existing Service Catalog product with the following Action:

ts
const cdkBuildOutput = new codepipeline.Artifact();
const serviceCatalogDeployAction = new codepipeline_actions.ServiceCatalogDeployActionBeta1({
  actionName: 'ServiceCatalogDeploy',
  templatePath: cdkBuildOutput.atPath("Sample.template.json"),
  productVersionName: "Version - " + Date.now.toString,
  productVersionDescription: "This is a version from the pipeline with a new description.",
  productId: "prod-XXXXXXXX",
});
python
cdk_build_output = codepipeline.Artifact()
service_catalog_deploy_action = codepipeline_actions.ServiceCatalogDeployActionBeta1(
    action_name="ServiceCatalogDeploy",
    template_path=cdk_build_output.at_path("Sample.template.json"),
    product_version_name="Version - " + Date.now.to_string,
    product_version_description="This is a version from the pipeline with a new description.",
    product_id="prod-XXXXXXXX"
)
java
Artifact cdkBuildOutput = new Artifact();
ServiceCatalogDeployActionBeta1 serviceCatalogDeployAction = ServiceCatalogDeployActionBeta1.Builder.create()
        .actionName("ServiceCatalogDeploy")
        .templatePath(cdkBuildOutput.atPath("Sample.template.json"))
        .productVersionName("Version - " + Date.getNow().getToString())
        .productVersionDescription("This is a version from the pipeline with a new description.")
        .productId("prod-XXXXXXXX")
        .build();
csharp
var cdkBuildOutput = new Artifact();
var serviceCatalogDeployAction = new ServiceCatalogDeployActionBeta1(new ServiceCatalogDeployActionBeta1Props {
    ActionName = "ServiceCatalogDeploy",
    TemplatePath = cdkBuildOutput.AtPath("Sample.template.json"),
    ProductVersionName = "Version - " + Date.Now.ToString,
    ProductVersionDescription = "This is a version from the pipeline with a new description.",
    ProductId = "prod-XXXXXXXX"
});
go
cdkBuildOutput := codepipeline.NewArtifact()
serviceCatalogDeployAction := codepipeline_actions.NewServiceCatalogDeployActionBeta1(&ServiceCatalogDeployActionBeta1Props{
	ActionName: jsii.String("ServiceCatalogDeploy"),
	TemplatePath: cdkBuildOutput.AtPath(jsii.String("Sample.template.json")),
	ProductVersionName: jsii.String("Version - " + date.now.toString),
	ProductVersionDescription: jsii.String("This is a version from the pipeline with a new description."),
	ProductId: jsii.String("prod-XXXXXXXX"),
})

Approve & invoke ​

Manual approval Action ​

This package contains an Action that stops the Pipeline until someone manually clicks the approve button:

ts
import * as sns from 'aws-cdk-lib/aws-sns';

const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const approveStage = pipeline.addStage({ stageName: 'Approve' });
const manualApprovalAction = new codepipeline_actions.ManualApprovalAction({
  actionName: 'Approve',
  notificationTopic: new sns.Topic(this, 'Topic'), // optional
  notifyEmails: [
    'some_email@example.com',
  ], // optional
  additionalInformation: 'additional info', // optional
  timeout: Duration.minutes(10), // optional
});
approveStage.addAction(manualApprovalAction);
// `manualApprovalAction.notificationTopic` can be used to access the Topic
// after the Action has been added to a Pipeline
python
import aws_cdk.aws_sns as sns


pipeline = codepipeline.Pipeline(self, "MyPipeline")
approve_stage = pipeline.add_stage(stage_name="Approve")
manual_approval_action = codepipeline_actions.ManualApprovalAction(
    action_name="Approve",
    notification_topic=sns.Topic(self, "Topic"),  # optional
    notify_emails=["some_email@example.com"
    ],  # optional
    additional_information="additional info",  # optional
    timeout=Duration.minutes(10)
)
approve_stage.add_action(manual_approval_action)
java
import software.amazon.awscdk.services.sns.*;


Pipeline pipeline = new Pipeline(this, "MyPipeline");
IStage approveStage = pipeline.addStage(StageOptions.builder().stageName("Approve").build());
ManualApprovalAction manualApprovalAction = ManualApprovalAction.Builder.create()
        .actionName("Approve")
        .notificationTopic(new Topic(this, "Topic")) // optional
        .notifyEmails(List.of("some_email@example.com")) // optional
        .additionalInformation("additional info") // optional
        .timeout(Duration.minutes(10))
        .build();
approveStage.addAction(manualApprovalAction);
csharp
using Amazon.CDK.AWS.SNS;


var pipeline = new Pipeline(this, "MyPipeline");
var approveStage = pipeline.AddStage(new StageOptions { StageName = "Approve" });
var manualApprovalAction = new ManualApprovalAction(new ManualApprovalActionProps {
    ActionName = "Approve",
    NotificationTopic = new Topic(this, "Topic"),  // optional
    NotifyEmails = new [] { "some_email@example.com" },  // optional
    AdditionalInformation = "additional info",  // optional
    Timeout = Duration.Minutes(10)
});
approveStage.AddAction(manualApprovalAction);
go
import sns "github.com/aws/aws-cdk-go/awscdk"


pipeline := codepipeline.NewPipeline(this, jsii.String("MyPipeline"))
approveStage := pipeline.AddStage(&StageOptions{
	StageName: jsii.String("Approve"),
})
manualApprovalAction := codepipeline_actions.NewManualApprovalAction(&ManualApprovalActionProps{
	ActionName: jsii.String("Approve"),
	NotificationTopic: sns.NewTopic(this, jsii.String("Topic")),
	 // optional
	NotifyEmails: []*string{
		jsii.String("some_email@example.com"),
	},
	 // optional
	AdditionalInformation: jsii.String("additional info"),
	 // optional
	Timeout: awscdk.Duration_Minutes(jsii.Number(10)),
})
approveStage.AddAction(manualApprovalAction)

If the notificationTopic has not been provided, but notifyEmails were, a new SNS Topic will be created (and accessible through the notificationTopic property of the Action).

If you want to grant a principal permissions to approve the changes, you can invoke the method grantManualApproval passing it a IGrantable:

ts
const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const approveStage = pipeline.addStage({ stageName: 'Approve' });
const manualApprovalAction = new codepipeline_actions.ManualApprovalAction({
  actionName: 'Approve',
});
approveStage.addAction(manualApprovalAction);

const role = iam.Role.fromRoleArn(this, 'Admin', Arn.format({ service: 'iam', resource: 'role', resourceName: 'Admin' }, this));
manualApprovalAction.grantManualApproval(role);
python
from aws_cdk import ArnComponents
pipeline = codepipeline.Pipeline(self, "MyPipeline")
approve_stage = pipeline.add_stage(stage_name="Approve")
manual_approval_action = codepipeline_actions.ManualApprovalAction(
    action_name="Approve"
)
approve_stage.add_action(manual_approval_action)

role = iam.Role.from_role_arn(self, "Admin", Arn.format(ArnComponents(service="iam", resource="role", resource_name="Admin"), self))
manual_approval_action.grant_manual_approval(role)
java
Pipeline pipeline = new Pipeline(this, "MyPipeline");
IStage approveStage = pipeline.addStage(StageOptions.builder().stageName("Approve").build());
ManualApprovalAction manualApprovalAction = ManualApprovalAction.Builder.create()
        .actionName("Approve")
        .build();
approveStage.addAction(manualApprovalAction);

IRole role = Role.fromRoleArn(this, "Admin", Arn.format(ArnComponents.builder().service("iam").resource("role").resourceName("Admin").build(), this));
manualApprovalAction.grantManualApproval(role);
csharp
var pipeline = new Pipeline(this, "MyPipeline");
var approveStage = pipeline.AddStage(new StageOptions { StageName = "Approve" });
var manualApprovalAction = new ManualApprovalAction(new ManualApprovalActionProps {
    ActionName = "Approve"
});
approveStage.AddAction(manualApprovalAction);

var role = Role.FromRoleArn(this, "Admin", Arn.Format(new ArnComponents { Service = "iam", Resource = "role", ResourceName = "Admin" }, this));
manualApprovalAction.GrantManualApproval(role);
go
pipeline := codepipeline.NewPipeline(this, jsii.String("MyPipeline"))
approveStage := pipeline.AddStage(&StageOptions{
	StageName: jsii.String("Approve"),
})
manualApprovalAction := codepipeline_actions.NewManualApprovalAction(&ManualApprovalActionProps{
	ActionName: jsii.String("Approve"),
})
approveStage.AddAction(manualApprovalAction)

role := iam.Role_FromRoleArn(this, jsii.String("Admin"), awscdk.Arn_Format(&ArnComponents{
	Service: jsii.String("iam"),
	Resource: jsii.String("role"),
	ResourceName: jsii.String("Admin"),
}, this))
manualApprovalAction.GrantManualApproval(role)

AWS Lambda ​

This module contains an Action that allows you to invoke a Lambda function in a Pipeline:

ts
declare const fn: lambda.Function;
const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const lambdaAction = new codepipeline_actions.LambdaInvokeAction({
  actionName: 'Lambda',
  lambda: fn,
});
pipeline.addStage({
  stageName: 'Lambda',
  actions: [lambdaAction],
});
python
# fn: lambda.Function

pipeline = codepipeline.Pipeline(self, "MyPipeline")
lambda_action = codepipeline_actions.LambdaInvokeAction(
    action_name="Lambda",
    lambda_=fn
)
pipeline.add_stage(
    stage_name="Lambda",
    actions=[lambda_action]
)
java
Function fn;

Pipeline pipeline = new Pipeline(this, "MyPipeline");
LambdaInvokeAction lambdaAction = LambdaInvokeAction.Builder.create()
        .actionName("Lambda")
        .lambda(fn)
        .build();
pipeline.addStage(StageOptions.builder()
        .stageName("Lambda")
        .actions(List.of(lambdaAction))
        .build());
csharp
Function fn;

var pipeline = new Pipeline(this, "MyPipeline");
var lambdaAction = new LambdaInvokeAction(new LambdaInvokeActionProps {
    ActionName = "Lambda",
    Lambda = fn
});
pipeline.AddStage(new StageOptions {
    StageName = "Lambda",
    Actions = new [] { lambdaAction }
});
go
var fn Function

pipeline := codepipeline.NewPipeline(this, jsii.String("MyPipeline"))
lambdaAction := codepipeline_actions.NewLambdaInvokeAction(&LambdaInvokeActionProps{
	ActionName: jsii.String("Lambda"),
	Lambda: fn,
})
pipeline.AddStage(&StageOptions{
	StageName: jsii.String("Lambda"),
	Actions: []IAction{
		lambdaAction,
	},
})

The Lambda Action can have up to 5 inputs, and up to 5 outputs:

ts
declare const fn: lambda.Function;
const sourceOutput = new codepipeline.Artifact();
const buildOutput = new codepipeline.Artifact();
const lambdaAction = new codepipeline_actions.LambdaInvokeAction({
  actionName: 'Lambda',
  inputs: [
    sourceOutput,
    buildOutput,
  ],
  outputs: [
    new codepipeline.Artifact('Out1'),
    new codepipeline.Artifact('Out2'),
  ],
  lambda: fn,
});
python
# fn: lambda.Function

source_output = codepipeline.Artifact()
build_output = codepipeline.Artifact()
lambda_action = codepipeline_actions.LambdaInvokeAction(
    action_name="Lambda",
    inputs=[source_output, build_output
    ],
    outputs=[
        codepipeline.Artifact("Out1"),
        codepipeline.Artifact("Out2")
    ],
    lambda_=fn
)
java
Function fn;

Artifact sourceOutput = new Artifact();
Artifact buildOutput = new Artifact();
LambdaInvokeAction lambdaAction = LambdaInvokeAction.Builder.create()
        .actionName("Lambda")
        .inputs(List.of(sourceOutput, buildOutput))
        .outputs(List.of(
            new Artifact("Out1"),
            new Artifact("Out2")))
        .lambda(fn)
        .build();
csharp
Function fn;

var sourceOutput = new Artifact();
var buildOutput = new Artifact();
var lambdaAction = new LambdaInvokeAction(new LambdaInvokeActionProps {
    ActionName = "Lambda",
    Inputs = new [] { sourceOutput, buildOutput },
    Outputs = new [] {
        new Artifact("Out1"),
        new Artifact("Out2") },
    Lambda = fn
});
go
var fn Function

sourceOutput := codepipeline.NewArtifact()
buildOutput := codepipeline.NewArtifact()
lambdaAction := codepipeline_actions.NewLambdaInvokeAction(&LambdaInvokeActionProps{
	ActionName: jsii.String("Lambda"),
	Inputs: []Artifact{
		sourceOutput,
		buildOutput,
	},
	Outputs: []Artifact{
		codepipeline.NewArtifact(jsii.String("Out1")),
		codepipeline.NewArtifact(jsii.String("Out2")),
	},
	Lambda: fn,
})

The Lambda Action supports custom user parameters that pipeline will pass to the Lambda function:

ts
declare const fn: lambda.Function;

const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const lambdaAction = new codepipeline_actions.LambdaInvokeAction({
  actionName: 'Lambda',
  lambda: fn,
  userParameters: {
    foo: 'bar',
    baz: 'qux',
  },
  // OR
  userParametersString: 'my-parameter-string',
});
python
# fn: lambda.Function


pipeline = codepipeline.Pipeline(self, "MyPipeline")
lambda_action = codepipeline_actions.LambdaInvokeAction(
    action_name="Lambda",
    lambda_=fn,
    user_parameters={
        "foo": "bar",
        "baz": "qux"
    },
    # OR
    user_parameters_string="my-parameter-string"
)
java
Function fn;


Pipeline pipeline = new Pipeline(this, "MyPipeline");
LambdaInvokeAction lambdaAction = LambdaInvokeAction.Builder.create()
        .actionName("Lambda")
        .lambda(fn)
        .userParameters(Map.of(
                "foo", "bar",
                "baz", "qux"))
        // OR
        .userParametersString("my-parameter-string")
        .build();
csharp
Function fn;


var pipeline = new Pipeline(this, "MyPipeline");
var lambdaAction = new LambdaInvokeAction(new LambdaInvokeActionProps {
    ActionName = "Lambda",
    Lambda = fn,
    UserParameters = new Dictionary<string, object> {
        { "foo", "bar" },
        { "baz", "qux" }
    },
    // OR
    UserParametersString = "my-parameter-string"
});
go
var fn Function


pipeline := codepipeline.NewPipeline(this, jsii.String("MyPipeline"))
lambdaAction := codepipeline_actions.NewLambdaInvokeAction(&LambdaInvokeActionProps{
	ActionName: jsii.String("Lambda"),
	Lambda: fn,
	UserParameters: map[string]interface{}{
		"foo": jsii.String("bar"),
		"baz": jsii.String("qux"),
	},
	// OR
	UserParametersString: jsii.String("my-parameter-string"),
})

The Lambda invoke action emits variables. Unlike many other actions, the variables are not static, but dynamic, defined by the function calling the PutJobSuccessResult API with the outputVariables property filled with the map of variables Example:

ts
const lambdaInvokeAction = new codepipeline_actions.LambdaInvokeAction({
  actionName: 'Lambda',
  lambda: new lambda.Function(this, 'Func', {
    runtime: lambda.Runtime.NODEJS_LATEST,
    handler: 'index.handler',
    code: lambda.Code.fromInline(`
        const { CodePipeline } = require('@aws-sdk/client-codepipeline');

        exports.handler = async function(event, context) {
            const codepipeline = new AWS.CodePipeline();
            await codepipeline.putJobSuccessResult({
                jobId: event['CodePipeline.job'].id,
                outputVariables: {
                    MY_VAR: "some value",
                },
            });
        }
    `),
  }),
  variablesNamespace: 'MyNamespace', // optional - by default, a name will be generated for you
});

// later:
declare const project: codebuild.PipelineProject;
const sourceOutput = new codepipeline.Artifact();
new codepipeline_actions.CodeBuildAction({
  actionName: 'CodeBuild',
  project,
  input: sourceOutput,
  environmentVariables: {
    MyVar: {
      value: lambdaInvokeAction.variable('MY_VAR'),
    },
  },
});
python
# later:
# project: codebuild.PipelineProject
lambda_invoke_action = codepipeline_actions.LambdaInvokeAction(
    action_name="Lambda",
    lambda_=lambda_.Function(self, "Func",
        runtime=lambda_.Runtime.NODEJS_LATEST,
        handler="index.handler",
        code=lambda_.Code.from_inline("""
                    const { CodePipeline } = require('@aws-sdk/client-codepipeline');

                    exports.handler = async function(event, context) {
                        const codepipeline = new AWS.CodePipeline();
                        await codepipeline.putJobSuccessResult({
                            jobId: event['CodePipeline.job'].id,
                            outputVariables: {
                                MY_VAR: "some value",
                            },
                        });
                    }
                """)
    ),
    variables_namespace="MyNamespace"
)
source_output = codepipeline.Artifact()
codepipeline_actions.CodeBuildAction(
    action_name="CodeBuild",
    project=project,
    input=source_output,
    environment_variables={
        "MyVar": codebuild.BuildEnvironmentVariable(
            value=lambda_invoke_action.variable("MY_VAR")
        )
    }
)
java
// later:
PipelineProject project;
LambdaInvokeAction lambdaInvokeAction = LambdaInvokeAction.Builder.create()
        .actionName("Lambda")
        .lambda(Function.Builder.create(this, "Func")
                .runtime(Runtime.NODEJS_LATEST)
                .handler("index.handler")
                .code(Code.fromInline("\n        const { CodePipeline } = require('@aws-sdk/client-codepipeline');\n\n        exports.handler = async function(event, context) {\n            const codepipeline = new AWS.CodePipeline();\n            await codepipeline.putJobSuccessResult({\n                jobId: event['CodePipeline.job'].id,\n                outputVariables: {\n                    MY_VAR: \"some value\",\n                },\n            });\n        }\n    "))
                .build())
        .variablesNamespace("MyNamespace")
        .build();
Artifact sourceOutput = new Artifact();
CodeBuildAction.Builder.create()
        .actionName("CodeBuild")
        .project(project)
        .input(sourceOutput)
        .environmentVariables(Map.of(
                "MyVar", BuildEnvironmentVariable.builder()
                        .value(lambdaInvokeAction.variable("MY_VAR"))
                        .build()))
        .build();
csharp
// later:
PipelineProject project;
var lambdaInvokeAction = new LambdaInvokeAction(new LambdaInvokeActionProps {
    ActionName = "Lambda",
    Lambda = new Function(this, "Func", new FunctionProps {
        Runtime = Runtime.NODEJS_LATEST,
        Handler = "index.handler",
        Code = Code.FromInline(@"
                const { CodePipeline } = require('@aws-sdk/client-codepipeline');

                exports.handler = async function(event, context) {
                    const codepipeline = new AWS.CodePipeline();
                    await codepipeline.putJobSuccessResult({
                        jobId: event['CodePipeline.job'].id,
                        outputVariables: {
                            MY_VAR: ""some value"",
                        },
                    });
                }
            ")
    }),
    VariablesNamespace = "MyNamespace"
});
var sourceOutput = new Artifact();
new CodeBuildAction(new CodeBuildActionProps {
    ActionName = "CodeBuild",
    Project = project,
    Input = sourceOutput,
    EnvironmentVariables = new Dictionary<string, BuildEnvironmentVariable> {
        { "MyVar", new BuildEnvironmentVariable {
            Value = lambdaInvokeAction.Variable("MY_VAR")
        } }
    }
});
go
// later:
var project PipelineProject
lambdaInvokeAction := codepipeline_actions.NewLambdaInvokeAction(&LambdaInvokeActionProps{
	ActionName: jsii.String("Lambda"),
	Lambda: lambda.NewFunction(this, jsii.String("Func"), &FunctionProps{
		Runtime: lambda.Runtime_NODEJS_LATEST(),
		Handler: jsii.String("index.handler"),
		Code: lambda.Code_FromInline(jsii.String(`
		        const { CodePipeline } = require('@aws-sdk/client-codepipeline');

		        exports.handler = async function(event, context) {
		            const codepipeline = new AWS.CodePipeline();
		            await codepipeline.putJobSuccessResult({
		                jobId: event['CodePipeline.job'].id,
		                outputVariables: {
		                    MY_VAR: "some value",
		                },
		            });
		        }
		    `)),
	}),
	VariablesNamespace: jsii.String("MyNamespace"),
})
sourceOutput := codepipeline.NewArtifact()
codepipeline_actions.NewCodeBuildAction(&CodeBuildActionProps{
	ActionName: jsii.String("CodeBuild"),
	Project: Project,
	Input: sourceOutput,
	EnvironmentVariables: map[string]BuildEnvironmentVariable{
		"MyVar": &BuildEnvironmentVariable{
			"value": lambdaInvokeAction.variable(jsii.String("MY_VAR")),
		},
	},
})

See the AWS documentation on how to write a Lambda function invoked from CodePipeline.

AWS Step Functions ​

This module contains an Action that allows you to invoke a Step Function in a Pipeline:

ts
import * as stepfunctions from 'aws-cdk-lib/aws-stepfunctions';
const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const startState = new stepfunctions.Pass(this, 'StartState');
const simpleStateMachine  = new stepfunctions.StateMachine(this, 'SimpleStateMachine', {
  definition: startState,
});
const stepFunctionAction = new codepipeline_actions.StepFunctionInvokeAction({
  actionName: 'Invoke',
  stateMachine: simpleStateMachine,
  stateMachineInput: codepipeline_actions.StateMachineInput.literal({ IsHelloWorldExample: true }),
});
pipeline.addStage({
  stageName: 'StepFunctions',
  actions: [stepFunctionAction],
});
python
import aws_cdk.aws_stepfunctions as stepfunctions

pipeline = codepipeline.Pipeline(self, "MyPipeline")
start_state = stepfunctions.Pass(self, "StartState")
simple_state_machine = stepfunctions.StateMachine(self, "SimpleStateMachine",
    definition=start_state
)
step_function_action = codepipeline_actions.StepFunctionInvokeAction(
    action_name="Invoke",
    state_machine=simple_state_machine,
    state_machine_input=codepipeline_actions.StateMachineInput.literal({"IsHelloWorldExample": True})
)
pipeline.add_stage(
    stage_name="StepFunctions",
    actions=[step_function_action]
)
java
import software.amazon.awscdk.services.stepfunctions.*;

Pipeline pipeline = new Pipeline(this, "MyPipeline");
Pass startState = new Pass(this, "StartState");
StateMachine simpleStateMachine = StateMachine.Builder.create(this, "SimpleStateMachine")
        .definition(startState)
        .build();
StepFunctionInvokeAction stepFunctionAction = StepFunctionInvokeAction.Builder.create()
        .actionName("Invoke")
        .stateMachine(simpleStateMachine)
        .stateMachineInput(StateMachineInput.literal(Map.of("IsHelloWorldExample", true)))
        .build();
pipeline.addStage(StageOptions.builder()
        .stageName("StepFunctions")
        .actions(List.of(stepFunctionAction))
        .build());
csharp
using Amazon.CDK.AWS.StepFunctions;

var pipeline = new Pipeline(this, "MyPipeline");
var startState = new Pass(this, "StartState");
var simpleStateMachine = new StateMachine(this, "SimpleStateMachine", new StateMachineProps {
    Definition = startState
});
var stepFunctionAction = new StepFunctionInvokeAction(new StepFunctionsInvokeActionProps {
    ActionName = "Invoke",
    StateMachine = simpleStateMachine,
    StateMachineInput = StateMachineInput.Literal(new Dictionary<string, boolean> { { "IsHelloWorldExample", true } })
});
pipeline.AddStage(new StageOptions {
    StageName = "StepFunctions",
    Actions = new [] { stepFunctionAction }
});
go
import "github.com/aws/aws-cdk-go/awscdk"

pipeline := codepipeline.NewPipeline(this, jsii.String("MyPipeline"))
startState := stepfunctions.NewPass(this, jsii.String("StartState"))
simpleStateMachine := stepfunctions.NewStateMachine(this, jsii.String("SimpleStateMachine"), &StateMachineProps{
	Definition: startState,
})
stepFunctionAction := codepipeline_actions.NewStepFunctionInvokeAction(&StepFunctionsInvokeActionProps{
	ActionName: jsii.String("Invoke"),
	StateMachine: simpleStateMachine,
	StateMachineInput: codepipeline_actions.StateMachineInput_Literal(map[string]*bool{
		"IsHelloWorldExample": jsii.Boolean(true),
	}),
})
pipeline.AddStage(&StageOptions{
	StageName: jsii.String("StepFunctions"),
	Actions: []IAction{
		stepFunctionAction,
	},
})

The StateMachineInput can be created with one of 2 static factory methods: literal, which takes an arbitrary map as its only argument, or filePath:

ts
import * as stepfunctions from 'aws-cdk-lib/aws-stepfunctions';

const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const inputArtifact = new codepipeline.Artifact();
const startState = new stepfunctions.Pass(this, 'StartState');
const simpleStateMachine  = new stepfunctions.StateMachine(this, 'SimpleStateMachine', {
  definition: startState,
});
const stepFunctionAction = new codepipeline_actions.StepFunctionInvokeAction({
  actionName: 'Invoke',
  stateMachine: simpleStateMachine,
  stateMachineInput: codepipeline_actions.StateMachineInput.filePath(inputArtifact.atPath('assets/input.json')),
});
pipeline.addStage({
  stageName: 'StepFunctions',
  actions: [stepFunctionAction],
});
python
import aws_cdk.aws_stepfunctions as stepfunctions


pipeline = codepipeline.Pipeline(self, "MyPipeline")
input_artifact = codepipeline.Artifact()
start_state = stepfunctions.Pass(self, "StartState")
simple_state_machine = stepfunctions.StateMachine(self, "SimpleStateMachine",
    definition=start_state
)
step_function_action = codepipeline_actions.StepFunctionInvokeAction(
    action_name="Invoke",
    state_machine=simple_state_machine,
    state_machine_input=codepipeline_actions.StateMachineInput.file_path(input_artifact.at_path("assets/input.json"))
)
pipeline.add_stage(
    stage_name="StepFunctions",
    actions=[step_function_action]
)
java
import software.amazon.awscdk.services.stepfunctions.*;


Pipeline pipeline = new Pipeline(this, "MyPipeline");
Artifact inputArtifact = new Artifact();
Pass startState = new Pass(this, "StartState");
StateMachine simpleStateMachine = StateMachine.Builder.create(this, "SimpleStateMachine")
        .definition(startState)
        .build();
StepFunctionInvokeAction stepFunctionAction = StepFunctionInvokeAction.Builder.create()
        .actionName("Invoke")
        .stateMachine(simpleStateMachine)
        .stateMachineInput(StateMachineInput.filePath(inputArtifact.atPath("assets/input.json")))
        .build();
pipeline.addStage(StageOptions.builder()
        .stageName("StepFunctions")
        .actions(List.of(stepFunctionAction))
        .build());
csharp
using Amazon.CDK.AWS.StepFunctions;


var pipeline = new Pipeline(this, "MyPipeline");
var inputArtifact = new Artifact();
var startState = new Pass(this, "StartState");
var simpleStateMachine = new StateMachine(this, "SimpleStateMachine", new StateMachineProps {
    Definition = startState
});
var stepFunctionAction = new StepFunctionInvokeAction(new StepFunctionsInvokeActionProps {
    ActionName = "Invoke",
    StateMachine = simpleStateMachine,
    StateMachineInput = StateMachineInput.FilePath(inputArtifact.AtPath("assets/input.json"))
});
pipeline.AddStage(new StageOptions {
    StageName = "StepFunctions",
    Actions = new [] { stepFunctionAction }
});
go
import "github.com/aws/aws-cdk-go/awscdk"


pipeline := codepipeline.NewPipeline(this, jsii.String("MyPipeline"))
inputArtifact := codepipeline.NewArtifact()
startState := stepfunctions.NewPass(this, jsii.String("StartState"))
simpleStateMachine := stepfunctions.NewStateMachine(this, jsii.String("SimpleStateMachine"), &StateMachineProps{
	Definition: startState,
})
stepFunctionAction := codepipeline_actions.NewStepFunctionInvokeAction(&StepFunctionsInvokeActionProps{
	ActionName: jsii.String("Invoke"),
	StateMachine: simpleStateMachine,
	StateMachineInput: codepipeline_actions.StateMachineInput_FilePath(inputArtifact.AtPath(jsii.String("assets/input.json"))),
})
pipeline.AddStage(&StageOptions{
	StageName: jsii.String("StepFunctions"),
	Actions: []IAction{
		stepFunctionAction,
	},
})

See the AWS documentation for information on Action structure reference.

Pipeline ​

This module contains an Action that allows you to invoke another pipeline execution in a pipeline:

ts
import * as cpactions from 'aws-cdk-lib/aws-codepipeline-actions';

const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const targetPipeline = codepipeline.Pipeline.fromPipelineArn(this, 'Pipeline',
    'arn:aws:codepipeline:us-east-1:123456789012:InvokePipelineAction'); // If targetPipeline is not created by cdk, import from arn.
pipeline.addStage({
  stageName: 'stageName',
  actions: [new cpactions.PipelineInvokeAction({
  actionName: 'Invoke',
  targetPipeline,
  variables: [{
    name: 'name1',
    value: 'value1',
  }],
  sourceRevisions: [{
    actionName: 'Source',
    revisionType: cpactions.RevisionType.S3_OBJECT_VERSION_ID,
    revisionValue: 'testRevisionValue',
    }],
  })],
});
python
import aws_cdk.aws_codepipeline_actions as cpactions


pipeline = codepipeline.Pipeline(self, "MyPipeline")
target_pipeline = codepipeline.Pipeline.from_pipeline_arn(self, "Pipeline", "arn:aws:codepipeline:us-east-1:123456789012:InvokePipelineAction") # If targetPipeline is not created by cdk, import from arn.
pipeline.add_stage(
    stage_name="stageName",
    actions=[cpactions.PipelineInvokeAction(
        action_name="Invoke",
        target_pipeline=target_pipeline,
        variables=[cpactions.Variable(
            name="name1",
            value="value1"
        )],
        source_revisions=[cpactions.SourceRevision(
            action_name="Source",
            revision_type=cpactions.RevisionType.S3_OBJECT_VERSION_ID,
            revision_value="testRevisionValue"
        )]
    )]
)
java
import software.amazon.awscdk.services.codepipeline.actions.*;


Pipeline pipeline = new Pipeline(this, "MyPipeline");
IPipeline targetPipeline = Pipeline.fromPipelineArn(this, "Pipeline", "arn:aws:codepipeline:us-east-1:123456789012:InvokePipelineAction"); // If targetPipeline is not created by cdk, import from arn.
pipeline.addStage(StageOptions.builder()
        .stageName("stageName")
        .actions(List.of(PipelineInvokeAction.Builder.create()
                .actionName("Invoke")
                .targetPipeline(targetPipeline)
                .variables(List.of(Variable.builder()
                        .name("name1")
                        .value("value1")
                        .build()))
                .sourceRevisions(List.of(SourceRevision.builder()
                        .actionName("Source")
                        .revisionType(RevisionType.S3_OBJECT_VERSION_ID)
                        .revisionValue("testRevisionValue")
                        .build()))
                .build()))
        .build());
csharp
using Amazon.CDK.AWS.CodePipeline.Actions;


var pipeline = new Pipeline(this, "MyPipeline");
var targetPipeline = Pipeline.FromPipelineArn(this, "Pipeline", "arn:aws:codepipeline:us-east-1:123456789012:InvokePipelineAction"); // If targetPipeline is not created by cdk, import from arn.
pipeline.AddStage(new StageOptions {
    StageName = "stageName",
    Actions = new [] { new PipelineInvokeAction(new PipelineInvokeActionProps {
        ActionName = "Invoke",
        TargetPipeline = targetPipeline,
        Variables = new [] { new Variable {
            Name = "name1",
            Value = "value1"
        } },
        SourceRevisions = new [] { new SourceRevision {
            ActionName = "Source",
            RevisionType = RevisionType.S3_OBJECT_VERSION_ID,
            RevisionValue = "testRevisionValue"
        } }
    }) }
});
go
import "github.com/aws/aws-cdk-go/awscdk"


pipeline := codepipeline.NewPipeline(this, jsii.String("MyPipeline"))
targetPipeline := codepipeline.Pipeline_FromPipelineArn(this, jsii.String("Pipeline"), jsii.String("arn:aws:codepipeline:us-east-1:123456789012:InvokePipelineAction")) // If targetPipeline is not created by cdk, import from arn.
pipeline.AddStage(&StageOptions{
	StageName: jsii.String("stageName"),
	Actions: []IAction{
		cpactions.NewPipelineInvokeAction(&PipelineInvokeActionProps{
			ActionName: jsii.String("Invoke"),
			TargetPipeline: *TargetPipeline,
			Variables: []Variable{
				&Variable{
					Name: jsii.String("name1"),
					Value: jsii.String("value1"),
				},
			},
			SourceRevisions: []SourceRevision{
				&SourceRevision{
					ActionName: jsii.String("Source"),
					RevisionType: cpactions.RevisionType_S3_OBJECT_VERSION_ID,
					RevisionValue: jsii.String("testRevisionValue"),
				},
			},
		}),
	},
})

See the AWS documentation for information on Action structure reference.

Invoke ​

Inspector ​

Amazon Inspector is a vulnerability management service that automatically discovers workloads and continually scans them for software vulnerabilities and unintended network exposure.

The actions InspectorSourceCodeScanAction and InspectorEcrImageScanAction automate detecting and fixing security vulnerabilities in your open source code. The actions are managed compute actions with security scanning capabilities. You can use the actions with application source code in your third-party repository, such as GitHub or Bitbucket Cloud, or with images for container applications.

Your actions will scan and report on vulnerability levels and alerts that you configure.

Inspector Source Code Scan ​

The InspectorSourceCodeScanAction allows you to scan the application source code for vulnerabilities in your repository.

ts
declare const pipeline: codepipeline.Pipeline;

const sourceOutput = new codepipeline.Artifact();
const sourceAction = new codepipeline_actions.CodeStarConnectionsSourceAction({
  actionName: 'CodeStarConnectionsSourceAction',
  output: sourceOutput,
  connectionArn: 'your-connection-arn',
  owner: 'your-owner',
  repo: 'your-repo',
});

const scanOutput = new codepipeline.Artifact();
const scanAction = new codepipeline_actions.InspectorSourceCodeScanAction({
  actionName: 'InspectorSourceCodeScanAction',
  input: sourceOutput,
  output: scanOutput,
});

pipeline.addStage({
  stageName: 'Source',
  actions: [sourceAction],
});
pipeline.addStage({
  stageName: 'Scan',
  actions: [scanAction],
});
python
# pipeline: codepipeline.Pipeline


source_output = codepipeline.Artifact()
source_action = codepipeline_actions.CodeStarConnectionsSourceAction(
    action_name="CodeStarConnectionsSourceAction",
    output=source_output,
    connection_arn="your-connection-arn",
    owner="your-owner",
    repo="your-repo"
)

scan_output = codepipeline.Artifact()
scan_action = codepipeline_actions.InspectorSourceCodeScanAction(
    action_name="InspectorSourceCodeScanAction",
    input=source_output,
    output=scan_output
)

pipeline.add_stage(
    stage_name="Source",
    actions=[source_action]
)
pipeline.add_stage(
    stage_name="Scan",
    actions=[scan_action]
)
java
Pipeline pipeline;


Artifact sourceOutput = new Artifact();
CodeStarConnectionsSourceAction sourceAction = CodeStarConnectionsSourceAction.Builder.create()
        .actionName("CodeStarConnectionsSourceAction")
        .output(sourceOutput)
        .connectionArn("your-connection-arn")
        .owner("your-owner")
        .repo("your-repo")
        .build();

Artifact scanOutput = new Artifact();
InspectorSourceCodeScanAction scanAction = InspectorSourceCodeScanAction.Builder.create()
        .actionName("InspectorSourceCodeScanAction")
        .input(sourceOutput)
        .output(scanOutput)
        .build();

pipeline.addStage(StageOptions.builder()
        .stageName("Source")
        .actions(List.of(sourceAction))
        .build());
pipeline.addStage(StageOptions.builder()
        .stageName("Scan")
        .actions(List.of(scanAction))
        .build());
csharp
Pipeline pipeline;


var sourceOutput = new Artifact();
var sourceAction = new CodeStarConnectionsSourceAction(new CodeStarConnectionsSourceActionProps {
    ActionName = "CodeStarConnectionsSourceAction",
    Output = sourceOutput,
    ConnectionArn = "your-connection-arn",
    Owner = "your-owner",
    Repo = "your-repo"
});

var scanOutput = new Artifact();
var scanAction = new InspectorSourceCodeScanAction(new InspectorSourceCodeScanActionProps {
    ActionName = "InspectorSourceCodeScanAction",
    Input = sourceOutput,
    Output = scanOutput
});

pipeline.AddStage(new StageOptions {
    StageName = "Source",
    Actions = new [] { sourceAction }
});
pipeline.AddStage(new StageOptions {
    StageName = "Scan",
    Actions = new [] { scanAction }
});
go
var pipeline Pipeline


sourceOutput := codepipeline.NewArtifact()
sourceAction := codepipeline_actions.NewCodeStarConnectionsSourceAction(&CodeStarConnectionsSourceActionProps{
	ActionName: jsii.String("CodeStarConnectionsSourceAction"),
	Output: sourceOutput,
	ConnectionArn: jsii.String("your-connection-arn"),
	Owner: jsii.String("your-owner"),
	Repo: jsii.String("your-repo"),
})

scanOutput := codepipeline.NewArtifact()
scanAction := codepipeline_actions.NewInspectorSourceCodeScanAction(&InspectorSourceCodeScanActionProps{
	ActionName: jsii.String("InspectorSourceCodeScanAction"),
	Input: sourceOutput,
	Output: scanOutput,
})

pipeline.AddStage(&StageOptions{
	StageName: jsii.String("Source"),
	Actions: []IAction{
		sourceAction,
	},
})
pipeline.AddStage(&StageOptions{
	StageName: jsii.String("Scan"),
	Actions: []IAction{
		scanAction,
	},
})

Inspector ECR Image Scan ​

The InspectorEcrImageScanAction allows you to scan the image for vulnerabilities in your container applications.

ts
import * as ecr from 'aws-cdk-lib/aws-ecr';

declare const pipeline: codepipeline.Pipeline;
declare const repository: ecr.IRepository;

const scanOutput = new codepipeline.Artifact();
const scanAction = new codepipeline_actions.InspectorEcrImageScanAction({
  actionName: 'InspectorEcrImageScanAction',
  output: scanOutput,
  repository: repository,
});

pipeline.addStage({
  stageName: 'Scan',
  actions: [scanAction],
});
python
import aws_cdk.aws_ecr as ecr

# pipeline: codepipeline.Pipeline
# repository: ecr.IRepository


scan_output = codepipeline.Artifact()
scan_action = codepipeline_actions.InspectorEcrImageScanAction(
    action_name="InspectorEcrImageScanAction",
    output=scan_output,
    repository=repository
)

pipeline.add_stage(
    stage_name="Scan",
    actions=[scan_action]
)
java
import software.amazon.awscdk.services.ecr.*;

Pipeline pipeline;
IRepository repository;


Artifact scanOutput = new Artifact();
InspectorEcrImageScanAction scanAction = InspectorEcrImageScanAction.Builder.create()
        .actionName("InspectorEcrImageScanAction")
        .output(scanOutput)
        .repository(repository)
        .build();

pipeline.addStage(StageOptions.builder()
        .stageName("Scan")
        .actions(List.of(scanAction))
        .build());
csharp
using Amazon.CDK.AWS.ECR;

Pipeline pipeline;
IRepository repository;


var scanOutput = new Artifact();
var scanAction = new InspectorEcrImageScanAction(new InspectorEcrImageScanActionProps {
    ActionName = "InspectorEcrImageScanAction",
    Output = scanOutput,
    Repository = repository
});

pipeline.AddStage(new StageOptions {
    StageName = "Scan",
    Actions = new [] { scanAction }
});
go
import ecr "github.com/aws/aws-cdk-go/awscdk"

var pipeline Pipeline
var repository IRepository


scanOutput := codepipeline.NewArtifact()
scanAction := codepipeline_actions.NewInspectorEcrImageScanAction(&InspectorEcrImageScanActionProps{
	ActionName: jsii.String("InspectorEcrImageScanAction"),
	Output: scanOutput,
	Repository: repository,
})

pipeline.AddStage(&StageOptions{
	StageName: jsii.String("Scan"),
	Actions: []IAction{
		scanAction,
	},
})

Compute ​

Commands ​

The Commands action allows you to run shell commands in a virtual compute instance. When you run the action, commands specified in the action configuration are run in a separate container. All artifacts that are specified as input artifacts to a CodeBuild action are available inside of the container running the commands. This action allows you to specify commands without first creating a CodeBuild project.

ts
// Source action
const bucket = new s3.Bucket(this, 'SourceBucket', {
  versioned: true,
});
const sourceArtifact = new codepipeline.Artifact('SourceArtifact');
const sourceAction = new codepipeline_actions.S3SourceAction({
  actionName: 'Source',
  output: sourceArtifact,
  bucket,
  bucketKey: 'my.zip',
});

// Commands action
const outputArtifact = new codepipeline.Artifact('OutputArtifact');
const commandsAction = new codepipeline_actions.CommandsAction({
  actionName: 'Commands',
  commands: [
    'echo "some commands"',
  ],
  input: sourceArtifact,
  output: outputArtifact,
});

const pipeline = new codepipeline.Pipeline(this, 'Pipeline', {
  stages: [
    {
      stageName: 'Source',
      actions: [sourceAction],
    },
    {
      stageName: 'Commands',
      actions: [commandsAction],
    },
  ],
});
python
# Source action
bucket = s3.Bucket(self, "SourceBucket",
    versioned=True
)
source_artifact = codepipeline.Artifact("SourceArtifact")
source_action = codepipeline_actions.S3SourceAction(
    action_name="Source",
    output=source_artifact,
    bucket=bucket,
    bucket_key="my.zip"
)

# Commands action
output_artifact = codepipeline.Artifact("OutputArtifact")
commands_action = codepipeline_actions.CommandsAction(
    action_name="Commands",
    commands=["echo \"some commands\""
    ],
    input=source_artifact,
    output=output_artifact
)

pipeline = codepipeline.Pipeline(self, "Pipeline",
    stages=[codepipeline.StageProps(
        stage_name="Source",
        actions=[source_action]
    ), codepipeline.StageProps(
        stage_name="Commands",
        actions=[commands_action]
    )
    ]
)
java
// Source action
Bucket bucket = Bucket.Builder.create(this, "SourceBucket")
        .versioned(true)
        .build();
Artifact sourceArtifact = new Artifact("SourceArtifact");
S3SourceAction sourceAction = S3SourceAction.Builder.create()
        .actionName("Source")
        .output(sourceArtifact)
        .bucket(bucket)
        .bucketKey("my.zip")
        .build();

// Commands action
Artifact outputArtifact = new Artifact("OutputArtifact");
CommandsAction commandsAction = CommandsAction.Builder.create()
        .actionName("Commands")
        .commands(List.of("echo \"some commands\""))
        .input(sourceArtifact)
        .output(outputArtifact)
        .build();

Pipeline pipeline = Pipeline.Builder.create(this, "Pipeline")
        .stages(List.of(StageProps.builder()
                .stageName("Source")
                .actions(List.of(sourceAction))
                .build(), StageProps.builder()
                .stageName("Commands")
                .actions(List.of(commandsAction))
                .build()))
        .build();
csharp
// Source action
var bucket = new Bucket(this, "SourceBucket", new BucketProps {
    Versioned = true
});
var sourceArtifact = new Artifact("SourceArtifact");
var sourceAction = new S3SourceAction(new S3SourceActionProps {
    ActionName = "Source",
    Output = sourceArtifact,
    Bucket = bucket,
    BucketKey = "my.zip"
});

// Commands action
var outputArtifact = new Artifact("OutputArtifact");
var commandsAction = new CommandsAction(new CommandsActionProps {
    ActionName = "Commands",
    Commands = new [] { "echo \"some commands\"" },
    Input = sourceArtifact,
    Output = outputArtifact
});

var pipeline = new Pipeline(this, "Pipeline", new PipelineProps {
    Stages = new [] { new StageProps {
        StageName = "Source",
        Actions = new [] { sourceAction }
    }, new StageProps {
        StageName = "Commands",
        Actions = new [] { commandsAction }
    } }
});
go
// Source action
bucket := s3.NewBucket(this, jsii.String("SourceBucket"), &BucketProps{
	Versioned: jsii.Boolean(true),
})
sourceArtifact := codepipeline.NewArtifact(jsii.String("SourceArtifact"))
sourceAction := codepipeline_actions.NewS3SourceAction(&S3SourceActionProps{
	ActionName: jsii.String("Source"),
	Output: sourceArtifact,
	Bucket: Bucket,
	BucketKey: jsii.String("my.zip"),
})

// Commands action
outputArtifact := codepipeline.NewArtifact(jsii.String("OutputArtifact"))
commandsAction := codepipeline_actions.NewCommandsAction(&CommandsActionProps{
	ActionName: jsii.String("Commands"),
	Commands: []*string{
		jsii.String("echo \"some commands\""),
	},
	Input: sourceArtifact,
	Output: outputArtifact,
})

pipeline := codepipeline.NewPipeline(this, jsii.String("Pipeline"), &PipelineProps{
	Stages: []StageProps{
		&StageProps{
			StageName: jsii.String("Source"),
			Actions: []IAction{
				sourceAction,
			},
		},
		&StageProps{
			StageName: jsii.String("Commands"),
			Actions: []IAction{
				commandsAction,
			},
		},
	},
})

If you want to filter the files to be included in the output artifact, you can specify their paths as the second argument to Artifact.

ts
declare const sourceArtifact: codepipeline.Artifact;

// filter files to be included in the output artifact
const outputArtifact = new codepipeline.Artifact('OutputArtifact', ['my-dir/**/*']);
const commandsAction = new codepipeline_actions.CommandsAction({
  actionName: 'Commands',
  commands: [
    'mkdir -p my-dir',
    'echo "HelloWorld" > my-dir/file.txt',
  ],
  input: sourceArtifact,
  output: outputArtifact,
});
python
# source_artifact: codepipeline.Artifact


# filter files to be included in the output artifact
output_artifact = codepipeline.Artifact("OutputArtifact", ["my-dir/**/*"])
commands_action = codepipeline_actions.CommandsAction(
    action_name="Commands",
    commands=["mkdir -p my-dir", "echo \"HelloWorld\" > my-dir/file.txt"
    ],
    input=source_artifact,
    output=output_artifact
)
java
Artifact sourceArtifact;


// filter files to be included in the output artifact
Artifact outputArtifact = new Artifact("OutputArtifact", List.of("my-dir/**/*"));
CommandsAction commandsAction = CommandsAction.Builder.create()
        .actionName("Commands")
        .commands(List.of("mkdir -p my-dir", "echo \"HelloWorld\" > my-dir/file.txt"))
        .input(sourceArtifact)
        .output(outputArtifact)
        .build();
csharp
Artifact sourceArtifact;


// filter files to be included in the output artifact
var outputArtifact = new Artifact("OutputArtifact", new [] { "my-dir/**/*" });
var commandsAction = new CommandsAction(new CommandsActionProps {
    ActionName = "Commands",
    Commands = new [] { "mkdir -p my-dir", "echo \"HelloWorld\" > my-dir/file.txt" },
    Input = sourceArtifact,
    Output = outputArtifact
});
go
var sourceArtifact Artifact


// filter files to be included in the output artifact
outputArtifact := codepipeline.NewArtifact(jsii.String("OutputArtifact"), []*string{
	jsii.String("my-dir/**/*"),
})
commandsAction := codepipeline_actions.NewCommandsAction(&CommandsActionProps{
	ActionName: jsii.String("Commands"),
	Commands: []*string{
		jsii.String("mkdir -p my-dir"),
		jsii.String("echo \"HelloWorld\" > my-dir/file.txt"),
	},
	Input: sourceArtifact,
	Output: outputArtifact,
})

You can also specify the outputVariables property in the CommandsAction to emit environment variables that can be used in subsequent actions. The variables are those defined in your shell commands or exported as defaults by the CodeBuild service. For a reference of CodeBuild environment variables, see Environment variables in build environments in the CodeBuild User Guide.

To use the output variables in a subsequent action, you can use the variable method on the action:

ts
declare const sourceArtifact: codepipeline.Artifact;
declare const outputArtifact: codepipeline.Artifact;

const commandsAction = new codepipeline_actions.CommandsAction({
  actionName: 'Commands',
  commands: [
    'export MY_OUTPUT=my-key',
  ],
  input: sourceArtifact,
  output: outputArtifact,
  outputVariables: ['MY_OUTPUT', 'CODEBUILD_BUILD_ID'], // CODEBUILD_BUILD_ID is a variable defined by CodeBuild
});

// Deploy action
const deployAction = new codepipeline_actions.S3DeployAction({
  actionName: 'DeployAction',
  extract: true,
  input: outputArtifact,
  bucket: new s3.Bucket(this, 'DeployBucket'),
  objectKey: commandsAction.variable('MY_OUTPUT'), // the variable emitted by the Commands action
});
python
# source_artifact: codepipeline.Artifact
# output_artifact: codepipeline.Artifact


commands_action = codepipeline_actions.CommandsAction(
    action_name="Commands",
    commands=["export MY_OUTPUT=my-key"
    ],
    input=source_artifact,
    output=output_artifact,
    output_variables=["MY_OUTPUT", "CODEBUILD_BUILD_ID"]
)

# Deploy action
deploy_action = codepipeline_actions.S3DeployAction(
    action_name="DeployAction",
    extract=True,
    input=output_artifact,
    bucket=s3.Bucket(self, "DeployBucket"),
    object_key=commands_action.variable("MY_OUTPUT")
)
java
Artifact sourceArtifact;
Artifact outputArtifact;


CommandsAction commandsAction = CommandsAction.Builder.create()
        .actionName("Commands")
        .commands(List.of("export MY_OUTPUT=my-key"))
        .input(sourceArtifact)
        .output(outputArtifact)
        .outputVariables(List.of("MY_OUTPUT", "CODEBUILD_BUILD_ID"))
        .build();

// Deploy action
S3DeployAction deployAction = S3DeployAction.Builder.create()
        .actionName("DeployAction")
        .extract(true)
        .input(outputArtifact)
        .bucket(new Bucket(this, "DeployBucket"))
        .objectKey(commandsAction.variable("MY_OUTPUT"))
        .build();
csharp
Artifact sourceArtifact;
Artifact outputArtifact;


var commandsAction = new CommandsAction(new CommandsActionProps {
    ActionName = "Commands",
    Commands = new [] { "export MY_OUTPUT=my-key" },
    Input = sourceArtifact,
    Output = outputArtifact,
    OutputVariables = new [] { "MY_OUTPUT", "CODEBUILD_BUILD_ID" }
});

// Deploy action
var deployAction = new S3DeployAction(new S3DeployActionProps {
    ActionName = "DeployAction",
    Extract = true,
    Input = outputArtifact,
    Bucket = new Bucket(this, "DeployBucket"),
    ObjectKey = commandsAction.Variable("MY_OUTPUT")
});
go
var sourceArtifact Artifact
var outputArtifact Artifact


commandsAction := codepipeline_actions.NewCommandsAction(&CommandsActionProps{
	ActionName: jsii.String("Commands"),
	Commands: []*string{
		jsii.String("export MY_OUTPUT=my-key"),
	},
	Input: sourceArtifact,
	Output: outputArtifact,
	OutputVariables: []*string{
		jsii.String("MY_OUTPUT"),
		jsii.String("CODEBUILD_BUILD_ID"),
	},
})

// Deploy action
deployAction := codepipeline_actions.NewS3DeployAction(&S3DeployActionProps{
	ActionName: jsii.String("DeployAction"),
	Extract: jsii.Boolean(true),
	Input: outputArtifact,
	Bucket: s3.NewBucket(this, jsii.String("DeployBucket")),
	ObjectKey: commandsAction.Variable(jsii.String("MY_OUTPUT")),
})

See the AWS documentation for more details about using Commands action in CodePipeline.

Types ​

NameKindSummary
ActionClassLow-level class for generic CodePipeline Actions.
AlexaSkillDeployActionClassDeploys the skill to Alexa.
AlexaSkillDeployActionPropsStructConstruction properties of the AlexaSkillDeployAction Alexa deploy Action.
BaseJenkinsProviderConstruct
CacheControlClassUsed for HTTP cache-control header, which influences downstream caches.
CloudFormationCreateReplaceChangeSetActionClassCodePipeline action to prepare a change set.
CloudFormationCreateReplaceChangeSetActionPropsStructProperties for the CloudFormationCreateReplaceChangeSetAction.
CloudFormationCreateUpdateStackActionClassCodePipeline action to deploy a stack.
CloudFormationCreateUpdateStackActionPropsStructProperties for the CloudFormationCreateUpdateStackAction.
CloudFormationDeleteStackActionClassCodePipeline action to delete a stack.
CloudFormationDeleteStackActionPropsStructProperties for the CloudFormationDeleteStackAction.
CloudFormationDeployStackInstancesActionClassCodePipeline action to create/update Stack Instances of a StackSet.
CloudFormationDeployStackInstancesActionPropsStructProperties for the CloudFormationDeployStackInstancesAction.
CloudFormationDeployStackSetActionClassCodePipeline action to deploy a stackset.
CloudFormationDeployStackSetActionPropsStructProperties for the CloudFormationDeployStackSetAction.
CloudFormationExecuteChangeSetActionClassCodePipeline action to execute a prepared change set.
CloudFormationExecuteChangeSetActionPropsStructProperties for the CloudFormationExecuteChangeSetAction.
CodeBuildActionClassCodePipeline build action that uses AWS CodeBuild.
CodeBuildActionPropsStructConstruction properties of the CodeBuildAction CodeBuild build CodePipeline action.
CodeBuildActionTypeEnumThe type of the CodeBuild action that determines its CodePipeline Category - Build, or Test.
CodeCommitSourceActionClassCodePipeline Source that is provided by an AWS CodeCommit repository.
CodeCommitSourceActionPropsStructConstruction properties of the CodeCommitSourceAction CodeCommit source CodePipeline Action.
CodeCommitSourceVariablesStructThe CodePipeline variables emitted by the CodeCommit source Action.
CodeCommitTriggerEnumHow should the CodeCommit Action detect changes.
CodeDeployEcsContainerImageInputStructConfiguration for replacing a placeholder string in the ECS task definition template file with an image URI.
CodeDeployEcsDeployActionClass
CodeDeployEcsDeployActionPropsStructConstruction properties of the CodeDeployEcsDeployAction CodeDeploy ECS deploy CodePipeline Action.
CodeDeployServerDeployActionClass
CodeDeployServerDeployActionPropsStructConstruction properties of the CodeDeployServerDeployAction CodeDeploy server deploy CodePipeline Action.
CodeStarConnectionsSourceActionClassA CodePipeline source action for the CodeStar Connections source, which allows connecting to GitHub and BitBucket.
CodeStarConnectionsSourceActionPropsStructConstruction properties for CodeStarConnectionsSourceAction.
CodeStarSourceVariablesStructThe CodePipeline variables emitted by CodeStar source Action.
CommandsActionClassCodePipeline compute action that uses AWS Commands.
CommandsActionPropsStructConstruction properties of the CommandsAction.
CommonCloudFormationStackSetOptionsStructOptions in common between both StackSet actions.
Ec2DeployActionClassCodePipeline Action to deploy EC2 instances.
Ec2DeployActionPropsStructConstruction properties of Ec2DeployAction.
Ec2DeploySpecificationsClassA deploy specifications for EC2 deploy action.
Ec2DeploySpecificationsInlinePropsStructProperties of Ec2DeploySpecifications.inline().
Ec2InstanceTypeEnumThe type of instances or SSM nodes created in Amazon EC2.
Ec2MaxInstancesClassNumber or percentage of max instances for EC2 deploy action.
EcrBuildAndPublishActionClassCodePipeline build action that uses AWS EcrBuildAndPublish.
EcrBuildAndPublishActionPropsStructConstruction properties of the EcrBuildAndPublishAction.
EcrBuildAndPublishVariablesStructThe CodePipeline variables emitted by the ECR build and publish Action.
EcrSourceActionClassThe ECR Repository source CodePipeline Action.
EcrSourceActionPropsStructConstruction properties of EcrSourceAction.
EcrSourceVariablesStructThe CodePipeline variables emitted by the ECR source Action.
EcsDeployActionClassCodePipeline Action to deploy an ECS Service.
EcsDeployActionPropsStructConstruction properties of EcsDeployAction.
ElasticBeanstalkDeployActionClassCodePipeline action to deploy an AWS ElasticBeanstalk Application.
ElasticBeanstalkDeployActionPropsStructConstruction properties of the ElasticBeanstalkDeployAction Elastic Beanstalk deploy CodePipeline Action.
GitHubSourceActionClassSource that is provided by a GitHub repository.
GitHubSourceActionPropsStructConstruction properties of the GitHubSourceAction GitHub source action.
GitHubSourceVariablesStructThe CodePipeline variables emitted by GitHub source Action.
GitHubTriggerEnumIf and how the GitHub source action should be triggered.
ICustomEventRuleInterfaceRepresents a custom event rule in AWS CodePipeline Actions.
IJenkinsProviderInterfaceA Jenkins provider.
InspectorEcrImageScanActionClassCodePipeline invoke action that uses AWS InspectorScan for ECR images.
InspectorEcrImageScanActionPropsStructConstruction properties of the InspectorEcrImageScanAction.
InspectorScanActionBaseClassCodePipeline invoke action that uses AWS InspectorScan.
InspectorScanActionBasePropsStructBase construction properties of the InspectorScanActionBase.
InspectorScanVariablesStructThe CodePipeline variables emitted by the InspectorScan Action.
InspectorSourceCodeScanActionClassCodePipeline invoke action that uses AWS InspectorScan for source code.
InspectorSourceCodeScanActionPropsStructConstruction properties of the InspectorSourceCodeScanAction.
JenkinsActionClassJenkins build CodePipeline Action.
JenkinsActionPropsStructConstruction properties of JenkinsAction.
JenkinsActionTypeEnumThe type of the Jenkins Action that determines its CodePipeline Category - Build, or Test.
JenkinsProviderConstructA class representing Jenkins providers.
JenkinsProviderAttributesStructProperties for importing an existing Jenkins provider.
JenkinsProviderPropsStruct
LambdaInvokeActionClassCodePipeline invoke Action that is provided by an AWS Lambda function.
LambdaInvokeActionPropsStructConstruction properties of the LambdaInvokeAction Lambda invoke CodePipeline Action.
ManualApprovalActionClassManual approval action.
ManualApprovalActionPropsStructConstruction properties of the ManualApprovalAction.
OrganizationsDeploymentPropsStructProperties for configuring service-managed (Organizations) permissions.
PipelineInvokeActionClassCodePipeline action to invoke a pipeline.
PipelineInvokeActionPropsStructConstruction properties of the PipelineInvokeAction.
RegistryTypeEnumThe type of registry to use for the EcrBuildAndPublish action.
RevisionTypeEnumThe types of revision for a pipeline execution.
S3DeployActionClassDeploys the sourceArtifact to Amazon S3.
S3DeployActionPropsStructConstruction properties of the S3DeployAction S3 deploy Action.
S3SourceActionClassSource that is provided by a specific Amazon S3 object.
S3SourceActionPropsStructConstruction properties of the S3SourceAction S3 source Action.
S3SourceVariablesStructThe CodePipeline variables emitted by the S3 source Action.
S3TriggerEnumHow should the S3 Action detect changes.
SelfManagedDeploymentPropsStructProperties for configuring self-managed permissions.
ServiceCatalogDeployActionBeta1ClassCodePipeline action to connect to an existing ServiceCatalog product.
ServiceCatalogDeployActionBeta1PropsStructConstruction properties of the ServiceCatalogDeployActionBeta1 ServiceCatalog deploy CodePipeline Action.
SourceRevisionStructA list that allows you to specify, or override, the source revision for a pipeline execution that's being started.
StackInstancesClassWhere Stack Instances will be created from the StackSet.
StackSetDeploymentModelClassDetermines how IAM roles are created and managed.
StackSetOrganizationsAutoDeploymentEnumDescribes whether AWS CloudFormation StackSets automatically deploys to AWS Organizations accounts that are added to a target organization or organizational unit (OU).
StackSetParametersClassBase parameters for the StackSet.
StackSetTemplateClassThe source of a StackSet template.
StateMachineInputClassRepresents the input for the StateMachine.
StepFunctionInvokeActionClassStepFunctionInvokeAction that is provided by an AWS CodePipeline.
StepFunctionsInvokeActionPropsStructConstruction properties of the StepFunctionsInvokeAction StepFunction Invoke Action.
VariableStructA pipeline-level variable used for a pipeline execution.