aws-cdk.aws-codepipeline-actions


Nameaws-cdk.aws-codepipeline-actions JSON
Version 1.203.0 PyPI version JSON
download
home_pagehttps://github.com/aws/aws-cdk
SummaryConcrete Actions for AWS Code Pipeline
upload_time2023-05-31 23:01:28
maintainer
docs_urlNone
authorAmazon Web Services
requires_python~=3.7
licenseApache-2.0
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # AWS CodePipeline Actions

<!--BEGIN STABILITY BANNER-->---


![cdk-constructs: Stable](https://img.shields.io/badge/cdk--constructs-stable-success.svg?style=for-the-badge)

---
<!--END STABILITY BANNER-->

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

```python
import aws_cdk.aws_codepipeline as codepipeline
import aws_cdk.aws_codepipeline_actions as codepipeline_actions
```

## Sources

### AWS CodeCommit

To use a CodeCommit Repository in a CodePipeline:

```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]
)
```

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.

```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
)
```

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

```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()]
)
```

The CodeCommit source action emits variables:

```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
        )
    }
)
```

### GitHub

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

* A [GitHub Access Token](https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line),
  with scopes **repo** and **admin:repo_hook**.
* A [Secrets Manager Secret](https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_create-basic-secret.html)
  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:

```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]
)
```

The GitHub source action emits variables:

```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
        )
    }
)
```

### 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](https://docs.aws.amazon.com/cli/latest/reference/codestar-connections/list-connections.html)
to find it.
After that, you can safely abort creating or editing the pipeline -
the connection has already been created.

```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"
)
```

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:

```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
        )
    }
)
```

### AWS S3 Source

To use an S3 Bucket as a source in CodePipeline:

```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]
)
```

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:

```python
source_bucket = s3.Bucket.from_bucket_attributes(self, "SourceBucket",
    bucket_name="my-bucket",
    region="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:

```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
)
```

The S3 source action emits variables:

```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
        )
    }
)
```

### AWS ECR

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

```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]
)
```

The ECR source action emits variables:

```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
        )
    }
)
```

## Build & test

### AWS CodeBuild

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

```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]
    )
    ]
)
```

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

```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
)
```

#### 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:

```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")
    ]
)
```

**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:

```python
project = codebuild.PipelineProject(self, "MyProject",
    build_spec=codebuild.BuildSpec.from_object({
        "version": "0.2",
        "phases": {
            "build": {
                "commands": []
            }
        },
        "artifacts": {
            "secondary-artifacts": {
                "artifact1": {},
                "artifact2": {}
            }
        }
    })
)
```

#### 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:

```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")
        )
    }
)
```

### Jenkins

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

```python
jenkins_provider = codepipeline_actions.JenkinsProvider(self, "JenkinsProvider",
    provider_name="MyJenkinsProvider",
    server_url="http://my-jenkins.com:8080",
    version="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:

```python
jenkins_provider = codepipeline_actions.JenkinsProvider.from_jenkins_provider_attributes(self, "JenkinsProvider",
    provider_name="MyJenkinsProvider",
    server_url="http://my-jenkins.com:8080",
    version="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:

```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
)
```

## 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:

```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",
    stages=[source_stage, prod_stage
    ]
)
```

See [the AWS documentation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/continuous-delivery-codepipeline.html)
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](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/what-is-cfnstacksets.html)
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 Instaces using the current version of the StackSet.

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

```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"])
        )
    ]
)
```

#### 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:

```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_14_X
)
# other resources that your Lambda needs, added to the lambdaStack...

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

# 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.UBUNTU_14_04_NODEJS_10_1_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.UBUNTU_14_04_NODEJS_10_1_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
            ]
        )
    ]
)
```

#### Cross-account actions

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

```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"
)
```

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:

```python
from aws_cdk.core 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
)
```

### AWS CodeDeploy

#### Server deployments

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

```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]
)
```

##### Lambda deployments

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

```python
lambda_code = lambda_.Code.from_cfn_parameters()
func = lambda_.Function(self, "Lambda",
    code=lambda_code,
    handler="index.handler",
    runtime=lambda_.Runtime.NODEJS_14_X
)
# 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
)
```

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](https://docs.aws.amazon.com/codepipeline/latest/userguide/pipelines-create.html#pipelines-create-image-definitions):

```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)
        )
    ]
)
```

#### 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](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-account-settings.html#ecs-resource-ids).
This also works if the service is in a different account and/or region than the pipeline:

```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
        )
    ]
)
```

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](https://docs.aws.amazon.com/codepipeline/latest/userguide/how-to-custom-role.html#how-to-update-role-new-services)
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](https://docs.aws.amazon.com/cdk/latest/guide/assets.html#assets_types_docker),
and use the [CDK Pipelines module](https://docs.aws.amazon.com/cdk/api/latest/docs/pipelines-readme.html).

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:

```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, synthesizer=None, terminationProtection=None, analyticsReporting=None):
        super().__init__(scope, id, image=image, description=description, env=env, stackName=stackName, tags=tags, synthesizer=synthesizer, terminationProtection=terminationProtection, analyticsReporting=analyticsReporting)

        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, synthesizer=None, terminationProtection=None, analyticsReporting=None):
        super().__init__(scope, id, description=description, env=env, stackName=stackName, tags=tags, synthesizer=synthesizer, terminationProtection=terminationProtection, analyticsReporting=analyticsReporting)

        # ********* 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
)
```

### AWS S3 Deployment

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

```python
source_output = codepipeline.Artifact()
target_bucket = s3.Bucket(self, "MyBucket")

pipeline = codepipeline.Pipeline(self, "MyPipeline")
deploy_action = codepipeline_actions.S3DeployAction(
    action_name="S3Deploy",
    bucket=target_bucket,
    input=source_output
)
deploy_stage = pipeline.add_stage(
    stage_name="Deploy",
    actions=[deploy_action]
)
```

#### 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:

```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
            )
        ]
    )
    ]
)
```

### Alexa Skill

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

```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"
)
```

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

```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"
)
```

### AWS Service Catalog

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

```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"
)
```

## Approve & invoke

### Manual approval Action

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

```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"
)
approve_stage.add_action(manual_approval_action)
```

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`:

```python
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)
```

### AWS Lambda

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

```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]
)
```

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

```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
)
```

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

```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"
)
```

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:

```python
# later:
# project: codebuild.PipelineProject
lambda_invoke_action = codepipeline_actions.LambdaInvokeAction(
    action_name="Lambda",
    lambda_=lambda_.Function(self, "Func",
        runtime=lambda_.Runtime.NODEJS_14_X,
        handler="index.handler",
        code=lambda_.Code.from_inline("""
                    const AWS = require('aws-sdk');

                    exports.handler = async function(event, context) {
                        const codepipeline = new AWS.CodePipeline();
                        await codepipeline.putJobSuccessResult({
                            jobId: event['CodePipeline.job'].id,
                            outputVariables: {
                                MY_VAR: "some value",
                            },
                        }).promise();
                    }
                """)
    ),
    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")
        )
    }
)
```

See [the AWS documentation](https://docs.aws.amazon.com/codepipeline/latest/userguide/actions-invoke-lambda-function.html)
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:

```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]
)
```

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

```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]
)
```

See [the AWS documentation](https://docs.aws.amazon.com/codepipeline/latest/userguide/action-reference-StepFunctions.html)
for information on Action structure reference.



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/aws/aws-cdk",
    "name": "aws-cdk.aws-codepipeline-actions",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "~=3.7",
    "maintainer_email": "",
    "keywords": "",
    "author": "Amazon Web Services",
    "author_email": "",
    "download_url": "https://files.pythonhosted.org/packages/3a/72/1122f9c098129d9c2ce7f20debfde7dbb7ea4a60dc33d4e78213a571d127/aws-cdk.aws-codepipeline-actions-1.203.0.tar.gz",
    "platform": null,
    "description": "# AWS CodePipeline Actions\n\n<!--BEGIN STABILITY BANNER-->---\n\n\n![cdk-constructs: Stable](https://img.shields.io/badge/cdk--constructs-stable-success.svg?style=for-the-badge)\n\n---\n<!--END STABILITY BANNER-->\n\nThis package contains Actions that can be used in a CodePipeline.\n\n```python\nimport aws_cdk.aws_codepipeline as codepipeline\nimport aws_cdk.aws_codepipeline_actions as codepipeline_actions\n```\n\n## Sources\n\n### AWS CodeCommit\n\nTo use a CodeCommit Repository in a CodePipeline:\n\n```python\nrepo = codecommit.Repository(self, \"Repo\",\n    repository_name=\"MyRepo\"\n)\n\npipeline = codepipeline.Pipeline(self, \"MyPipeline\",\n    pipeline_name=\"MyPipeline\"\n)\nsource_output = codepipeline.Artifact()\nsource_action = codepipeline_actions.CodeCommitSourceAction(\n    action_name=\"CodeCommit\",\n    repository=repo,\n    output=source_output\n)\npipeline.add_stage(\n    stage_name=\"Source\",\n    actions=[source_action]\n)\n```\n\nIf you want to use existing role which can be used by on commit event rule.\nYou can specify the role object in eventRole property.\n\n```python\n# repo: codecommit.Repository\nevent_role = iam.Role.from_role_arn(self, \"Event-role\", \"roleArn\")\nsource_action = codepipeline_actions.CodeCommitSourceAction(\n    action_name=\"CodeCommit\",\n    repository=repo,\n    output=codepipeline.Artifact(),\n    event_role=event_role\n)\n```\n\nIf you want to clone the entire CodeCommit repository (only available for CodeBuild actions),\nyou can set the `codeBuildCloneOutput` property to `true`:\n\n```python\n# project: codebuild.PipelineProject\n# repo: codecommit.Repository\n\nsource_output = codepipeline.Artifact()\nsource_action = codepipeline_actions.CodeCommitSourceAction(\n    action_name=\"CodeCommit\",\n    repository=repo,\n    output=source_output,\n    code_build_clone_output=True\n)\n\nbuild_action = codepipeline_actions.CodeBuildAction(\n    action_name=\"CodeBuild\",\n    project=project,\n    input=source_output,  # The build action must use the CodeCommitSourceAction output as input.\n    outputs=[codepipeline.Artifact()]\n)\n```\n\nThe CodeCommit source action emits variables:\n\n```python\n# project: codebuild.PipelineProject\n# repo: codecommit.Repository\n\nsource_output = codepipeline.Artifact()\nsource_action = codepipeline_actions.CodeCommitSourceAction(\n    action_name=\"CodeCommit\",\n    repository=repo,\n    output=source_output,\n    variables_namespace=\"MyNamespace\"\n)\n\n# later:\n\ncodepipeline_actions.CodeBuildAction(\n    action_name=\"CodeBuild\",\n    project=project,\n    input=source_output,\n    environment_variables={\n        \"COMMIT_ID\": codebuild.BuildEnvironmentVariable(\n            value=source_action.variables.commit_id\n        )\n    }\n)\n```\n\n### GitHub\n\nIf you want to use a GitHub repository as the source, you must create:\n\n* A [GitHub Access Token](https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line),\n  with scopes **repo** and **admin:repo_hook**.\n* A [Secrets Manager Secret](https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_create-basic-secret.html)\n  with the value of the **GitHub Access Token**. Pick whatever name you want (for example `my-github-token`).\n  This token can be stored either as Plaintext or as a Secret key/value.\n  If you stored the token as Plaintext,\n  set `SecretValue.secretsManager('my-github-token')` as the value of `oauthToken`.\n  If you stored it as a Secret key/value,\n  you must set `SecretValue.secretsManager('my-github-token', { jsonField : 'my-github-token' })` as the value of `oauthToken`.\n\nTo use GitHub as the source of a CodePipeline:\n\n```python\n# Read the secret from Secrets Manager\npipeline = codepipeline.Pipeline(self, \"MyPipeline\")\nsource_output = codepipeline.Artifact()\nsource_action = codepipeline_actions.GitHubSourceAction(\n    action_name=\"GitHub_Source\",\n    owner=\"awslabs\",\n    repo=\"aws-cdk\",\n    oauth_token=SecretValue.secrets_manager(\"my-github-token\"),\n    output=source_output,\n    branch=\"develop\"\n)\npipeline.add_stage(\n    stage_name=\"Source\",\n    actions=[source_action]\n)\n```\n\nThe GitHub source action emits variables:\n\n```python\n# source_output: codepipeline.Artifact\n# project: codebuild.PipelineProject\n\n\nsource_action = codepipeline_actions.GitHubSourceAction(\n    action_name=\"Github_Source\",\n    output=source_output,\n    owner=\"my-owner\",\n    repo=\"my-repo\",\n    oauth_token=SecretValue.secrets_manager(\"my-github-token\"),\n    variables_namespace=\"MyNamespace\"\n)\n\n# later:\n\ncodepipeline_actions.CodeBuildAction(\n    action_name=\"CodeBuild\",\n    project=project,\n    input=source_output,\n    environment_variables={\n        \"COMMIT_URL\": codebuild.BuildEnvironmentVariable(\n            value=source_action.variables.commit_url\n        )\n    }\n)\n```\n\n### BitBucket\n\nCodePipeline can use a BitBucket Git repository as a source:\n\n**Note**: you have to manually connect CodePipeline through the AWS Console with your BitBucket account.\nThis is a one-time operation for a given AWS account in a given region.\nThe simplest way to do that is to either start creating a new CodePipeline,\nor edit an existing one, while being logged in to BitBucket.\nChoose BitBucket as the source,\nand grant CodePipeline permissions to your BitBucket account.\nCopy & paste the Connection ARN that you get in the console,\nor use the [`codestar-connections list-connections` AWS CLI operation](https://docs.aws.amazon.com/cli/latest/reference/codestar-connections/list-connections.html)\nto find it.\nAfter that, you can safely abort creating or editing the pipeline -\nthe connection has already been created.\n\n```python\nsource_output = codepipeline.Artifact()\nsource_action = codepipeline_actions.CodeStarConnectionsSourceAction(\n    action_name=\"BitBucket_Source\",\n    owner=\"aws\",\n    repo=\"aws-cdk\",\n    output=source_output,\n    connection_arn=\"arn:aws:codestar-connections:us-east-1:123456789012:connection/12345678-abcd-12ab-34cdef5678gh\"\n)\n```\n\nYou can also use the `CodeStarConnectionsSourceAction` to connect to GitHub, in the same way\n(you just have to select GitHub as the source when creating the connection in the console).\n\nSimilarly to `GitHubSourceAction`, `CodeStarConnectionsSourceAction` also emits the variables:\n\n```python\n# project: codebuild.Project\n\n\nsource_output = codepipeline.Artifact()\nsource_action = codepipeline_actions.CodeStarConnectionsSourceAction(\n    action_name=\"BitBucket_Source\",\n    owner=\"aws\",\n    repo=\"aws-cdk\",\n    output=source_output,\n    connection_arn=\"arn:aws:codestar-connections:us-east-1:123456789012:connection/12345678-abcd-12ab-34cdef5678gh\",\n    variables_namespace=\"SomeSpace\"\n)\n\n# later:\n\ncodepipeline_actions.CodeBuildAction(\n    action_name=\"CodeBuild\",\n    project=project,\n    input=source_output,\n    environment_variables={\n        \"COMMIT_ID\": codebuild.BuildEnvironmentVariable(\n            value=source_action.variables.commit_id\n        )\n    }\n)\n```\n\n### AWS S3 Source\n\nTo use an S3 Bucket as a source in CodePipeline:\n\n```python\nsource_bucket = s3.Bucket(self, \"MyBucket\",\n    versioned=True\n)\n\npipeline = codepipeline.Pipeline(self, \"MyPipeline\")\nsource_output = codepipeline.Artifact()\nsource_action = codepipeline_actions.S3SourceAction(\n    action_name=\"S3Source\",\n    bucket=source_bucket,\n    bucket_key=\"path/to/file.zip\",\n    output=source_output\n)\npipeline.add_stage(\n    stage_name=\"Source\",\n    actions=[source_action]\n)\n```\n\nThe region of the action will be determined by the region the bucket itself is in.\nWhen using a newly created bucket,\nthat region will be taken from the stack the bucket belongs to;\nfor an imported bucket,\nyou can specify the region explicitly:\n\n```python\nsource_bucket = s3.Bucket.from_bucket_attributes(self, \"SourceBucket\",\n    bucket_name=\"my-bucket\",\n    region=\"ap-southeast-1\"\n)\n```\n\nBy default, the Pipeline will poll the Bucket to detect changes.\nYou can change that behavior to use CloudWatch Events by setting the `trigger`\nproperty to `S3Trigger.EVENTS` (it's `S3Trigger.POLL` by default).\nIf you do that, make sure the source Bucket is part of an AWS CloudTrail Trail -\notherwise, the CloudWatch Events will not be emitted,\nand your Pipeline will not react to changes in the Bucket.\nYou can do it through the CDK:\n\n```python\nimport aws_cdk.aws_cloudtrail as cloudtrail\n\n# source_bucket: s3.Bucket\n\nsource_output = codepipeline.Artifact()\nkey = \"some/key.zip\"\ntrail = cloudtrail.Trail(self, \"CloudTrail\")\ntrail.add_s3_event_selector([cloudtrail.S3EventSelector(\n    bucket=source_bucket,\n    object_prefix=key\n)],\n    read_write_type=cloudtrail.ReadWriteType.WRITE_ONLY\n)\nsource_action = codepipeline_actions.S3SourceAction(\n    action_name=\"S3Source\",\n    bucket_key=key,\n    bucket=source_bucket,\n    output=source_output,\n    trigger=codepipeline_actions.S3Trigger.EVENTS\n)\n```\n\nThe S3 source action emits variables:\n\n```python\n# source_bucket: s3.Bucket\n\n# later:\n# project: codebuild.PipelineProject\nkey = \"some/key.zip\"\nsource_output = codepipeline.Artifact()\nsource_action = codepipeline_actions.S3SourceAction(\n    action_name=\"S3Source\",\n    bucket_key=key,\n    bucket=source_bucket,\n    output=source_output,\n    variables_namespace=\"MyNamespace\"\n)\ncodepipeline_actions.CodeBuildAction(\n    action_name=\"CodeBuild\",\n    project=project,\n    input=source_output,\n    environment_variables={\n        \"VERSION_ID\": codebuild.BuildEnvironmentVariable(\n            value=source_action.variables.version_id\n        )\n    }\n)\n```\n\n### AWS ECR\n\nTo use an ECR Repository as a source in a Pipeline:\n\n```python\nimport aws_cdk.aws_ecr as ecr\n\n# ecr_repository: ecr.Repository\n\npipeline = codepipeline.Pipeline(self, \"MyPipeline\")\nsource_output = codepipeline.Artifact()\nsource_action = codepipeline_actions.EcrSourceAction(\n    action_name=\"ECR\",\n    repository=ecr_repository,\n    image_tag=\"some-tag\",  # optional, default: 'latest'\n    output=source_output\n)\npipeline.add_stage(\n    stage_name=\"Source\",\n    actions=[source_action]\n)\n```\n\nThe ECR source action emits variables:\n\n```python\nimport aws_cdk.aws_ecr as ecr\n# ecr_repository: ecr.Repository\n\n# later:\n# project: codebuild.PipelineProject\n\n\nsource_output = codepipeline.Artifact()\nsource_action = codepipeline_actions.EcrSourceAction(\n    action_name=\"Source\",\n    output=source_output,\n    repository=ecr_repository,\n    variables_namespace=\"MyNamespace\"\n)\ncodepipeline_actions.CodeBuildAction(\n    action_name=\"CodeBuild\",\n    project=project,\n    input=source_output,\n    environment_variables={\n        \"IMAGE_URI\": codebuild.BuildEnvironmentVariable(\n            value=source_action.variables.image_uri\n        )\n    }\n)\n```\n\n## Build & test\n\n### AWS CodeBuild\n\nExample of a CodeBuild Project used in a Pipeline, alongside CodeCommit:\n\n```python\n# project: codebuild.PipelineProject\n\nrepository = codecommit.Repository(self, \"MyRepository\",\n    repository_name=\"MyRepository\"\n)\nproject = codebuild.PipelineProject(self, \"MyProject\")\n\nsource_output = codepipeline.Artifact()\nsource_action = codepipeline_actions.CodeCommitSourceAction(\n    action_name=\"CodeCommit\",\n    repository=repository,\n    output=source_output\n)\nbuild_action = codepipeline_actions.CodeBuildAction(\n    action_name=\"CodeBuild\",\n    project=project,\n    input=source_output,\n    outputs=[codepipeline.Artifact()],  # optional\n    execute_batch_build=True,  # optional, defaults to false\n    combine_batch_build_artifacts=True\n)\n\ncodepipeline.Pipeline(self, \"MyPipeline\",\n    stages=[codepipeline.StageProps(\n        stage_name=\"Source\",\n        actions=[source_action]\n    ), codepipeline.StageProps(\n        stage_name=\"Build\",\n        actions=[build_action]\n    )\n    ]\n)\n```\n\nThe default category of the CodeBuild Action is `Build`;\nif you want a `Test` Action instead,\noverride the `type` property:\n\n```python\n# project: codebuild.PipelineProject\n\nsource_output = codepipeline.Artifact()\ntest_action = codepipeline_actions.CodeBuildAction(\n    action_name=\"IntegrationTest\",\n    project=project,\n    input=source_output,\n    type=codepipeline_actions.CodeBuildActionType.TEST\n)\n```\n\n#### Multiple inputs and outputs\n\nWhen you want to have multiple inputs and/or outputs for a Project used in a\nPipeline, instead of using the `secondarySources` and `secondaryArtifacts`\nproperties of the `Project` class, you need to use the `extraInputs` and\n`outputs` properties of the CodeBuild CodePipeline\nActions. Example:\n\n```python\n# repository1: codecommit.Repository\n# repository2: codecommit.Repository\n\n# project: codebuild.PipelineProject\n\nsource_output1 = codepipeline.Artifact()\nsource_action1 = codepipeline_actions.CodeCommitSourceAction(\n    action_name=\"Source1\",\n    repository=repository1,\n    output=source_output1\n)\nsource_output2 = codepipeline.Artifact(\"source2\")\nsource_action2 = codepipeline_actions.CodeCommitSourceAction(\n    action_name=\"Source2\",\n    repository=repository2,\n    output=source_output2\n)\nbuild_action = codepipeline_actions.CodeBuildAction(\n    action_name=\"Build\",\n    project=project,\n    input=source_output1,\n    extra_inputs=[source_output2\n    ],\n    outputs=[\n        codepipeline.Artifact(\"artifact1\"),  # for better buildspec readability - see below\n        codepipeline.Artifact(\"artifact2\")\n    ]\n)\n```\n\n**Note**: when a CodeBuild Action in a Pipeline has more than one output, it\nonly uses the `secondary-artifacts` field of the buildspec, never the\nprimary output specification directly under `artifacts`. Because of that, it\npays to explicitly name all output artifacts of that Action, like we did\nabove, so that you know what name to use in the buildspec.\n\nExample buildspec for the above project:\n\n```python\nproject = codebuild.PipelineProject(self, \"MyProject\",\n    build_spec=codebuild.BuildSpec.from_object({\n        \"version\": \"0.2\",\n        \"phases\": {\n            \"build\": {\n                \"commands\": []\n            }\n        },\n        \"artifacts\": {\n            \"secondary-artifacts\": {\n                \"artifact1\": {},\n                \"artifact2\": {}\n            }\n        }\n    })\n)\n```\n\n#### Variables\n\nThe CodeBuild action emits variables.\nUnlike many other actions, the variables are not static,\nbut dynamic, defined in the buildspec,\nin the 'exported-variables' subsection of the 'env' section.\nExample:\n\n```python\n# later:\n# project: codebuild.PipelineProject\nsource_output = codepipeline.Artifact()\nbuild_action = codepipeline_actions.CodeBuildAction(\n    action_name=\"Build1\",\n    input=source_output,\n    project=codebuild.PipelineProject(self, \"Project\",\n        build_spec=codebuild.BuildSpec.from_object({\n            \"version\": \"0.2\",\n            \"env\": {\n                \"exported-variables\": [\"MY_VAR\"\n                ]\n            },\n            \"phases\": {\n                \"build\": {\n                    \"commands\": \"export MY_VAR=\\\"some value\\\"\"\n                }\n            }\n        })\n    ),\n    variables_namespace=\"MyNamespace\"\n)\ncodepipeline_actions.CodeBuildAction(\n    action_name=\"CodeBuild\",\n    project=project,\n    input=source_output,\n    environment_variables={\n        \"MyVar\": codebuild.BuildEnvironmentVariable(\n            value=build_action.variable(\"MY_VAR\")\n        )\n    }\n)\n```\n\n### Jenkins\n\nIn order to use Jenkins Actions in the Pipeline,\nyou first need to create a `JenkinsProvider`:\n\n```python\njenkins_provider = codepipeline_actions.JenkinsProvider(self, \"JenkinsProvider\",\n    provider_name=\"MyJenkinsProvider\",\n    server_url=\"http://my-jenkins.com:8080\",\n    version=\"2\"\n)\n```\n\nIf you've registered a Jenkins provider in a different CDK app,\nor outside the CDK (in the CodePipeline AWS Console, for example),\nyou can import it:\n\n```python\njenkins_provider = codepipeline_actions.JenkinsProvider.from_jenkins_provider_attributes(self, \"JenkinsProvider\",\n    provider_name=\"MyJenkinsProvider\",\n    server_url=\"http://my-jenkins.com:8080\",\n    version=\"2\"\n)\n```\n\nNote that a Jenkins provider\n(identified by the provider name-category(build/test)-version tuple)\nmust always be registered in the given account, in the given AWS region,\nbefore it can be used in CodePipeline.\n\nWith a `JenkinsProvider`,\nwe can create a Jenkins Action:\n\n```python\n# jenkins_provider: codepipeline_actions.JenkinsProvider\n\nbuild_action = codepipeline_actions.JenkinsAction(\n    action_name=\"JenkinsBuild\",\n    jenkins_provider=jenkins_provider,\n    project_name=\"MyProject\",\n    type=codepipeline_actions.JenkinsActionType.BUILD\n)\n```\n\n## Deploy\n\n### AWS CloudFormation\n\nThis module contains Actions that allows you to deploy to CloudFormation from AWS CodePipeline.\n\nFor example, the following code fragment defines a pipeline that automatically deploys a CloudFormation template\ndirectly from a CodeCommit repository, with a manual approval step in between to confirm the changes:\n\n```python\n# Source stage: read from repository\nrepo = codecommit.Repository(stack, \"TemplateRepo\",\n    repository_name=\"template-repo\"\n)\nsource_output = codepipeline.Artifact(\"SourceArtifact\")\nsource = cpactions.CodeCommitSourceAction(\n    action_name=\"Source\",\n    repository=repo,\n    output=source_output,\n    trigger=cpactions.CodeCommitTrigger.POLL\n)\nsource_stage = {\n    \"stage_name\": \"Source\",\n    \"actions\": [source]\n}\n\n# Deployment stage: create and deploy changeset with manual approval\nstack_name = \"OurStack\"\nchange_set_name = \"StagedChangeSet\"\n\nprod_stage = {\n    \"stage_name\": \"Deploy\",\n    \"actions\": [\n        cpactions.CloudFormationCreateReplaceChangeSetAction(\n            action_name=\"PrepareChanges\",\n            stack_name=stack_name,\n            change_set_name=change_set_name,\n            admin_permissions=True,\n            template_path=source_output.at_path(\"template.yaml\"),\n            run_order=1\n        ),\n        cpactions.ManualApprovalAction(\n            action_name=\"ApproveChanges\",\n            run_order=2\n        ),\n        cpactions.CloudFormationExecuteChangeSetAction(\n            action_name=\"ExecuteChanges\",\n            stack_name=stack_name,\n            change_set_name=change_set_name,\n            run_order=3\n        )\n    ]\n}\n\ncodepipeline.Pipeline(stack, \"Pipeline\",\n    stages=[source_stage, prod_stage\n    ]\n)\n```\n\nSee [the AWS documentation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/continuous-delivery-codepipeline.html)\nfor more details about using CloudFormation in CodePipeline.\n\n#### Actions for updating individual CloudFormation Stacks\n\nThis package contains the following CloudFormation actions:\n\n* **CloudFormationCreateUpdateStackAction** - Deploy a CloudFormation template directly from the pipeline. The indicated stack is created,\n  or updated if it already exists. If the stack is in a failure state, deployment will fail (unless `replaceOnFailure`\n  is set to `true`, in which case it will be destroyed and recreated).\n* **CloudFormationDeleteStackAction** - Delete the stack with the given name.\n* **CloudFormationCreateReplaceChangeSetAction** - Prepare a change set to be applied later. You will typically use change sets if you want\n  to manually verify the changes that are being staged, or if you want to separate the people (or system) preparing the\n  changes from the people (or system) applying the changes.\n* **CloudFormationExecuteChangeSetAction** - Execute a change set prepared previously.\n\n#### Actions for deploying CloudFormation StackSets to multiple accounts\n\nYou can use CloudFormation StackSets to deploy the same CloudFormation template to multiple\naccounts in a managed way. If you use AWS Organizations, StackSets can be deployed to\nall accounts in a particular Organizational Unit (OU), and even automatically to new\naccounts as soon as they are added to a particular OU. For more information, see\nthe [Working with StackSets](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/what-is-cfnstacksets.html)\nsection of the CloudFormation developer guide.\n\nThe actions available for updating StackSets are:\n\n* **CloudFormationDeployStackSetAction** - Create or update a CloudFormation StackSet directly from the pipeline, optionally\n  immediately create and update Stack Instances as well.\n* **CloudFormationDeployStackInstancesAction** - Update outdated Stack Instaces using the current version of the StackSet.\n\nHere's an example of using both of these actions:\n\n```python\n# pipeline: codepipeline.Pipeline\n# source_output: codepipeline.Artifact\n\n\npipeline.add_stage(\n    stage_name=\"DeployStackSets\",\n    actions=[\n        # First, update the StackSet itself with the newest template\n        codepipeline_actions.CloudFormationDeployStackSetAction(\n            action_name=\"UpdateStackSet\",\n            run_order=1,\n            stack_set_name=\"MyStackSet\",\n            template=codepipeline_actions.StackSetTemplate.from_artifact_path(source_output.at_path(\"template.yaml\")),\n\n            # Change this to 'StackSetDeploymentModel.organizations()' if you want to deploy to OUs\n            deployment_model=codepipeline_actions.StackSetDeploymentModel.self_managed(),\n            # This deploys to a set of accounts\n            stack_instances=codepipeline_actions.StackInstances.in_accounts([\"111111111111\"], [\"us-east-1\", \"eu-west-1\"])\n        ),\n\n        # Afterwards, update/create additional instances in other accounts\n        codepipeline_actions.CloudFormationDeployStackInstancesAction(\n            action_name=\"AddMoreInstances\",\n            run_order=2,\n            stack_set_name=\"MyStackSet\",\n            stack_instances=codepipeline_actions.StackInstances.in_accounts([\"222222222222\", \"333333333333\"], [\"us-east-1\", \"eu-west-1\"])\n        )\n    ]\n)\n```\n\n#### Lambda deployed through CodePipeline\n\nIf you want to deploy your Lambda through CodePipeline,\nand you don't use assets (for example, because your CDK code and Lambda code are separate),\nyou can use a special Lambda `Code` class, `CfnParametersCode`.\nNote that your Lambda must be in a different Stack than your Pipeline.\nThe Lambda itself will be deployed, alongside the entire Stack it belongs to,\nusing a CloudFormation CodePipeline Action. Example:\n\n```python\nlambda_stack = cdk.Stack(app, \"LambdaStack\")\nlambda_code = lambda_.Code.from_cfn_parameters()\nlambda_.Function(lambda_stack, \"Lambda\",\n    code=lambda_code,\n    handler=\"index.handler\",\n    runtime=lambda_.Runtime.NODEJS_14_X\n)\n# other resources that your Lambda needs, added to the lambdaStack...\n\npipeline_stack = cdk.Stack(app, \"PipelineStack\")\npipeline = codepipeline.Pipeline(pipeline_stack, \"Pipeline\")\n\n# add the source code repository containing this code to your Pipeline,\n# and the source code of the Lambda Function, if they're separate\ncdk_source_output = codepipeline.Artifact()\ncdk_source_action = codepipeline_actions.CodeCommitSourceAction(\n    repository=codecommit.Repository(pipeline_stack, \"CdkCodeRepo\",\n        repository_name=\"CdkCodeRepo\"\n    ),\n    action_name=\"CdkCode_Source\",\n    output=cdk_source_output\n)\nlambda_source_output = codepipeline.Artifact()\nlambda_source_action = codepipeline_actions.CodeCommitSourceAction(\n    repository=codecommit.Repository(pipeline_stack, \"LambdaCodeRepo\",\n        repository_name=\"LambdaCodeRepo\"\n    ),\n    action_name=\"LambdaCode_Source\",\n    output=lambda_source_output\n)\npipeline.add_stage(\n    stage_name=\"Source\",\n    actions=[cdk_source_action, lambda_source_action]\n)\n\n# synthesize the Lambda CDK template, using CodeBuild\n# the below values are just examples, assuming your CDK code is in TypeScript/JavaScript -\n# adjust the build environment and/or commands accordingly\ncdk_build_project = codebuild.Project(pipeline_stack, \"CdkBuildProject\",\n    environment=codebuild.BuildEnvironment(\n        build_image=codebuild.LinuxBuildImage.UBUNTU_14_04_NODEJS_10_1_0\n    ),\n    build_spec=codebuild.BuildSpec.from_object({\n        \"version\": \"0.2\",\n        \"phases\": {\n            \"install\": {\n                \"commands\": \"npm install\"\n            },\n            \"build\": {\n                \"commands\": [\"npm run build\", \"npm run cdk synth LambdaStack -- -o .\"\n                ]\n            }\n        },\n        \"artifacts\": {\n            \"files\": \"LambdaStack.template.yaml\"\n        }\n    })\n)\ncdk_build_output = codepipeline.Artifact()\ncdk_build_action = codepipeline_actions.CodeBuildAction(\n    action_name=\"CDK_Build\",\n    project=cdk_build_project,\n    input=cdk_source_output,\n    outputs=[cdk_build_output]\n)\n\n# build your Lambda code, using CodeBuild\n# again, this example assumes your Lambda is written in TypeScript/JavaScript -\n# make sure to adjust the build environment and/or commands if they don't match your specific situation\nlambda_build_project = codebuild.Project(pipeline_stack, \"LambdaBuildProject\",\n    environment=codebuild.BuildEnvironment(\n        build_image=codebuild.LinuxBuildImage.UBUNTU_14_04_NODEJS_10_1_0\n    ),\n    build_spec=codebuild.BuildSpec.from_object({\n        \"version\": \"0.2\",\n        \"phases\": {\n            \"install\": {\n                \"commands\": \"npm install\"\n            },\n            \"build\": {\n                \"commands\": \"npm run build\"\n            }\n        },\n        \"artifacts\": {\n            \"files\": [\"index.js\", \"node_modules/**/*\"\n            ]\n        }\n    })\n)\nlambda_build_output = codepipeline.Artifact()\nlambda_build_action = codepipeline_actions.CodeBuildAction(\n    action_name=\"Lambda_Build\",\n    project=lambda_build_project,\n    input=lambda_source_output,\n    outputs=[lambda_build_output]\n)\n\npipeline.add_stage(\n    stage_name=\"Build\",\n    actions=[cdk_build_action, lambda_build_action]\n)\n\n# finally, deploy your Lambda Stack\npipeline.add_stage(\n    stage_name=\"Deploy\",\n    actions=[\n        codepipeline_actions.CloudFormationCreateUpdateStackAction(\n            action_name=\"Lambda_CFN_Deploy\",\n            template_path=cdk_build_output.at_path(\"LambdaStack.template.yaml\"),\n            stack_name=\"LambdaStackDeployedName\",\n            admin_permissions=True,\n            parameter_overrides=lambda_code.assign(lambda_build_output.s3_location),\n            extra_inputs=[lambda_build_output\n            ]\n        )\n    ]\n)\n```\n\n#### Cross-account actions\n\nIf you want to update stacks in a different account,\npass the `account` property when creating the action:\n\n```python\nsource_output = codepipeline.Artifact()\ncodepipeline_actions.CloudFormationCreateUpdateStackAction(\n    action_name=\"CloudFormationCreateUpdate\",\n    stack_name=\"MyStackName\",\n    admin_permissions=True,\n    template_path=source_output.at_path(\"template.yaml\"),\n    account=\"123456789012\"\n)\n```\n\nThis will create a new stack, called `<PipelineStackName>-support-123456789012`, in your `App`,\nthat will contain the role that the pipeline will assume in account 123456789012 before executing this action.\nThis support stack will automatically be deployed before the stack containing the pipeline.\n\nYou can also pass a role explicitly when creating the action -\nin that case, the `account` property is ignored,\nand the action will operate in the same account the role belongs to:\n\n```python\nfrom aws_cdk.core import PhysicalName\n\n# in stack for account 123456789012...\n# other_account_stack: Stack\n\naction_role = iam.Role(other_account_stack, \"ActionRole\",\n    assumed_by=iam.AccountPrincipal(\"123456789012\"),\n    # the role has to have a physical name set\n    role_name=PhysicalName.GENERATE_IF_NEEDED\n)\n\n# in the pipeline stack...\nsource_output = codepipeline.Artifact()\ncodepipeline_actions.CloudFormationCreateUpdateStackAction(\n    action_name=\"CloudFormationCreateUpdate\",\n    stack_name=\"MyStackName\",\n    admin_permissions=True,\n    template_path=source_output.at_path(\"template.yaml\"),\n    role=action_role\n)\n```\n\n### AWS CodeDeploy\n\n#### Server deployments\n\nTo use CodeDeploy for EC2/on-premise deployments in a Pipeline:\n\n```python\n# deployment_group: codedeploy.ServerDeploymentGroup\npipeline = codepipeline.Pipeline(self, \"MyPipeline\",\n    pipeline_name=\"MyPipeline\"\n)\n\n# add the source and build Stages to the Pipeline...\nbuild_output = codepipeline.Artifact()\ndeploy_action = codepipeline_actions.CodeDeployServerDeployAction(\n    action_name=\"CodeDeploy\",\n    input=build_output,\n    deployment_group=deployment_group\n)\npipeline.add_stage(\n    stage_name=\"Deploy\",\n    actions=[deploy_action]\n)\n```\n\n##### Lambda deployments\n\nTo use CodeDeploy for blue-green Lambda deployments in a Pipeline:\n\n```python\nlambda_code = lambda_.Code.from_cfn_parameters()\nfunc = lambda_.Function(self, \"Lambda\",\n    code=lambda_code,\n    handler=\"index.handler\",\n    runtime=lambda_.Runtime.NODEJS_14_X\n)\n# used to make sure each CDK synthesis produces a different Version\nversion = func.current_version\nalias = lambda_.Alias(self, \"LambdaAlias\",\n    alias_name=\"Prod\",\n    version=version\n)\n\ncodedeploy.LambdaDeploymentGroup(self, \"DeploymentGroup\",\n    alias=alias,\n    deployment_config=codedeploy.LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE\n)\n```\n\nThen, you need to create your Pipeline Stack,\nwhere you will define your Pipeline,\nand deploy the `lambdaStack` using a CloudFormation CodePipeline Action\n(see above for a complete example).\n\n### ECS\n\nCodePipeline can deploy an ECS service.\nThe deploy Action receives one input Artifact which contains the [image definition file](https://docs.aws.amazon.com/codepipeline/latest/userguide/pipelines-create.html#pipelines-create-image-definitions):\n\n```python\nimport aws_cdk.aws_ecs as ecs\n\n# service: ecs.FargateService\n\npipeline = codepipeline.Pipeline(self, \"MyPipeline\")\nbuild_output = codepipeline.Artifact()\ndeploy_stage = pipeline.add_stage(\n    stage_name=\"Deploy\",\n    actions=[\n        codepipeline_actions.EcsDeployAction(\n            action_name=\"DeployAction\",\n            service=service,\n            # if your file is called imagedefinitions.json,\n            # use the `input` property,\n            # and leave out the `imageFile` property\n            input=build_output,\n            # if your file name is _not_ imagedefinitions.json,\n            # use the `imageFile` property,\n            # and leave out the `input` property\n            image_file=build_output.at_path(\"imageDef.json\"),\n            deployment_timeout=Duration.minutes(60)\n        )\n    ]\n)\n```\n\n#### Deploying ECS applications to existing services\n\nCodePipeline can deploy to an existing ECS service which uses the\n[ECS service ARN format that contains the Cluster name](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-account-settings.html#ecs-resource-ids).\nThis also works if the service is in a different account and/or region than the pipeline:\n\n```python\nimport aws_cdk.aws_ecs as ecs\n\n\nservice = ecs.BaseService.from_service_arn_with_cluster(self, \"EcsService\", \"arn:aws:ecs:us-east-1:123456789012:service/myClusterName/myServiceName\")\npipeline = codepipeline.Pipeline(self, \"MyPipeline\")\nbuild_output = codepipeline.Artifact()\n# add source and build stages to the pipeline as usual...\ndeploy_stage = pipeline.add_stage(\n    stage_name=\"Deploy\",\n    actions=[\n        codepipeline_actions.EcsDeployAction(\n            action_name=\"DeployAction\",\n            service=service,\n            input=build_output\n        )\n    ]\n)\n```\n\nWhen deploying across accounts, especially in a CDK Pipelines self-mutating pipeline,\nit is recommended to provide the `role` property to the `EcsDeployAction`.\nThe Role will need to have permissions assigned to it for ECS deployment.\nSee [the CodePipeline documentation](https://docs.aws.amazon.com/codepipeline/latest/userguide/how-to-custom-role.html#how-to-update-role-new-services)\nfor the permissions needed.\n\n#### Deploying ECS applications stored in a separate source code repository\n\nThe idiomatic CDK way of deploying an ECS application is to have your Dockerfiles and your CDK code in the same source code repository,\nleveraging [Docker Assets](https://docs.aws.amazon.com/cdk/latest/guide/assets.html#assets_types_docker),\nand use the [CDK Pipelines module](https://docs.aws.amazon.com/cdk/api/latest/docs/pipelines-readme.html).\n\nHowever, if you want to deploy a Docker application whose source code is kept in a separate version control repository than the CDK code,\nyou can use the `TagParameterContainerImage` class from the ECS module.\nHere's an example:\n\n```python\n#\n# This is the Stack containing a simple ECS Service that uses the provided ContainerImage.\n#\nclass EcsAppStack(cdk.Stack):\n    def __init__(self, scope, id, *, image, description=None, env=None, stackName=None, tags=None, synthesizer=None, terminationProtection=None, analyticsReporting=None):\n        super().__init__(scope, id, image=image, description=description, env=env, stackName=stackName, tags=tags, synthesizer=synthesizer, terminationProtection=terminationProtection, analyticsReporting=analyticsReporting)\n\n        task_definition = ecs.TaskDefinition(self, \"TaskDefinition\",\n            compatibility=ecs.Compatibility.FARGATE,\n            cpu=\"1024\",\n            memory_mi_b=\"2048\"\n        )\n        task_definition.add_container(\"AppContainer\",\n            image=image\n        )\n        ecs.FargateService(self, \"EcsService\",\n            task_definition=task_definition,\n            cluster=ecs.Cluster(self, \"Cluster\",\n                vpc=ec2.Vpc(self, \"Vpc\",\n                    max_azs=1\n                )\n            )\n        )\n\n#\n# This is the Stack containing the CodePipeline definition that deploys an ECS Service.\n#\nclass PipelineStack(cdk.Stack):\n\n    def __init__(self, scope, id, *, description=None, env=None, stackName=None, tags=None, synthesizer=None, terminationProtection=None, analyticsReporting=None):\n        super().__init__(scope, id, description=description, env=env, stackName=stackName, tags=tags, synthesizer=synthesizer, terminationProtection=terminationProtection, analyticsReporting=analyticsReporting)\n\n        # ********* ECS part ****************\n\n        # this is the ECR repository where the built Docker image will be pushed\n        app_ecr_repo = ecr.Repository(self, \"EcsDeployRepository\")\n        # the build that creates the Docker image, and pushes it to the ECR repo\n        app_code_docker_build = codebuild.PipelineProject(self, \"AppCodeDockerImageBuildAndPushProject\",\n            environment=codebuild.BuildEnvironment(\n                # we need to run Docker\n                privileged=True\n            ),\n            build_spec=codebuild.BuildSpec.from_object({\n                \"version\": \"0.2\",\n                \"phases\": {\n                    \"build\": {\n                        \"commands\": [\"$(aws ecr get-login --region $AWS_DEFAULT_REGION --no-include-email)\", \"docker build -t $REPOSITORY_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION .\"\n                        ]\n                    },\n                    \"post_build\": {\n                        \"commands\": [\"docker push $REPOSITORY_URI:$CODEBUILD_RESOLVED_SOURCE_VERSION\", \"export imageTag=$CODEBUILD_RESOLVED_SOURCE_VERSION\"\n                        ]\n                    }\n                },\n                \"env\": {\n                    # save the imageTag environment variable as a CodePipeline Variable\n                    \"exported-variables\": [\"imageTag\"\n                    ]\n                }\n            }),\n            environment_variables={\n                \"REPOSITORY_URI\": codebuild.BuildEnvironmentVariable(\n                    value=app_ecr_repo.repository_uri\n                )\n            }\n        )\n        # needed for `docker push`\n        app_ecr_repo.grant_pull_push(app_code_docker_build)\n        # create the ContainerImage used for the ECS application Stack\n        self.tag_parameter_container_image = ecs.TagParameterContainerImage(app_ecr_repo)\n\n        cdk_code_build = codebuild.PipelineProject(self, \"CdkCodeBuildProject\",\n            build_spec=codebuild.BuildSpec.from_object({\n                \"version\": \"0.2\",\n                \"phases\": {\n                    \"install\": {\n                        \"commands\": [\"npm install\"\n                        ]\n                    },\n                    \"build\": {\n                        \"commands\": [\"npx cdk synth --verbose\"\n                        ]\n                    }\n                },\n                \"artifacts\": {\n                    # store the entire Cloud Assembly as the output artifact\n                    \"base-directory\": \"cdk.out\",\n                    \"files\": \"**/*\"\n                }\n            })\n        )\n\n        # ********* Pipeline part ****************\n\n        app_code_source_output = codepipeline.Artifact()\n        cdk_code_source_output = codepipeline.Artifact()\n        cdk_code_build_output = codepipeline.Artifact()\n        app_code_build_action = codepipeline_actions.CodeBuildAction(\n            action_name=\"AppCodeDockerImageBuildAndPush\",\n            project=app_code_docker_build,\n            input=app_code_source_output\n        )\n        codepipeline.Pipeline(self, \"CodePipelineDeployingEcsApplication\",\n            artifact_bucket=s3.Bucket(self, \"ArtifactBucket\",\n                removal_policy=cdk.RemovalPolicy.DESTROY\n            ),\n            stages=[codepipeline.StageProps(\n                stage_name=\"Source\",\n                actions=[\n                    # this is the Action that takes the source of your application code\n                    codepipeline_actions.CodeCommitSourceAction(\n                        action_name=\"AppCodeSource\",\n                        repository=codecommit.Repository(self, \"AppCodeSourceRepository\", repository_name=\"AppCodeSourceRepository\"),\n                        output=app_code_source_output\n                    ),\n                    # this is the Action that takes the source of your CDK code\n                    # (which would probably include this Pipeline code as well)\n                    codepipeline_actions.CodeCommitSourceAction(\n                        action_name=\"CdkCodeSource\",\n                        repository=codecommit.Repository(self, \"CdkCodeSourceRepository\", repository_name=\"CdkCodeSourceRepository\"),\n                        output=cdk_code_source_output\n                    )\n                ]\n            ), codepipeline.StageProps(\n                stage_name=\"Build\",\n                actions=[app_code_build_action,\n                    codepipeline_actions.CodeBuildAction(\n                        action_name=\"CdkCodeBuildAndSynth\",\n                        project=cdk_code_build,\n                        input=cdk_code_source_output,\n                        outputs=[cdk_code_build_output]\n                    )\n                ]\n            ), codepipeline.StageProps(\n                stage_name=\"Deploy\",\n                actions=[\n                    codepipeline_actions.CloudFormationCreateUpdateStackAction(\n                        action_name=\"CFN_Deploy\",\n                        stack_name=\"SampleEcsStackDeployedFromCodePipeline\",\n                        # this name has to be the same name as used below in the CDK code for the application Stack\n                        template_path=cdk_code_build_output.at_path(\"EcsStackDeployedInPipeline.template.json\"),\n                        admin_permissions=True,\n                        parameter_overrides={\n                            # read the tag pushed to the ECR repository from the CodePipeline Variable saved by the application build step,\n                            # and pass it as the CloudFormation Parameter for the tag\n                            \"self.tag_parameter_container_image.tag_parameter_name\": app_code_build_action.variable(\"imageTag\")\n                        }\n                    )\n                ]\n            )\n            ]\n        )\n\napp = cdk.App()\n\n# the CodePipeline Stack needs to be created first\npipeline_stack = PipelineStack(app, \"aws-cdk-pipeline-ecs-separate-sources\")\n# we supply the image to the ECS application Stack from the CodePipeline Stack\nEcsAppStack(app, \"EcsStackDeployedInPipeline\",\n    image=pipeline_stack.tag_parameter_container_image\n)\n```\n\n### AWS S3 Deployment\n\nTo use an S3 Bucket as a deployment target in CodePipeline:\n\n```python\nsource_output = codepipeline.Artifact()\ntarget_bucket = s3.Bucket(self, \"MyBucket\")\n\npipeline = codepipeline.Pipeline(self, \"MyPipeline\")\ndeploy_action = codepipeline_actions.S3DeployAction(\n    action_name=\"S3Deploy\",\n    bucket=target_bucket,\n    input=source_output\n)\ndeploy_stage = pipeline.add_stage(\n    stage_name=\"Deploy\",\n    actions=[deploy_action]\n)\n```\n\n#### Invalidating the CloudFront cache when deploying to S3\n\nThere is currently no native support in CodePipeline for invalidating a CloudFront cache after deployment.\nOne workaround is to add another build step after the deploy step,\nand use the AWS CLI to invalidate the cache:\n\n```python\n# Create a Cloudfront Web Distribution\nimport aws_cdk.aws_cloudfront as cloudfront\n# distribution: cloudfront.Distribution\n\n\n# Create the build project that will invalidate the cache\ninvalidate_build_project = codebuild.PipelineProject(self, \"InvalidateProject\",\n    build_spec=codebuild.BuildSpec.from_object({\n        \"version\": \"0.2\",\n        \"phases\": {\n            \"build\": {\n                \"commands\": [\"aws cloudfront create-invalidation --distribution-id ${CLOUDFRONT_ID} --paths \\\"/*\\\"\"\n                ]\n            }\n        }\n    }),\n    environment_variables={\n        \"CLOUDFRONT_ID\": codebuild.BuildEnvironmentVariable(value=distribution.distribution_id)\n    }\n)\n\n# Add Cloudfront invalidation permissions to the project\ndistribution_arn = f\"arn:aws:cloudfront::{this.account}:distribution/{distribution.distributionId}\"\ninvalidate_build_project.add_to_role_policy(iam.PolicyStatement(\n    resources=[distribution_arn],\n    actions=[\"cloudfront:CreateInvalidation\"\n    ]\n))\n\n# Create the pipeline (here only the S3 deploy and Invalidate cache build)\ndeploy_bucket = s3.Bucket(self, \"DeployBucket\")\ndeploy_input = codepipeline.Artifact()\ncodepipeline.Pipeline(self, \"Pipeline\",\n    stages=[codepipeline.StageProps(\n        stage_name=\"Deploy\",\n        actions=[\n            codepipeline_actions.S3DeployAction(\n                action_name=\"S3Deploy\",\n                bucket=deploy_bucket,\n                input=deploy_input,\n                run_order=1\n            ),\n            codepipeline_actions.CodeBuildAction(\n                action_name=\"InvalidateCache\",\n                project=invalidate_build_project,\n                input=deploy_input,\n                run_order=2\n            )\n        ]\n    )\n    ]\n)\n```\n\n### Alexa Skill\n\nYou can deploy to Alexa using CodePipeline with the following Action:\n\n```python\n# Read the secrets from ParameterStore\nclient_id = SecretValue.secrets_manager(\"AlexaClientId\")\nclient_secret = SecretValue.secrets_manager(\"AlexaClientSecret\")\nrefresh_token = SecretValue.secrets_manager(\"AlexaRefreshToken\")\n\n# Add deploy action\nsource_output = codepipeline.Artifact()\ncodepipeline_actions.AlexaSkillDeployAction(\n    action_name=\"DeploySkill\",\n    run_order=1,\n    input=source_output,\n    client_id=client_id.to_string(),\n    client_secret=client_secret,\n    refresh_token=refresh_token,\n    skill_id=\"amzn1.ask.skill.12345678-1234-1234-1234-123456789012\"\n)\n```\n\nIf you need manifest overrides you can specify them as `parameterOverridesArtifact` in the action:\n\n```python\n# Deploy some CFN change set and store output\nexecute_output = codepipeline.Artifact(\"CloudFormation\")\nexecute_change_set_action = codepipeline_actions.CloudFormationExecuteChangeSetAction(\n    action_name=\"ExecuteChangesTest\",\n    run_order=2,\n    stack_name=\"MyStack\",\n    change_set_name=\"MyChangeSet\",\n    output_file_name=\"overrides.json\",\n    output=execute_output\n)\n\n# Provide CFN output as manifest overrides\nclient_id = SecretValue.secrets_manager(\"AlexaClientId\")\nclient_secret = SecretValue.secrets_manager(\"AlexaClientSecret\")\nrefresh_token = SecretValue.secrets_manager(\"AlexaRefreshToken\")\nsource_output = codepipeline.Artifact()\ncodepipeline_actions.AlexaSkillDeployAction(\n    action_name=\"DeploySkill\",\n    run_order=1,\n    input=source_output,\n    parameter_overrides_artifact=execute_output,\n    client_id=client_id.to_string(),\n    client_secret=client_secret,\n    refresh_token=refresh_token,\n    skill_id=\"amzn1.ask.skill.12345678-1234-1234-1234-123456789012\"\n)\n```\n\n### AWS Service Catalog\n\nYou can deploy a CloudFormation template to an existing Service Catalog product with the following Action:\n\n```python\ncdk_build_output = codepipeline.Artifact()\nservice_catalog_deploy_action = codepipeline_actions.ServiceCatalogDeployActionBeta1(\n    action_name=\"ServiceCatalogDeploy\",\n    template_path=cdk_build_output.at_path(\"Sample.template.json\"),\n    product_version_name=\"Version - \" + Date.now.to_string,\n    product_version_description=\"This is a version from the pipeline with a new description.\",\n    product_id=\"prod-XXXXXXXX\"\n)\n```\n\n## Approve & invoke\n\n### Manual approval Action\n\nThis package contains an Action that stops the Pipeline until someone manually clicks the approve button:\n\n```python\nimport aws_cdk.aws_sns as sns\n\n\npipeline = codepipeline.Pipeline(self, \"MyPipeline\")\napprove_stage = pipeline.add_stage(stage_name=\"Approve\")\nmanual_approval_action = codepipeline_actions.ManualApprovalAction(\n    action_name=\"Approve\",\n    notification_topic=sns.Topic(self, \"Topic\"),  # optional\n    notify_emails=[\"some_email@example.com\"\n    ],  # optional\n    additional_information=\"additional info\"\n)\napprove_stage.add_action(manual_approval_action)\n```\n\nIf the `notificationTopic` has not been provided,\nbut `notifyEmails` were,\na new SNS Topic will be created\n(and accessible through the `notificationTopic` property of the Action).\n\nIf you want to grant a principal permissions to approve the changes,\nyou can invoke the method `grantManualApproval` passing it a `IGrantable`:\n\n```python\npipeline = codepipeline.Pipeline(self, \"MyPipeline\")\napprove_stage = pipeline.add_stage(stage_name=\"Approve\")\nmanual_approval_action = codepipeline_actions.ManualApprovalAction(\n    action_name=\"Approve\"\n)\napprove_stage.add_action(manual_approval_action)\n\nrole = iam.Role.from_role_arn(self, \"Admin\", Arn.format(ArnComponents(service=\"iam\", resource=\"role\", resource_name=\"Admin\"), self))\nmanual_approval_action.grant_manual_approval(role)\n```\n\n### AWS Lambda\n\nThis module contains an Action that allows you to invoke a Lambda function in a Pipeline:\n\n```python\n# fn: lambda.Function\n\npipeline = codepipeline.Pipeline(self, \"MyPipeline\")\nlambda_action = codepipeline_actions.LambdaInvokeAction(\n    action_name=\"Lambda\",\n    lambda_=fn\n)\npipeline.add_stage(\n    stage_name=\"Lambda\",\n    actions=[lambda_action]\n)\n```\n\nThe Lambda Action can have up to 5 inputs,\nand up to 5 outputs:\n\n```python\n# fn: lambda.Function\n\nsource_output = codepipeline.Artifact()\nbuild_output = codepipeline.Artifact()\nlambda_action = codepipeline_actions.LambdaInvokeAction(\n    action_name=\"Lambda\",\n    inputs=[source_output, build_output\n    ],\n    outputs=[\n        codepipeline.Artifact(\"Out1\"),\n        codepipeline.Artifact(\"Out2\")\n    ],\n    lambda_=fn\n)\n```\n\nThe Lambda Action supports custom user parameters that pipeline\nwill pass to the Lambda function:\n\n```python\n# fn: lambda.Function\n\n\npipeline = codepipeline.Pipeline(self, \"MyPipeline\")\nlambda_action = codepipeline_actions.LambdaInvokeAction(\n    action_name=\"Lambda\",\n    lambda_=fn,\n    user_parameters={\n        \"foo\": \"bar\",\n        \"baz\": \"qux\"\n    },\n    # OR\n    user_parameters_string=\"my-parameter-string\"\n)\n```\n\nThe Lambda invoke action emits variables.\nUnlike many other actions, the variables are not static,\nbut dynamic, defined by the function calling the `PutJobSuccessResult`\nAPI with the `outputVariables` property filled with the map of variables\nExample:\n\n```python\n# later:\n# project: codebuild.PipelineProject\nlambda_invoke_action = codepipeline_actions.LambdaInvokeAction(\n    action_name=\"Lambda\",\n    lambda_=lambda_.Function(self, \"Func\",\n        runtime=lambda_.Runtime.NODEJS_14_X,\n        handler=\"index.handler\",\n        code=lambda_.Code.from_inline(\"\"\"\n                    const AWS = require('aws-sdk');\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                        }).promise();\n                    }\n                \"\"\")\n    ),\n    variables_namespace=\"MyNamespace\"\n)\nsource_output = codepipeline.Artifact()\ncodepipeline_actions.CodeBuildAction(\n    action_name=\"CodeBuild\",\n    project=project,\n    input=source_output,\n    environment_variables={\n        \"MyVar\": codebuild.BuildEnvironmentVariable(\n            value=lambda_invoke_action.variable(\"MY_VAR\")\n        )\n    }\n)\n```\n\nSee [the AWS documentation](https://docs.aws.amazon.com/codepipeline/latest/userguide/actions-invoke-lambda-function.html)\non how to write a Lambda function invoked from CodePipeline.\n\n### AWS Step Functions\n\nThis module contains an Action that allows you to invoke a Step Function in a Pipeline:\n\n```python\nimport aws_cdk.aws_stepfunctions as stepfunctions\n\npipeline = codepipeline.Pipeline(self, \"MyPipeline\")\nstart_state = stepfunctions.Pass(self, \"StartState\")\nsimple_state_machine = stepfunctions.StateMachine(self, \"SimpleStateMachine\",\n    definition=start_state\n)\nstep_function_action = codepipeline_actions.StepFunctionInvokeAction(\n    action_name=\"Invoke\",\n    state_machine=simple_state_machine,\n    state_machine_input=codepipeline_actions.StateMachineInput.literal({\"IsHelloWorldExample\": True})\n)\npipeline.add_stage(\n    stage_name=\"StepFunctions\",\n    actions=[step_function_action]\n)\n```\n\nThe `StateMachineInput` can be created with one of 2 static factory methods:\n`literal`, which takes an arbitrary map as its only argument, or `filePath`:\n\n```python\nimport aws_cdk.aws_stepfunctions as stepfunctions\n\n\npipeline = codepipeline.Pipeline(self, \"MyPipeline\")\ninput_artifact = codepipeline.Artifact()\nstart_state = stepfunctions.Pass(self, \"StartState\")\nsimple_state_machine = stepfunctions.StateMachine(self, \"SimpleStateMachine\",\n    definition=start_state\n)\nstep_function_action = codepipeline_actions.StepFunctionInvokeAction(\n    action_name=\"Invoke\",\n    state_machine=simple_state_machine,\n    state_machine_input=codepipeline_actions.StateMachineInput.file_path(input_artifact.at_path(\"assets/input.json\"))\n)\npipeline.add_stage(\n    stage_name=\"StepFunctions\",\n    actions=[step_function_action]\n)\n```\n\nSee [the AWS documentation](https://docs.aws.amazon.com/codepipeline/latest/userguide/action-reference-StepFunctions.html)\nfor information on Action structure reference.\n\n\n",
    "bugtrack_url": null,
    "license": "Apache-2.0",
    "summary": "Concrete Actions for AWS Code Pipeline",
    "version": "1.203.0",
    "project_urls": {
        "Homepage": "https://github.com/aws/aws-cdk",
        "Source": "https://github.com/aws/aws-cdk.git"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "6743128c2f1892cc315f2ca0b9531a1f0273486e410fb4fb24d5b2ae0dadd11e",
                "md5": "5c7b12467e4ac386f416ec16e80c8d1e",
                "sha256": "3c3d657b7b0d7cdd40f33190e50cae8d6924f22efb5da9c7e9f166f001579038"
            },
            "downloads": -1,
            "filename": "aws_cdk.aws_codepipeline_actions-1.203.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "5c7b12467e4ac386f416ec16e80c8d1e",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "~=3.7",
            "size": 371300,
            "upload_time": "2023-05-31T22:53:44",
            "upload_time_iso_8601": "2023-05-31T22:53:44.641074Z",
            "url": "https://files.pythonhosted.org/packages/67/43/128c2f1892cc315f2ca0b9531a1f0273486e410fb4fb24d5b2ae0dadd11e/aws_cdk.aws_codepipeline_actions-1.203.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "3a721122f9c098129d9c2ce7f20debfde7dbb7ea4a60dc33d4e78213a571d127",
                "md5": "db1540c2a93ab6e34f16294fc2c377c0",
                "sha256": "a62651c3bf3b5fd38a2e42bdfa72bcda4197a063e5d03af4f49faf54b2ef8e71"
            },
            "downloads": -1,
            "filename": "aws-cdk.aws-codepipeline-actions-1.203.0.tar.gz",
            "has_sig": false,
            "md5_digest": "db1540c2a93ab6e34f16294fc2c377c0",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "~=3.7",
            "size": 392914,
            "upload_time": "2023-05-31T23:01:28",
            "upload_time_iso_8601": "2023-05-31T23:01:28.699514Z",
            "url": "https://files.pythonhosted.org/packages/3a/72/1122f9c098129d9c2ce7f20debfde7dbb7ea4a60dc33d4e78213a571d127/aws-cdk.aws-codepipeline-actions-1.203.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-05-31 23:01:28",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "aws",
    "github_project": "aws-cdk",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "aws-cdk.aws-codepipeline-actions"
}
        
Elapsed time: 0.50152s