

Amazon CodeCatalyst is no longer open to new customers. Existing customers can continue to use the service as normal. For more information, see [How to migrate from CodeCatalyst](migration.md).

# Deploying with workflows
<a name="deploy"></a>



Using [CodeCatalyst workflows](workflow.md), you can deploy applications and other resources to various targets such as Amazon ECS, AWS Lambda, and more. 

## How do I deploy an application?
<a name="deploy-concepts"></a>

To deploy an application or resource through CodeCatalyst, you first create a workflow, and then specify a deploy action inside of it. A *deploy action* is a workflow building block that defines *what* you want to deploy, *where* you want to deploy it, and *how* you want to deploy it (for example, using a blue/green scheme). You add a deploy action to your workflow using the CodeCatalyst console's visual editor, or YAML editor.

The high-level steps to deploy an application or resource are as follows.

**To deploy an application (high-level tasks)**

1. In your CodeCatalyst project, you **add source code** for an application you want to deploy. For more information, see [Storing source code in repositories for a project in CodeCatalyst](source-repositories.md).

1. In your CodeCatalyst project, you **add an environment** that defines the target AWS account and optional Amazon Virtual Private Cloud (VPC) that you want to deploy to. For more information, see [Deploying into AWS accounts and VPCs](deploy-environments.md).

1. In your CodeCatalyst project, you **create a workflow**. The workflow is where you define how to build, test, and deploy your application. For more information, see [Getting started with workflows](workflows-getting-started.md).

1. In the workflow, you **add a trigger**, a **build action**, and optionally, a **test action**. For more information, see [Starting a workflow run automatically using triggers](workflows-add-trigger.md), [Adding the build action](build-add-action.md), and [Adding the test action](test-add-action.md).

1. In the workflow, you **add a deploy action**. You can choose from several CodeCatalyst-provided deploy actions to your application to different targets, such as Amazon ECS. (You can also use a build action or a GitHub Action to deploy your application. For more information about the build action and GitHub Actions, see [Alternatives to deploy actions](#deploy-concepts-alternatives).)

1. You **start the workflow** either manually or automatically through a trigger. The workflow runs the build, test, and deploy actions in sequence to deploy your application and resources to the target. For more information, see [Starting a workflow run manually](workflows-manually-start.md).

## List of deploy actions
<a name="deploy-concepts-action-supported"></a>

The following deploy actions are available:
+ Deploy CloudFormation stack – This action creates a CloudFormation stack in AWS based on an [CloudFormation template](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-specification.html) or [AWS Serverless Application Model template](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-guide.html) that you provide. For more information, see [Deploying an CloudFormation stack](deploy-action-cfn.md).
+ Deploy to Amazon ECS – This action registers a [task definition](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html#welcome-task-definitions) file that you provide. For more information, see [Deploying to Amazon ECS with a workflow](deploy-action-ecs.md).
+ Deploy to Kubernetes cluster – This action deploys an application to an Amazon Elastic Kubernetes Service cluster. For more information, see [Deploying to Amazon EKS with a workflow](deploy-action-eks.md).
+ AWS CDK deploy – This action deploys an [AWS CDK app](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html#getting_started_concepts) into AWS. For more information, see [Deploying an AWS CDK app with a workflow](cdk-dep-action.md).

**Note**  
There are other CodeCatalyst actions that can deploy resources; however, they are not considered *deploy* actions because their deployment information doesn't appear on the **Environments** page. To learn more about the **Environments** page and viewing deployments, see [Deploying into AWS accounts and VPCs](deploy-environments.md) and [Viewing deployment information](deploy-view-deployment-info.md).

## Benefits of deploy actions
<a name="deploy-concepts-why-use"></a>

Using deploy actions within a workflow has the following benefits:
+ **Deployment history** – View a history of your deployments to help manage and communicate changes in your deployed software. 
+ **Traceability** – Track the status of your deployments through the CodeCatalyst console, and see when and where each application revision was deployed.
+ **Rollbacks** – Roll back deployments automatically if there are errors. You can also configure alarms to activate deployment rollbacks.
+ **Monitoring** – Watch your deployment as it progresses through the various stages of your workflow.
+ **Integration with other CodeCatalyst features** – Store source code and then build, test, and deploy it, all from one application.

## Alternatives to deploy actions
<a name="deploy-concepts-alternatives"></a>

You don't have to use deploy actions, although they are recommended because they offer the benefits outlined in the preceding section. Instead, you can use the following [CodeCatalyst actions](workflows-actions.md#workflows-actions-types-cc) :
+ A **build** action.

  Typically, you use build actions if you want to deploy to a target for which a corresponding deploy action does not exist, or if you want more control over the deployment procedure. For more information about using build actions to deploy resources, see [Building with workflows](build-workflow-actions.md).
+ A **GitHub Action**.

  You can use a [GitHub Action](workflows-actions.md#workflows-actions-types-github) inside a CodeCatalyst workflow to deploy applications and resources (instead of a CodeCatalyst action). For information about how to use GitHub Actions inside a CodeCatalyst workflow, see [Integrating with GitHub Actions](integrations-github-actions.md)

You can also use the following AWS services to deploy your application, if you don't want to use a CodeCatalyst workflow to do so:
+ AWS CodeDeploy – see [What is CodeDeploy?](https://docs.aws.amazon.com/codedeploy/latest/userguide/welcome.html)
+ AWS CodeBuild and AWS CodePipeline – see [What is AWS CodeBuild?](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html) and [What is AWS CodePipeline?](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)
+ CloudFormation – see [What is CloudFormation?](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)

Use CodeDeploy, CodeBuild, CodePipeline, and CloudFormation services for complex, enterprise deployments.

**Topics**
+ [How do I deploy an application?](#deploy-concepts)
+ [List of deploy actions](#deploy-concepts-action-supported)
+ [Benefits of deploy actions](#deploy-concepts-why-use)
+ [Alternatives to deploy actions](#deploy-concepts-alternatives)
+ [Deploying to Amazon ECS with a workflow](deploy-action-ecs.md)
+ [Deploying to Amazon EKS with a workflow](deploy-action-eks.md)
+ [Deploying an CloudFormation stack](deploy-action-cfn.md)
+ [Deploying an AWS CDK app with a workflow](cdk-dep-action.md)
+ [Bootstrapping an AWS CDK app with a workflow](cdk-boot-action.md)
+ [Publishing files to Amazon S3 with a workflow](s3-pub-action.md)
+ [Deploying into AWS accounts and VPCs](deploy-environments.md)
+ [Displaying the app URL in the workflow diagram](deploy-app-url.md)
+ [Removing a deployment target](deploy-remove-target.md)
+ [Tracking deployment status by commit](track-changes.md)
+ [Viewing the deployment logs](deploy-deployment-logs.md)
+ [Viewing deployment information](deploy-view-deployment-info.md)

# Deploying to Amazon ECS with a workflow
<a name="deploy-action-ecs"></a>

This section describes how to deploy a containerized application into an Amazon Elastic Container Service cluster using a CodeCatalyst workflow. To accomplish this, you must add the **Deploy to Amazon ECS** action to your workflow. This action registers a [task definition](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html#welcome-task-definitions) file that you provide. Upon registration, the task definition is instantiated by your [Amazon ECS service](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_services.html) running in your [Amazon ECS cluster](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html#welcome-clusters). "Instantiating a task definition" is equivalent to deploying an application into Amazon ECS.

To use this action, you must have an Amazon ECS cluster, service, and task definition file ready.

For more information about Amazon ECS, see the *Amazon Elastic Container Service Developer Guide*.

**Tip**  
For a tutorial that shows you how to use the **Deploy to Amazon ECS ** action, see [Tutorial: Deploy an application to Amazon ECS](deploy-tut-ecs.md).

**Tip**  
For a working example of the **Deploy to Amazon ECS** action, create a project with either the **Node.js API with AWS Fargate** or **Java API with AWS Fargate** blueprint. For more information, see [Creating a project with a blueprint](projects-create.md#projects-create-console-template).

**Topics**
+ [Runtime image used by the 'Deploy to Amazon ECS' action](#deploy-action-ecs-runtime)
+ [Tutorial: Deploy an application to Amazon ECS](deploy-tut-ecs.md)
+ [Adding the 'Deploy to Amazon ECS' action](deploy-action-ecs-adding.md)
+ ['Deploy to Amazon ECS' variables](deploy-action-ecs-variables.md)
+ ['Deploy to Amazon ECS' action YAML](deploy-action-ref-ecs.md)

## Runtime image used by the 'Deploy to Amazon ECS' action
<a name="deploy-action-ecs-runtime"></a>

The **Deploy to Amazon ECS** action runs on a [November 2022 image](build-images.md#build.previous-image). For more information, see [Active images](build-images.md#build-curated-images).

# Tutorial: Deploy an application to Amazon ECS
<a name="deploy-tut-ecs"></a>

In this tutorial, you learn how to deploy a serverless application into Amazon Elastic Container Service (Amazon ECS) using a workflow, Amazon ECS, and a few other AWS services. The deployed application is a simple Hello World website built on an Apache web server Docker image. The tutorial walks you through the required preparation work such as setting up a cluster, and then describes how to create a workflow to build and deploy the application.

**Tip**  
Instead of working your way through this tutorial, you can use a blueprint that does a complete Amazon ECS setup for you. You'll need to use either the **Node.js API with AWS Fargate** or **Java API with AWS Fargate** blueprint. For more information, see [Creating a project with a blueprint](projects-create.md#projects-create-console-template).

**Topics**
+ [Prerequisites](#deploy-tut-ecs-prereqs)
+ [Step 1: Set up an AWS user and AWS CloudShell](#deploy-tut-ecs-user-cloudshell)
+ [Step 2: Deploy a placeholder application into Amazon ECS](#deploy-tut-ecs-placeholder)
+ [Step 3: Create an Amazon ECR image repository](#deploy-tut-ecs-ecr)
+ [Step 4: Create AWS roles](#deploy-tut-ecs-build-deploy-roles)
+ [Step 5: Add AWS roles to CodeCatalyst](#deploy-tut-ecs-import-roles)
+ [Step 6: Create a source repository](#deploy-tut-ecs-source-repo)
+ [Step 7: Add source files](#deploy-tut-ecs-source-files)
+ [Step 8: Create and run a workflow](#deploy-tut-ecs-workflow)
+ [Step 9: Make a change to your source files](#deploy-tut-ecs-change)
+ [Clean up](#deploy-tut-ecs-cleanup)

## Prerequisites
<a name="deploy-tut-ecs-prereqs"></a>

Before you begin:
+ You need a CodeCatalyst **space** with a connected AWS account. For more information, see [Creating a space](spaces-create.md).
+ In your space, you need an empty project called:

  ```
  codecatalyst-ecs-project
  ```

  Use the **Start from scratch** option to create this project.

  For more information, see [Creating an empty project in Amazon CodeCatalyst](projects-create.md#projects-create-empty).
+ In your project, you need a CodeCatalyst **environment** called:

  ```
  codecatalyst-ecs-environment
  ```

  Configure this environment as follows:
  + Choose any type, such as **Non-production**.
  + Connect your AWS account to it.
  + For the **Default IAM role**, choose any role. You'll specify a different role later.

  For more information, see [Deploying into AWS accounts and VPCs](deploy-environments.md).

## Step 1: Set up an AWS user and AWS CloudShell
<a name="deploy-tut-ecs-user-cloudshell"></a>

The first step in this tutorial is to create a user in AWS IAM Identity Center, and launch an AWS CloudShell instance as this user. For the duration of this tutorial, CloudShell is your development computer and is where you configure AWS resources and services. Delete this user after completing the tutorial.

**Note**  
Do not use your root user for this tutorial. You must create a separate user or else you may experience problems when performing actions in the AWS Command Line Interface (CLI) later on.

For more information about IAM Identity Center users and CloudShell, see the *AWS IAM Identity Center User Guide* and *AWS CloudShell User Guide*. 

**To create an IAM Identity Center user**

1. Sign in to the AWS Management Console and open the AWS IAM Identity Center console at [https://console.aws.amazon.com/singlesignon/](https://console.aws.amazon.com/singlesignon/).
**Note**  
Make sure you sign in using the AWS account that is connected to your CodeCatalyst space. You can verify which account is connected by navigating to your space and choosing the **AWS accounts** tab. For more information, see [Creating a space](spaces-create.md).

1. In the navigation pane, choose **Users**, and then choose **Add user**.

1. In **Username**, enter:

   ```
   CodeCatalystECSUser
   ```

1. Under **Password**, choose **Generate a one-time password that you can share with this user**.

1. In **Email address** and **Confirm email address**, enter an email address that doesn't already exist in IAM Identity Center.

1. In **First name** and **Last name**, enter:

   ```
   CodeCatalystECSUser
   ```

1. In **Display name**, keep the automatically generated name:

   ```
   CodeCatalystECSUser CodeCatalystECSUser
   ```

1. Choose **Next**.

1. On the **Add user to groups** page, choose **Next**.

1. On the **Review and add user** page, review the information and choose **Add user**.

   A **One-time password** dialog box appears.

1. Choose **Copy** and then paste the sign-in information, including the AWS access portal URL and the one-time password.

1. Choose **Close**.

**To create a permission set**

You'll assign this permission set to `CodeCatalystECSUser` later.

1. In the navigation pane, choose **Permission sets**, and then choose **Create permission set**.

1. Choose **Predefined permission set** and then select **AdministratorAccess**. This policy provides full permissions to all AWS services. 

1. Choose **Next**.

1. In **Permission set name**, enter:

   ```
   CodeCatalystECSPermissionSet
   ```

1. Choose **Next**.

1. On the **Review and create** page, review the information and choose **Create**.

**To assign the permission set to CodeCatalystECSUser**

1. In the navigation pane, choose **AWS accounts**, and then select the check box next to the AWS account that you're currently signed in to.

1. Choose **Assign users or groups**.

1. Choose the **Users** tab.

1. Select the check box next to `CodeCatalystECSUser`.

1. Choose **Next**.

1. Select the check box next to `CodeCatalystECSPermissionSet`.

1. Choose **Next**.

1. Review the information and choose **Submit**.

   You have now assigned `CodeCatalystECSUser` and `CodeCatalystECSPermissionSet` to your AWS account, binding them together.

**To sign out and sign back in as CodeCatalystECSUser**

1. Before you sign out, make sure you have the AWS access portal URL and the username and one-time password for `CodeCatalystECSUser`. You should have copied this information to a text editor earlier.
**Note**  
If you do not have this information, go to the `CodeCatalystECSUser` details page in IAM Identity Center, choose **Reset password**, **Generate a one-time password [...]**, and **Reset password** again to display the information on the screen.

1. Sign out of AWS.

1. Paste the AWS access portal URL into your browser's address bar.

1. Sign in with the username and one-time password for `CodeCatalystECSUser`.

1. In **New password**, enter a password, and choose **Set new password**.

   An **AWS account** box appears on the screen.

1. Choose **AWS account**, and then choose the name of the AWS account to which you assigned the `CodeCatalystECSUser` user and permission set.

1. Next to the `CodeCatalystECSPermissionSet`, choose **Management console**.

   The AWS Management Console appears. You are now signed in as `CodeCatalystECSUser` with the appropriate permissions.

**To launch an AWS CloudShell instance**

1. As `CodeCatalystECSUser`, in the top navigation bar, choose the AWS icon (![\[AWS icon\]](http://docs.aws.amazon.com/codecatalyst/latest/userguide/images/deploy/aws-logo.png)).

   The main page of the AWS Management Console appears.

1. In the top navigation bar, choose the AWS CloudShell icon (![\[CloudShell icon\]](http://docs.aws.amazon.com/codecatalyst/latest/userguide/images/deploy/CloudShell.png)).

   CloudShell opens. Wait while the CloudShell environment is created.
**Note**  
If you don't see the CloudShell icon, make sure that you're in a [Region supported by CloudShell](https://docs.aws.amazon.com/cloudshell/latest/userguide/faq-list.html#regions-available). This tutorial assumes you are in the US West (Oregon) Region.

**To verify that the AWS CLI is installed**

1. In the CloudShell terminal, enter:

   ```
   aws --version
   ```

1. Check that a version appears.

   The AWS CLI is already configured for the current user, `CodeCatalystECSUser`, so there is no need to configure AWS CLI keys and credentials, as is normally the case.

## Step 2: Deploy a placeholder application into Amazon ECS
<a name="deploy-tut-ecs-placeholder"></a>

In this section, you manually deploy a placeholder application into Amazon ECS. This placeholder application will be replaced by the Hello World application deployed by your workflow. The placeholder application is Apache Web Server.

For more information about Amazon ECS, see the *Amazon Elastic Container Service Developer Guide*.

Complete the following series of procedures to deploy the placeholder application.<a name="deploy-tut-ecs-create-task-execution-role"></a>

**To create the task execution role**

This role grants Amazon ECS and AWS Fargate permission to make API calls on your behalf. 

1. Create a trust policy:

   1. In AWS CloudShell, enter the following command:

      ```
      cat > codecatalyst-ecs-trust-policy.json
      ```

      A blinking prompt appears in the CloudShell terminal.

   1. Enter the following code at the prompt:

------
#### [ JSON ]

****  

      ```
      {
        "Version":"2012-10-17",		 	 	 
        "Statement": [
          {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
              "Service": "ecs-tasks.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
          }
        ]
      }
      ```

------

   1. Place your cursor after the last curly bracket (`}`).

   1. Press **Enter** and then **Ctrl\$1d** to save the file and exit cat.

1. Create a task execution role:

   ```
   aws iam create-role \
         --role-name codecatalyst-ecs-task-execution-role \
         --assume-role-policy-document file://codecatalyst-ecs-trust-policy.json
   ```

1. Attach the AWS managed `AmazonECSTaskExecutionRolePolicy` policy to the role:

   ```
   aws iam attach-role-policy \
         --role-name codecatalyst-ecs-task-execution-role \
         --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy
   ```

1. Display the role’s details:

   ```
   aws iam get-role \
         --role-name codecatalyst-ecs-task-execution-role
   ```

1. Note the role's `"Arn":` value, for example, `arn:aws:iam::111122223333:role/codecatalyst-ecs-task-execution-role`. You will need this Amazon Resource Name (ARN) later.

**To create an Amazon ECS cluster**

This cluster will contain the Apache placeholder application, and later, the Hello World application. 

1. As `CodeCatalystECSUser`, in AWS CloudShell, create an empty cluster:

   ```
   aws ecs create-cluster --cluster-name codecatalyst-ecs-cluster
   ```

1. (Optional) Verify that the cluster was created successfully:

   ```
   aws ecs list-clusters
   ```

   The ARN of the `codecatalyst-ecs-cluster` cluster should appear in the list, indicating a successful creation.

**To create a task definition file**

The task definition file indicates to run the [Apache 2.4 Web server](https://hub.docker.com/_/httpd) Docker image (`httpd:2.4`) which is pulled from DockerHub.

1. As `CodeCatalystECSUser`, in AWS CloudShell, create a task definition file:

   ```
   cat > taskdef.json
   ```

1. Paste the following code at the prompt:

   ```
   {
       "executionRoleArn": "arn:aws:iam::111122223333:role/codecatalyst-ecs-task-execution-role",
       "containerDefinitions": [
           {
               "name": "codecatalyst-ecs-container",
               "image": "httpd:2.4",
               "essential": true,
               "portMappings": [
                   {
                       "hostPort": 80,
                       "protocol": "tcp",
                       "containerPort": 80
                   }
               ]
           }
       ],
       "requiresCompatibilities": [
           "FARGATE"
       ],
       "cpu": "256",
       "family": "codecatalyst-ecs-task-def",
       "memory": "512",
       "networkMode": "awsvpc"
   }
   ```

   In the preceding code, replace *arn:aws:iam::111122223333:role/codecatalyst-ecs-task-execution-role*

   with the ARN of the task execution role that you noted in [To create the task execution role](#deploy-tut-ecs-create-task-execution-role).

1. Place your cursor after the last curly bracket (`}`).

1. Press **Enter** and then **Ctrl\$1d** to save the file and exit cat.

**To register the task definition file with Amazon ECS**

1. As `CodeCatalystECSUser`, in AWS CloudShell, register the task definition:

   ```
   aws ecs register-task-definition \
       --cli-input-json file://taskdef.json
   ```

1. (Optional) Verify that the task definition was registered:

   ```
   aws ecs list-task-definitions
   ```

   The `codecatalyst-ecs-task-def` task definition should appear in the list.

**To create the Amazon ECS service**

The Amazon ECS service runs the tasks (and associated Docker containers) of the Apache placeholder application, and later, the Hello World application.

1. As `CodeCatalystECSUser`, switch to the Amazon Elastic Container Service console if you haven't done so already.

1. Choose the cluster you created earlier, `codecatalyst-ecs-cluster`.

1. In the **Services** tab, choose **Create**.

1. In the **Create** page, do the following:

   1. Keep all default settings except for those listed next.

   1. For **Launch type**, choose **FARGATE**.

   1. Under **Task definition**, in the **Family** drop-down list, choose:

      `codecatalyst-ecs-task-def`

   1. For **Service name**, enter:

      ```
      codecatalyst-ecs-service
      ```

   1. For **Desired tasks**, enter:

      ```
      3
      ```

      In this tutorial, each task launches a single Docker container.

   1. Expand the **Networking** section.

   1. For **VPC**, choose any VPC.

   1. For **Subnets**, choose any subnet.
**Note**  
Only specify one subnet. That's all that is needed for this tutorial.
**Note**  
If you don’t have a VPC and subnet, create them. See [Create a VPC](https://docs.aws.amazon.com/vpc/latest/userguide/working-with-vpcs.html#Create-VPC), and [Create a subnet in your VPC](https://docs.aws.amazon.com/vpc/latest/userguide/working-with-vpcs.html#AddaSubnet) in the *Amazon VPC User Guide*.

   1. For **Security group**, choose **Create a new security group**, and then do the following:

      1. For **Security group name**, enter:

         ```
         codecatalyst-ecs-security-group
         ```

      1. For **Security group description**, enter:

         ```
         CodeCatalyst ECS security group
         ```

      1. Choose **Add rule**. For **Type**, choose **HTTP**, and for **Source**, choose **Anywhere**.

   1. At the bottom, choose **Create**.

   1. Wait while the service is created. This may take a few minutes.

1. Choose the **Tasks** tab, and then choose the refresh button. Verify that all three tasks have their **Last Status** column set to **Running**.

**(Optional) To verify that your Apache placeholder application is running**

1. In the **Tasks** tab, choose any one of the three tasks.

1. In the **Public IP** field, choose **open address**.

   An `It Works!` page appears. This indicates that the Amazon ECS service successfully started a task that launched a Docker container with the Apache image.

   At this point in the tutorial, you have manually deployed an Amazon ECS cluster, service, and task definition, as well as an Apache placeholder application. With all these items in place, you are now ready to create a workflow that will replace the Apache placeholder application with the tutorial’s Hello World application.

## Step 3: Create an Amazon ECR image repository
<a name="deploy-tut-ecs-ecr"></a>

In this section, you create a private image repository in Amazon Elastic Container Registry (Amazon ECR). This repository stores the tutorial’s Docker image that will replace the Apache placeholder image you deployed previously. 

For more information about Amazon ECR, see the *Amazon Elastic Container Registry User Guide*.

**To create an image repository in Amazon ECR**

1. As `CodeCatalystECSUser`, in AWS CloudShell, create an empty repository in Amazon ECR:

   ```
   aws ecr create-repository --repository-name codecatalyst-ecs-image-repo
   ```

1. Display the Amazon ECR repository’s details:

   ```
   aws ecr describe-repositories \
         --repository-names codecatalyst-ecs-image-repo
   ```

1. Note the `“repositoryUri”:` value, for example, `111122223333.dkr.ecr.us-west-2.amazonaws.com/codecatalyst-ecs-image-repo`.

   You need it later when adding the repository to your workflow. 

## Step 4: Create AWS roles
<a name="deploy-tut-ecs-build-deploy-roles"></a>

In this section, you create AWS IAM roles that your CodeCatalyst workflow will need in order to function. These roles are:
+ **Build role** – Grants the CodeCatalyst build action (in the workflow) permission to access your AWS account and write to Amazon ECR and Amazon EC2.
+ **Deploy role** – Grants the CodeCatalyst **Deploy to ECS** action (in the workflow) permission to access your AWS account, Amazon ECS, and a few other AWS services.

For more information about IAM roles, see [IAM roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) in the *AWS Identity and Access Management User Guide*.

**Note**  
To save time, you can create a single role, called the `CodeCatalystWorkflowDevelopmentRole-spaceName` role, instead of the two roles listed previously. For more information, see [Creating the **CodeCatalystWorkflowDevelopmentRole-*spaceName*** role for your account and space](ipa-iam-roles.md#ipa-iam-roles-service-create). Understand that the `CodeCatalystWorkflowDevelopmentRole-spaceName` role has very broad permissions which may pose a security risk. We recommend that you only use this role in tutorials and scenarios where security is less of a concern. This tutorial assumes you are creating the two roles listed previously.

To create the build and deploy roles, you can use either the AWS Management Console or the AWS CLI.

------
#### [ AWS Management Console ]

To create the build and deploy roles, complete the following series of procedures.

**To create a build role**

1. Create a policy for the role, as follows:

   1. Sign in to AWS.

   1. Open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

   1. In the navigation pane, choose **Policies**.

   1. Choose **Create policy**.

   1. Choose the **JSON** tab.

   1. Delete the existing code.

   1. Paste the following code:

------
#### [ JSON ]

****  

      ```
      {
          "Version":"2012-10-17",		 	 	 
          "Statement": [
              {
                  "Effect": "Allow",
                  "Action": [
                      "ecr:*",
                      "ec2:*"
                  ],
                  "Resource": "*"
              }
          ]
      }
      ```

------
**Note**  
The first time the role is used to run workflow actions, use the wildcard in the resource policy statement and then scope down the policy with the resource name after it is available.  

      ```
      "Resource": "*"
      ```

   1. Choose **Next: Tags**.

   1. Choose **Next: Review**.

   1. In **Name**, enter:

      ```
      codecatalyst-ecs-build-policy
      ```

   1. Choose **Create policy**.

      You have now created a permissions policy.

1. Create the build role, as follows:

   1. In the navigation pane, choose **Roles**, and then choose **Create role**.

   1. Choose **Custom trust policy**.

   1. Delete the existing custom trust policy.

   1. Add the following custom trust policy:

   1. Choose **Next**.

   1. In **Permissions policies**, search for `codecatalyst-ecs-build-policy`, select its check box.

   1. Choose **Next**.

   1. For **Role name**, enter:

      ```
      codecatalyst-ecs-build-role
      ```

   1. For **Role description**, enter:

      ```
      CodeCatalyst ECS build role
      ```

   1. Choose **Create role**.

   You have now created a build role with a permissions policy and a trust policy.

1. Obtain the build role ARN, as follows:

   1. In the navigation pane, choose **Roles**.

   1. In the search box, enter the name of the role you just created (`codecatalyst-ecs-build-role`).

   1. Choose the role from the list.

      The role's **Summary** page appears.

   1. At the top, copy the **ARN** value. You need it later.

**To create a deploy role**

1. Create a policy for the role, as follows:

   1. Sign in to AWS.

   1. Open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

   1. In the navigation pane, choose **Policies**.

   1. Choose **Create Policy**.

   1. Choose the **JSON** tab.

   1. Delete the existing code.

   1. Paste the following code:

------
#### [ JSON ]

****  

      ```
      {
          "Version":"2012-10-17",		 	 	 
          "Statement": [{
          "Action":[
            "ecs:DescribeServices",
            "ecs:CreateTaskSet",
            "ecs:DeleteTaskSet",
            "ecs:ListClusters",
            "ecs:RegisterTaskDefinition",
            "ecs:UpdateServicePrimaryTaskSet",
            "ecs:UpdateService",
            "elasticloadbalancing:DescribeTargetGroups",
            "elasticloadbalancing:DescribeListeners",
            "elasticloadbalancing:ModifyListener",
            "elasticloadbalancing:DescribeRules",
            "elasticloadbalancing:ModifyRule",
            "lambda:InvokeFunction",
            "lambda:ListFunctions",
            "cloudwatch:DescribeAlarms",
            "sns:Publish",
            "sns:ListTopics", 
            "s3:GetObject",
            "s3:GetObjectVersion",
            "codedeploy:CreateApplication", 
            "codedeploy:CreateDeployment", 
            "codedeploy:CreateDeploymentGroup", 
            "codedeploy:GetApplication", 
            "codedeploy:GetDeployment", 
            "codedeploy:GetDeploymentGroup", 
            "codedeploy:ListApplications", 
            "codedeploy:ListDeploymentGroups", 
            "codedeploy:ListDeployments", 
            "codedeploy:StopDeployment", 
            "codedeploy:GetDeploymentTarget", 
            "codedeploy:ListDeploymentTargets", 
            "codedeploy:GetDeploymentConfig", 
            "codedeploy:GetApplicationRevision", 
            "codedeploy:RegisterApplicationRevision", 
            "codedeploy:BatchGetApplicationRevisions", 
            "codedeploy:BatchGetDeploymentGroups", 
            "codedeploy:BatchGetDeployments", 
            "codedeploy:BatchGetApplications", 
            "codedeploy:ListApplicationRevisions", 
            "codedeploy:ListDeploymentConfigs", 
            "codedeploy:ContinueDeployment"           
         ],
         "Resource":"*",
         "Effect":"Allow"
      },{"Action":[
            "iam:PassRole"
         ],
         "Effect":"Allow",
         "Resource":"*",
         "Condition":{"StringLike":{"iam:PassedToService":[
                  "ecs-tasks.amazonaws.com",
                  "codedeploy.amazonaws.com"
               ]
            }
         }
      }]
      }
      ```

------
**Note**  
The first time the role is used to run workflow actions, use the wildcard in the resource policy statement. You can then scope down the policy with the resource name after it is available.  

      ```
      "Resource": "*"
      ```

   1. Choose **Next: Tags**.

   1. Choose **Next: Review**.

   1. In **Name**, enter:

      ```
      codecatalyst-ecs-deploy-policy
      ```

   1. Choose **Create policy**.

      You have now created a permissions policy.

1. Create the deploy role, as follows:

   1. In the navigation pane, choose **Roles**, and then choose **Create role**.

   1. Choose **Custom trust policy**.

   1. Delete the existing custom trust policy.

   1. Add the following custom trust policy:

   1. Choose **Next**.

   1. In **Permissions policies**, search for `codecatalyst-ecs-deploy-policy`, select its check box.

   1. Choose **Next**.

   1. For **Role name**, enter:

      ```
      codecatalyst-ecs-deploy-role
      ```

   1. For **Role description**, enter:

      ```
      CodeCatalyst ECS deploy role
      ```

   1. Choose **Create role**.

   You have now created a deploy role with a trust policy.

1. Obtain the deploy role ARN, as follows:

   1. In the navigation pane, choose **Roles**.

   1. In the search box, enter the name of the role you just created (`codecatalyst-ecs-deploy-role`).

   1. Choose the role from the list.

      The role's **Summary** page appears.

   1. At the top, copy the **ARN** value. You need it later.

------
#### [ AWS CLI ]

To create the build and deploy roles, complete the following series of procedures.

**To create a trust policy for both roles**

As `CodeCatalystECSUser`, in AWS CloudShell, create a trust policy file:

1. Create the file:

   ```
   cat > codecatalyst-ecs-trust-policy.json
   ```

1. At the terminal prompt, paste the following code:

1. Place your cursor after the last curly bracket (`}`).

1. Press **Enter** and then **Ctrl\$1d** to save the file and exit cat.

**To create the build policy and build role**

1. Create the build policy:

   1. As `CodeCatalystECSUser`, in AWS CloudShell, create a build policy file:

      ```
      cat > codecatalyst-ecs-build-policy.json
      ```

   1. At the prompt, enter the following code:

------
#### [ JSON ]

****  

      ```
      {
          "Version":"2012-10-17",		 	 	 
          "Statement": [
              {
                  "Effect": "Allow",
                  "Action": [
                      "ecr:*",
                      "ec2:*"
                  ],
                  "Resource": "*"
              }
          ]
      }
      ```

------

   1. Place your cursor after the last curly bracket (`}`).

   1. Press **Enter** and then **Ctrl\$1d** to save the file and exit cat.

1. Add the build policy to AWS:

   ```
   aws iam create-policy \
       --policy-name codecatalyst-ecs-build-policy \
       --policy-document file://codecatalyst-ecs-build-policy.json
   ```

1. In the command output, note the `"arn":` value, for example, `arn:aws:iam::111122223333:policy/codecatalyst-ecs-build-policy`. You need this ARN later.

1. Create the build role and attach the trust policy to it:

   ```
   aws iam create-role \
         --role-name codecatalyst-ecs-build-role \
         --assume-role-policy-document file://codecatalyst-ecs-trust-policy.json
   ```

1. Attach the build policy to the build role:

   ```
   aws iam attach-role-policy \
         --role-name codecatalyst-ecs-build-role \
         --policy-arn arn:aws:iam::111122223333:policy/codecatalyst-ecs-build-policy
   ```

   Where *arn:aws:iam::111122223333:policy/codecatalyst-ecs-build-policy* is replaced with the ARN of the build policy you noted earlier.

1. Display the build role’s details:

   ```
   aws iam get-role \
         --role-name codecatalyst-ecs-build-role
   ```

1. Note the role's `"Arn":` value, for example, `arn:aws:iam::111122223333:role/codecatalyst-ecs-build-role`. You need this ARN later.

**To create the deploy policy and deploy role**

1. Create a deploy policy:

   1. In AWS CloudShell, create a deploy policy file:

      ```
      cat > codecatalyst-ecs-deploy-policy.json
      ```

   1. At the prompt, enter the following code:

------
#### [ JSON ]

****  

      ```
      {
          "Version":"2012-10-17",		 	 	 
          "Statement": [{
          "Action":[
            "ecs:DescribeServices",
            "ecs:CreateTaskSet",
            "ecs:DeleteTaskSet",
            "ecs:ListClusters",
            "ecs:RegisterTaskDefinition",
            "ecs:UpdateServicePrimaryTaskSet",
            "ecs:UpdateService",
            "elasticloadbalancing:DescribeTargetGroups",
            "elasticloadbalancing:DescribeListeners",
            "elasticloadbalancing:ModifyListener",
            "elasticloadbalancing:DescribeRules",
            "elasticloadbalancing:ModifyRule",
            "lambda:InvokeFunction",
            "lambda:ListFunctions",
            "cloudwatch:DescribeAlarms",
            "sns:Publish",
            "sns:ListTopics", 
            "s3:GetObject",
            "s3:GetObjectVersion",
            "codedeploy:CreateApplication", 
            "codedeploy:CreateDeployment", 
            "codedeploy:CreateDeploymentGroup", 
            "codedeploy:GetApplication", 
            "codedeploy:GetDeployment", 
            "codedeploy:GetDeploymentGroup", 
            "codedeploy:ListApplications", 
            "codedeploy:ListDeploymentGroups", 
            "codedeploy:ListDeployments", 
            "codedeploy:StopDeployment", 
            "codedeploy:GetDeploymentTarget", 
            "codedeploy:ListDeploymentTargets", 
            "codedeploy:GetDeploymentConfig", 
            "codedeploy:GetApplicationRevision", 
            "codedeploy:RegisterApplicationRevision", 
            "codedeploy:BatchGetApplicationRevisions", 
            "codedeploy:BatchGetDeploymentGroups", 
            "codedeploy:BatchGetDeployments", 
            "codedeploy:BatchGetApplications", 
            "codedeploy:ListApplicationRevisions", 
            "codedeploy:ListDeploymentConfigs", 
            "codedeploy:ContinueDeployment"           
         ],
         "Resource":"*",
         "Effect":"Allow"
      },{"Action":[
            "iam:PassRole"
         ],
         "Effect":"Allow",
         "Resource":"*",
         "Condition":{"StringLike":{"iam:PassedToService":[
                  "ecs-tasks.amazonaws.com",
                  "codedeploy.amazonaws.com"
               ]
            }
         }
      }]
      }
      ```

------
**Note**  
The first time the role is used to run workflow actions, use the wildcard in the resource policy statement and then scope down the policy with the resource name after it is available.  

      ```
      "Resource": "*"
      ```

   1. Place your cursor after the last curly bracket (`}`).

   1. Press **Enter** and then **Ctrl\$1d** to save the file and exit cat.

1. Add the deploy policy to AWS:

   ```
   aws iam create-policy \
       --policy-name codecatalyst-ecs-deploy-policy \
       --policy-document file://codecatalyst-ecs-deploy-policy.json
   ```

1. In the command output, note the deploy policy's `"arn":` value, for example, `arn:aws:iam::111122223333:policy/codecatalyst-ecs-deploy-policy`. You need this ARN later.

1. Create the deploy role and attach the trust policy to it:

   ```
   aws iam create-role \
         --role-name codecatalyst-ecs-deploy-role \
         --assume-role-policy-document file://codecatalyst-ecs-trust-policy.json
   ```

1. Attach the deploy policy to the deploy role, where *arn:aws:iam::111122223333:policy/codecatalyst-ecs-deploy-policy* is replaced with the ARN of the deploy policy you noted earlier.

   ```
   aws iam attach-role-policy \
         --role-name codecatalyst-ecs-deploy-role \
         --policy-arn arn:aws:iam::111122223333:policy/codecatalyst-ecs-deploy-policy
   ```

1. Display the deploy role’s details:

   ```
   aws iam get-role \
         --role-name codecatalyst-ecs-deploy-role
   ```

1. Note the role's `"Arn":` value, for example, `arn:aws:iam::111122223333:role/codecatalyst-ecs-deploy-role`. You need this ARN later.

------

## Step 5: Add AWS roles to CodeCatalyst
<a name="deploy-tut-ecs-import-roles"></a>

In this step, you add the build role (`codecatalyst-ecs-build-role`) and deploy role (`codecatalyst-ecs-deploy-role`) to the CodeCatalyst account connection in your space.

**To add build and deploy roles to your account connection**

1. In CodeCatalyst, navigate to your space.

1. Choose **AWS accounts**. A list of account connections appears.

1. Choose the account connection that represents the AWS account where you created your build and deploy roles.

1. Choose **Manage roles from AWS management console**.

   The **Add IAM role to Amazon CodeCatalyst space** page appears. You might need to sign in to access the page.

1. Select **Add an existing role you have created in IAM**.

   A drop-down list appears. The list displays all IAM roles with a trust policy that includes the `codecatalyst-runner.amazonaws.com` and `codecatalyst.amazonaws.com` service principals.

1. In the drop-down list, choose `codecatalyst-ecs-build-role`, and choose **Add role**.
**Note**  
If you see `The security token included in the request is invalid`, it might be because you do not have the right permissions. To fix this issue, sign out of AWS as sign back in with the AWS account that you used when you created your CodeCatalyst space.

1. Choose **Add IAM role**, choose **Add an existing role you have created in IAM**, and in the drop-down list, choose `codecatalyst-ecs-deploy-role`. Choose **Add role**.

   You have now added the build and deploy roles to your space.

1. Copy the value of the **Amazon CodeCatalyst display name**. You'll need this value later, when creating your workflow.

## Step 6: Create a source repository
<a name="deploy-tut-ecs-source-repo"></a>

In this step, you create a source repository in CodeCatalyst. This repository stores the tutorial's source files, such as the task definition file.

For more information about source repositories, see [Creating a source repository](source-repositories-create.md).

**To create a source repository**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Navigate to your project, `codecatalyst-ecs-project`.

1. In the navigation pane, choose **Code**, and then choose **Source repositories**. 

1. Choose **Add repository**, and then choose **Create repository**.

1. In **Repository name**, enter:

   ```
   codecatalyst-ecs-source-repository
   ```

1. Choose **Create**.

## Step 7: Add source files
<a name="deploy-tut-ecs-source-files"></a>

In this section, you add the Hello World source files to your CodeCatalyst repository, `codecatalyst-ecs-source-repository`. They consist of:
+ An `index.html` file – Displays a Hello World message in the browser. 
+ A Dockerfile – Describes the base image to use for your Docker image and the Docker commands to apply to it. 
+ A `taskdef.json` file – Defines the Docker image to use when launching tasks into your cluster.

The folder structure is as follows:

```
.
|— public-html
|  |— index.html
|— Dockerfile
|— taskdef.json
```

**Note**  
The following instructions show you how to add the files using the CodeCatalyst console but you can use Git if you prefer. For details, see [Cloning a source repository](source-repositories-clone.md). 

**Topics**
+ [index.html](#deploy-tut-ecs-source-files-index)
+ [Dockerfile](#deploy-tut-ecs-source-files-dockerfile)
+ [taskdef.json](#deploy-tut-ecs-source-files-taskdef)

### index.html
<a name="deploy-tut-ecs-source-files-index"></a>

The `index.html` file displays a Hello World message in the browser. 

**To add the index.html file**

1. In the CodeCatalyst console, go to your source repository, `codecatalyst-ecs-source-repository`.

1. In **Files**, choose **Create file**.

1. For **File name**, enter:

   ```
   public-html/index.html
   ```
**Important**  
Make sure to include the `public-html/` prefix to create a folder of the same name. The `index.html` is expected to be in this folder.

1. In the text box, enter the following code:

   ```
   <html>
     <head>
       <title>Hello World</title>
       <style>
         body {
         background-color: black;
         text-align: center;
         color: white;
         font-family: Arial, Helvetica, sans-serif;
         }  
       </style>
     </head>
     <body>
       <h1>Hello World</h1>
     </body>
   </html>
   ```

1. Choose **Commit**, and then choose **Commit** again.

   The `index.html` is added to your repository in a `public-html` folder. 

### Dockerfile
<a name="deploy-tut-ecs-source-files-dockerfile"></a>

The Dockerfile describes the base Docker image to use and the Docker commands to apply to it. For more information about the Dockerfile, see the [Dockerfile Reference](https://docs.docker.com/engine/reference/builder/).

The Dockerfile specified here indicates to use the Apache 2.4 base image (`httpd`). It also includes instructions for copying a source file called `index.html` to a folder on the Apache server that serves webpages. The `EXPOSE` instruction in the Dockerfile tells Docker that the container is listening on port 80.

**To add the Dockerfile**

1. In your source repository, choose **Create file**.

1. For **File name**, enter:

   ```
   Dockerfile
   ```

   Do not include a file extension.
**Important**  
The Dockerfile must reside in your repository’s root folder. The workflow’s `Docker build` command expects it to be there.

1. In the text box, enter the following code:

   ```
   FROM httpd:2.4
   COPY ./public-html/index.html /usr/local/apache2/htdocs/index.html
   EXPOSE 80
   ```

1. Choose **Commit**, and then choose **Commit** again.

   The Dockerfile is added to your repository. 

### taskdef.json
<a name="deploy-tut-ecs-source-files-taskdef"></a>

The `taskdef.json` file that you add in this step is the same as the one you already specified in [Step 2: Deploy a placeholder application into Amazon ECS](#deploy-tut-ecs-placeholder) with the following difference:

Instead of specifying a hardcoded Docker image name in the `image:` field (`httpd:2.4`), the task definition here uses a couple of variables to denote the image: `$REPOSITORY_URI` and `$IMAGE_TAG`. These variables will be replaced with real values generated by the workflow’s build action when you run the workflow in a later step.

For details on the task definition parameters, see [Task definition parameters](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html) in the *Amazon Elastic Container Service Developer Guide*.

**To add the taskdef.json file**

1. In your source repository, choose **Create file**.

1. For **File name**, enter:

   ```
   taskdef.json
   ```

1. In the text box, enter the following code:

   ```
   {
       "executionRoleArn": "arn:aws:iam::account_ID:role/codecatalyst-ecs-task-execution-role",
       "containerDefinitions": [
           {
               "name": "codecatalyst-ecs-container",
               # The $REPOSITORY_URI and $IMAGE_TAG variables will be replaced 
               # by the workflow at build time (see the build action in the 
               # workflow)
               "image": $REPOSITORY_URI:$IMAGE_TAG,
               "essential": true,
               "portMappings": [
                   {
                       "hostPort": 80,
                       "protocol": "tcp",
                       "containerPort": 80
                   }
               ]
           }
       ],
       "requiresCompatibilities": [
           "FARGATE"
       ],
       "networkMode": "awsvpc",
       "cpu": "256",
       "memory": "512",
       "family": "codecatalyst-ecs-task-def"
   }
   ```

   In the preceding code, replace

   *arn:aws:iam::account\$1ID:role/codecatalyst-ecs-task-execution-role*

   with the ARN of the task execution role that you noted in [To create the task execution role](#deploy-tut-ecs-create-task-execution-role).

1. Choose **Commit**, and then choose **Commit** again.

   The `taskdef.json` file is added to your repository. 

## Step 8: Create and run a workflow
<a name="deploy-tut-ecs-workflow"></a>

In this step, you create a workflow that takes your source files, builds them into a Docker image, and then deploys the image to your Amazon ECS cluster. This deployment replaces the existing Apache placeholder application.

The workflow consists of the following building blocks that run sequentially:
+ A trigger – This trigger starts the workflow run automatically when you push a change to your source repository. For more information about triggers, see [Starting a workflow run automatically using triggers](workflows-add-trigger.md).
+ A build action (`BuildBackend`) – On trigger, the action builds the Docker image using the Dockerfile and pushes the image to Amazon ECR. The build action also updates the `taskdef.json` with the correct `image` field value, and then creates an output artifact of this file. This artifact is used as the input for the deploy action, which is next.

  For more information about the build action, see [Building with workflows](build-workflow-actions.md).
+ A deploy action (`DeployToECS`) – On completion of the build action, the deploy action looks for the output artifact generated by the build action (`TaskDefArtifact`), finds the `taskdef.json` inside of it, and registers it with your Amazon ECS service. The service then follows the instructions in the `taskdef.json` file to run three Amazon ECS tasks—and associated Hello World Docker containers—inside your Amazon ECS cluster. 

**To create a workflow**

1. In the CodeCatalyst console, in the navigation pane, choose **CI/CD**, and then choose **Workflows**.

1. Choose **Create workflow**.

1. For **Source repository**, choose `codecatalyst-ecs-source-repository`.

1. For **Branch**, choose `main`.

1. Choose **Create**.

1. Delete the YAML sample code.

1. Add the following YAML code:
**Note**  
In the YAML code that follows, you can omit the `Connections:` sections if you want. If you omit these sections, you must ensure that the role specified in the **Default IAM role** field in your environment includes the permissions and trust policies of both roles described in [Step 5: Add AWS roles to CodeCatalyst](#deploy-tut-ecs-import-roles). For more information about setting up an environment with a default IAM role, see [Creating an environment](deploy-environments-creating-environment.md).

   ```
   Name: codecatalyst-ecs-workflow
   SchemaVersion: 1.0
   
   Triggers:
     - Type: PUSH
       Branches:
         - main
   Actions:
     BuildBackend:
       Identifier: aws/build@v1
       Environment:
         Name: codecatalyst-ecs-environment
         Connections:
           - Name: codecatalyst-account-connection
             Role: codecatalyst-ecs-build-role
       Inputs:
         Sources:
           - WorkflowSource
         Variables:
           - Name: REPOSITORY_URI
             Value: 111122223333.dkr.ecr.us-west-2.amazonaws.com/codecatalyst-ecs-image-repo
           - Name: IMAGE_TAG
             Value: ${WorkflowSource.CommitId}
       Configuration:
         Steps:
           #pre_build:
           - Run: echo Logging in to Amazon ECR...
           - Run: aws --version
           - Run: aws ecr get-login-password --region us-west-2 | docker login --username AWS --password-stdin 111122223333.dkr.ecr.us-west-2.amazonaws.com
           #build:
           - Run: echo Build started on `date`
           - Run: echo Building the Docker image...
           - Run: docker build -t $REPOSITORY_URI:latest .
           - Run: docker tag $REPOSITORY_URI:latest $REPOSITORY_URI:$IMAGE_TAG
           #post_build:
           - Run: echo Build completed on `date`
           - Run: echo Pushing the Docker images...
           - Run: docker push $REPOSITORY_URI:latest
           - Run: docker push $REPOSITORY_URI:$IMAGE_TAG
           # Replace the variables in taskdef.json
           - Run: find taskdef.json -type f | xargs sed -i "s|\$REPOSITORY_URI|$REPOSITORY_URI|g"
           - Run: find taskdef.json -type f | xargs sed -i "s|\$IMAGE_TAG|$IMAGE_TAG|g"
           - Run: cat taskdef.json
           # The output artifact will be a zip file that contains a task definition file.
       Outputs:
         Artifacts:
           - Name: TaskDefArtifact
             Files: 
               - taskdef.json
     DeployToECS:
       DependsOn: 
         - BuildBackend
       Identifier: aws/ecs-deploy@v1
       Environment:
         Name: codecatalyst-ecs-environment
         Connections:
           - Name: codecatalyst-account-connection
             Role: codecatalyst-ecs-deploy-role
       Inputs:
         Sources: []
         Artifacts:
           - TaskDefArtifact
       Configuration:
         region: us-west-2
         cluster: codecatalyst-ecs-cluster
         service: codecatalyst-ecs-service
         task-definition: taskdef.json
   ```

   In the preceding code, replace:
   + Both instances of *codecatalyst-ecs-environment* with the name of the environment you created in [Prerequisites](#deploy-tut-ecs-prereqs).
   + Both instances of *codecatalyst-account-connection* with the display name of your account connection. The display name might be a number. For more information, see [Step 5: Add AWS roles to CodeCatalyst](#deploy-tut-ecs-import-roles).
   + *codecatalyst-ecs-build-role* with the name of the build role you created in [Step 4: Create AWS roles](#deploy-tut-ecs-build-deploy-roles).
   + *111122223333.dkr.ecr.us-west-2.amazonaws.com/codecatalyst-ecs-image-repo* (in the `Value:` property) with the URI of the Amazon ECR repository you created in [Step 3: Create an Amazon ECR image repository](#deploy-tut-ecs-ecr).
   + *111122223333.dkr.ecr.us-west-2.amazonaws.com* (in the `Run: aws ecr` command) with the URI of the Amazon ECR repository without the image suffix (`/codecatalyst-ecs-image-repo`).
   + *codecatalyst-ecs-deploy-role* with the name of the deploy role you created in [Step 4: Create AWS roles](#deploy-tut-ecs-build-deploy-roles).
   + Both instances of *us-west-2* with your AWS Region code. For a list of Region codes, see [Regional endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html#regional-endpoints) in the *AWS General Reference*.
**Note**  
If you decided not to create build and deploy roles, replace *codecatalyst-ecs-build-role* and *codecatalyst-ecs-deploy-role* with the name of the `CodeCatalystWorkflowDevelopmentRole-spaceName` role. For more information about this role, see [Step 4: Create AWS roles](#deploy-tut-ecs-build-deploy-roles).
**Tip**  
Instead of using the `find` and `sed` commands shown in the previous workflow code to update the repository and image name, you can use the **Render Amazon ECS task definition** action for this purpose. For more information, see [Modifying an Amazon ECS task definition](render-ecs-action.md).

1. (Optional) Choose **Validate** to make sure that the YAML code is valid before committing.

1. Choose **Commit**.

1. In the **Commit workflow** dialog box, enter the following:

   1. For **Commit message**, remove the text and enter:

      ```
      Add first workflow
      ```

   1. For **Repository**, choose `codecatalyst-ecs-source-repository`.

   1. For **Branch name**, choose main.

   1. Choose **Commit**.

   You have now created a workflow. A workflow run starts automatically because of the trigger defined at the top of the workflow. Specifically, when you committed (and pushed) the `workflow.yaml` file to your source repository, the trigger started the workflow run.

**To view the workflow run progress**

1. In the navigation pane of the CodeCatalyst console, choose **CI/CD**, and then choose **Workflows**.

1. Choose the workflow you just created, `codecatalyst-ecs-workflow`.

1. Choose **BuildBackend** to see the build progress.

1. Choose **DeployToECS** to see the deployment progress.

   For more information about viewing run details, see [Viewing workflow run status and details](workflows-view-run.md).

**To verify the deployment**

1. Open the Amazon ECS classic console at [https://console.aws.amazon.com/ecs/](https://console.aws.amazon.com/ecs/).

1. Choose your cluster, `codecatalyst-ecs-cluster`.

1. Choose the **Tasks** tab. 

1. Choose any one of the three tasks.

1. In the **Public IP** field, choose **open address**.

   A "Hello World" page appears in the browser, indicating that the Amazon ECS service successfully deployed your application.

## Step 9: Make a change to your source files
<a name="deploy-tut-ecs-change"></a>

In this section, you make a change to the `index.html` file in your source repository. This change causes the workflow to build a new Docker image, tag it with a commit ID, push it to Amazon ECR, and deploy it to Amazon ECS. 

**To change the index.html**

1. In the CodeCatalyst console, in the navigation pane, choose **Code**, then choose **Source repositories**, and then choose your repository, `codecatalyst-ecs-source-repository`.

1. Choose `public-html`, and then choose `index.html`.

   The contents of `index.html` appear.

1. Choose **Edit**. 

1. On line 14, change the `Hello World` text to `Tutorial complete!`.

1. Choose **Commit**, and then choose **Commit** again.

   The commit causes a new workflow run to start. 

1. (Optional) Go to your source repository's main page, choose **View commits**, and then note the commit ID for the `index.html` change.

1. Watch the deployment progress:

   1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

   1. Choose `codecatalyst-ecs-workflow` to view the latest run.

   1. Choose **BuildBackend**, and **DeployToECS** to see the workflow run progress.

1. Verify that your application was updated, as follows:

   1. Open the Amazon ECS classic console at [https://console.aws.amazon.com/ecs/](https://console.aws.amazon.com/ecs/).

   1. Choose your cluster, `codecatalyst-ecs-cluster`.

   1. Choose the **Tasks** tab. 

   1. Choose any one of the three tasks.

   1. In the **Public IP** field, choose **open address**.

      A `Tutorial complete!` page appears.

1. (Optional) In AWS, switch to the Amazon ECR console and verify that the new Docker image was tagged with the commit ID from step 6.

## Clean up
<a name="deploy-tut-ecs-cleanup"></a>

Clean up the files and services used in this tutorial to avoid being charged for them.

In the AWS Management Console, clean up in this order:

1. In Amazon ECS, do the following:

   1. Delete `codecatalyst-ecs-service`.

   1. Delete `codecatalyst-ecs-cluster`.

   1. Deregister `codecatalyst-ecs-task-definition`.

1. In Amazon ECR, delete `codecatalyst-ecs-image-repo`.

1. In Amazon EC2, delete `codecatalyst-ecs-security-group`.

1. In IAM Identity Center, delete:

   1. `CodeCatalystECSUser`

   1. `CodeCatalystECSPermissionSet`

In the CodeCatalyst console, clean up as follows:

1. Delete `codecatalyst-ecs-workflow`.

1. Delete `codecatalyst-ecs-environment`.

1. Delete `codecatalyst-ecs-source-repository`.

1. Delete `codecatalyst-ecs-project`.

In this tutorial, you learned how to deploy an application to an Amazon ECS service using a CodeCatalyst workflow and a **Deploy to Amazon ECS** action.

# Adding the 'Deploy to Amazon ECS' action
<a name="deploy-action-ecs-adding"></a>

Use the following instructions to add the **Deploy to Amazon ECS** action to your workflow. 

------
#### [ Visual ]

**To add the 'Deploy to Amazon ECS' action using the visual editor**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

1. Choose the name of your workflow. You can filter by the source repository or branch name where the workflow is defined, or filter by workflow name or status.

1. Choose **Edit**.

1. Choose **Visual**.

1. At the top-left, choose **\$1 Actions** to open the action catalog.

1. From the drop-down list, choose **Amazon CodeCatalyst**.

1. Search for the **Deploy to Amazon ECS** action, and do one of the following:
   + Choose the plus sign (**\$1**) to add the action to the workflow diagram and open its configuration pane.

     Or
   + Choose **Deploy to Amazon ECS**. The action details dialog box appears. On this dialog box:
     + (Optional) Choose **Download** to [view the action's source code](workflows-view-source.md#workflows-view-source.title).
     + Choose **Add to workflow** to add the action to the workflow diagram and open its configuration pane.

1. In the **Inputs** and **Configuration** tabs, complete the fields according to your needs. For a description of each field, see the ['Deploy to Amazon ECS' action YAML](deploy-action-ref-ecs.md). This reference provides detailed information about each field (and corresponding YAML property value) as it appears in both the YAML and visual editors.

1. (Optional) Choose **Validate** to validate the workflow's YAML code before committing.

1. Choose **Commit**, enter a commit message, and choose **Commit** again.

------
#### [ YAML ]

**To add the 'Deploy to Amazon ECS' action using the YAML editor**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

1. Choose the name of your workflow. You can filter by the source repository or branch name where the workflow is defined, or filter by workflow name or status.

1. Choose **Edit**.

1. Choose **YAML**.

1. At the top-left, choose **\$1 Actions** to open the action catalog.

1. From the drop-down list, choose **Amazon CodeCatalyst**.

1. Search for the **Deploy to Amazon ECS** action, and do one of the following:
   + Choose the plus sign (**\$1**) to add the action to the workflow diagram and open its configuration pane.

     Or
   + Choose **Deploy to Amazon ECS**. The action details dialog box appears. On this dialog box:
     + (Optional) Choose **Download** to [view the action's source code](workflows-view-source.md#workflows-view-source.title).
     + Choose **Add to workflow** to add the action to the workflow diagram and open its configuration pane.

1. Modify the properties in the YAML code according to your needs. An explanation of each available property is provided in the ['Deploy to Amazon ECS' action YAML](deploy-action-ref-ecs.md).

1. (Optional) Choose **Validate** to validate the workflow's YAML code before committing.

1. Choose **Commit**, enter a commit message, and choose **Commit** again.

------

# 'Deploy to Amazon ECS' variables
<a name="deploy-action-ecs-variables"></a>

The **Deploy to Amazon ECS** action produces and sets the following variables at run time. These are known as *predefined variables*.

For information about referencing these variables in a workflow, see [Using predefined variables](workflows-using-predefined-variables.md).


| Key | Value | 
| --- | --- | 
|  cluster  |  The name of the Amazon ECS cluster that was deployed to during the workflow run. Example: `codecatalyst-ecs-cluster`  | 
|  deployment-platform  |  The name of the deployment platform. Hardcoded to `AWS:ECS`.  | 
|  service  |  The name of the Amazon ECS service that was deployed to during the workflow run. Example: `codecatalyst-ecs-service`  | 
|  task-definition-arn  |  The Amazon Resource Name (ARN) of the task definition that was registered during the workflow run. Example: `arn:aws:ecs:us-west-2:111122223333:task-definition/codecatalyst-task-def:8`The `:8` in the preceding example indicates the revision that was registered.  | 
|  deployment-url  |  A link to the Amazon ECS console's **Events** tab, where you can view details of the Amazon ECS deployment associated with the workflow run. Example: `https://console.aws.amazon.com/ecs/home?region=us-west-2#/clusters/codecatalyst-ecs-cluster/services/codecatalyst-ecs-service/events`  | 
|  region  |  The region code of the AWS Region that was deployed to during the workflow run. Example: `us-west-2`  | 

# 'Deploy to Amazon ECS' action YAML
<a name="deploy-action-ref-ecs"></a>

The following is the YAML definition of the **Deploy to Amazon ECS** action. To learn how to use this action, see [Deploying to Amazon ECS with a workflow](deploy-action-ecs.md).

This action definition exists as a section within a broader workflow definition file. For more information about this file, see [Workflow YAML definition](workflow-reference.md).

**Note**  
Most of the YAML properties that follow have corresponding UI elements in the visual editor. To look up a UI element, use **Ctrl\$1F**. The element will be listed with its associated YAML property.

```
# The workflow definition starts here.
# See Top-level properties for details.
        
Name: MyWorkflow
SchemaVersion: 1.0 
Actions:

# The action definition starts here.   
  ECSDeployAction\$1nn: 
    Identifier: aws/ecs-deploy@v1
    DependsOn:
      - build-action
    Compute:  
      Type: EC2 | Lambda
      Fleet: fleet-name
    Timeout: timeout-minutes
    Environment:
      Name: environment-name
      Connections:
        - Name: account-connection-name
          Role: iam-role-name
    Inputs:
      # Specify a source or an artifact, but not both.
      Sources:
        - source-name-1
      Artifacts:
        - task-definition-artifact
    Configuration: 
      region: us-east-1 
      cluster: ecs-cluster
      service: ecs-service
      task-definition: task-definition-path
      force-new-deployment: false|true
      codedeploy-appspec: app-spec-file-path
      codedeploy-application: application-name
      codedeploy-deployment-group: deployment-group-name
      codedeploy-deployment-description: deployment-description
```

## ECSDeployAction
<a name="deploy.action.ecs.name"></a>

(Required)

Specify the name of the action. All action names must be unique within the workflow. Action names are limited to alphanumeric characters (a-z, A-Z, 0-9), hyphens (-), and underscores (\$1). Spaces are not allowed. You cannot use quotation marks to enable special characters and spaces in action names.

Default: `ECSDeployAction_nn`.

Corresponding UI: Configuration tab/**Action display name**

## Identifier
<a name="deploy.action.ecs.identifier"></a>

(*ECSDeployAction*/**Identifier**)

(Required)

Identifies the action. Do not change this property unless you want to change the version. For more information, see [Specifying the action version to use](workflows-action-versions.md).

Default: `aws/ecs-deploy@v1`.

Corresponding UI: Workflow diagram/ECSDeployAction\$1nn/**aws/ecs-deploy@v1** label

## DependsOn
<a name="deploy.action.ecs.dependson"></a>

(*ECSDeployAction*/**DependsOn**)

(Optional)

Specify an action, action group, or gate that must run successfully in order for this action to run.

For more information about the 'depends on' functionality, see [Sequencing actions](workflows-depends-on.md).

Corresponding UI: Inputs tab/**Depends on - optional**

## Compute
<a name="deploy.action.ecs.computename"></a>

(*ECSDeployAction*/**Compute**)

(Optional)

The computing engine used to run your workflow actions. You can specify compute either at the workflow level or at the action level, but not both. When specified at the workflow level, the compute configuration applies to all actions defined in the workflow. At the workflow level, you can also run multiple actions on the same instance. For more information, see [Sharing compute across actions](compute-sharing.md).

Corresponding UI: *none*

## Type
<a name="deploy.action.ecs.computetype"></a>

(*ECSDeployAction*/Compute/**Type**)

(Required if [Compute](#deploy.action.ecs.computename) is included)

The type of compute engine. You can use one of the following values:
+ **EC2** (visual editor) or `EC2` (YAML editor)

  Optimized for flexibility during action runs.
+ **Lambda** (visual editor) or `Lambda` (YAML editor)

  Optimized action start-up speeds.

For more information about compute types, see [Compute types](workflows-working-compute.md#compute.types).

Corresponding UI: Configuration tab/Advanced - optional/**Compute type**

## Fleet
<a name="deploy.action.ecs.computefleet"></a>

(*ECSDeployAction*/Compute/**Fleet**)

(Optional)

Specify the machine or fleet that will run your workflow or workflow actions. With on-demand fleets, when an action starts, the workflow provisions the resources it needs, and the machines are destroyed when the action finishes. Examples of on-demand fleets: `Linux.x86-64.Large`, `Linux.x86-64.XLarge`. For more information about on-demand fleets, see [On-demand fleet properties](workflows-working-compute.md#compute.on-demand).

With provisioned fleets, you configure a set of dedicated machines to run your workflow actions. These machines remain idle, ready to process actions immediately. For more information about provisioned fleets, see [Provisioned fleet properties](workflows-working-compute.md#compute.provisioned-fleets).

If `Fleet` is omitted, the default is `Linux.x86-64.Large`.

Corresponding UI: Configuration tab/Advanced - optional/**Compute fleet**

## Timeout
<a name="deploy.action.ecs.timeout"></a>

(*ECSDeployAction*/**Timeout**)

(Optional)

Specify the amount of time in minutes (YAML editor), or hours and minutes (visual editor), that the action can run before CodeCatalyst ends the action. The minimum is 5 minutes and the maximum is described in [Quotas for workflows in CodeCatalyst](workflows-quotas.md). The default timeout is the same as the maximum timeout.

Corresponding UI: Configuration tab/**Timeout - optional **

## Environment
<a name="deploy.action.ecs.environment"></a>

(*ECSDeployAction*/**Environment**)

(Required)

Specify the CodeCatalyst environment to use with the action. The action connects to the AWS account and optional Amazon VPC specified in the chosen environment. The action uses the default IAM role specified in the environment to connect to the AWS account, and uses the IAM role specified in the [Amazon VPC connection](https://docs.aws.amazon.com/codecatalyst/latest/adminguide/managing-vpcs.add.html) to connect to the Amazon VPC.

**Note**  
If the default IAM role does not have the permissions required by the action, you can configure the action to use a different role. For more information, see [Changing the IAM role of an action](deploy-environments-switch-role.md).

For more information about environments, see [Deploying into AWS accounts and VPCs](deploy-environments.md) and [Creating an environment](deploy-environments-creating-environment.md).

Corresponding UI: Configuration tab/**Environment**

## Name
<a name="deploy.action.ecs.environment.name"></a>

(*ECSDeployAction*/Environment/**Name**)

(Required if [Environment](#deploy.action.ecs.environment) is included)

Specify the name of an existing environment that you want to associate with the action.

Corresponding UI: Configuration tab/**Environment**

## Connections
<a name="deploy.action.ecs.environment.connections"></a>

(*ECSDeployAction*/Environment/**Connections**)

(Optional in newer versions of the action; required in older versions)

Specify the account connection to associate with the action. You can specify a maximum of one account connection under `Environment`.

If you do not specify an account connection:
+ The action uses the AWS account connection and default IAM role specified in the environment in the CodeCatalyst console. For information about adding an account connection and default IAM role to environment, see [Creating an environment](deploy-environments-creating-environment.md).
+ The default IAM role must include the policies and permissions required by the action. To determine what those policies and permissions are, see the description of the **Role** property in the action's YAML definition documentation.

For more information about account connections, see [Allowing access to AWS resources with connected AWS accounts](ipa-connect-account.md). For information about adding an account connection to an environment, see [Creating an environment](deploy-environments-creating-environment.md).

Corresponding UI: One of the following depending on the action version:
+ (Newer versions) Configuration tab/Environment/What's in *my-environment*?/three dot menu/**Switch role**
+ (Older versions) Configuration tab/'Environment/account/role'/**AWS account connection**

## Name
<a name="deploy.action.ecs.environment.connections.name"></a>

(*ECSDeployAction*/Environment/Connections/**Name**)

(Required if [Connections](#deploy.action.ecs.environment.connections) is included)

Specify the name of the account connection.

Corresponding UI: One of the following depending on the action version:
+ (Newer versions) Configuration tab/Environment/What's in *my-environment*?/three dot menu/**Switch role**
+ (Older versions) Configuration tab/'Environment/account/role'/**AWS account connection**

## Role
<a name="deploy.action.ecs.environment.connections.role"></a>

(*ECSDeployAction*/Environment/Connections/**Role**)

(Required if [Connections](#deploy.action.ecs.environment.connections) is included)

Specify the name of the IAM role that the **Deploy to Amazon ECS** action uses to access AWS. Make sure that you have [added the role to your CodeCatalyst space](ipa-connect-account-addroles.md), and that the role includes the following policies.

If you do not specify an IAM role, then the action uses the default IAM role listed in the [environment](deploy-environments.md) in the CodeCatalyst console. If you use the default role in the environment, make sure it has the following policies.
+ The following permissions policy:
**Warning**  
Limit the permissions to those shown in the following policy. Using a role with broader permissions might pose a security risk.

------
#### [ JSON ]

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Statement": [{
      "Action":[
        "ecs:DescribeServices",
        "ecs:CreateTaskSet",
        "ecs:DeleteTaskSet",
        "ecs:ListClusters",
        "ecs:RegisterTaskDefinition",
        "ecs:UpdateServicePrimaryTaskSet",
        "ecs:UpdateService",
        "elasticloadbalancing:DescribeTargetGroups",
        "elasticloadbalancing:DescribeListeners",
        "elasticloadbalancing:ModifyListener",
        "elasticloadbalancing:DescribeRules",
        "elasticloadbalancing:ModifyRule",
        "lambda:InvokeFunction",
        "lambda:ListFunctions",
        "cloudwatch:DescribeAlarms",
        "sns:Publish",
        "sns:ListTopics", 
        "s3:GetObject",
        "s3:GetObjectVersion",
        "codedeploy:CreateApplication", 
        "codedeploy:CreateDeployment", 
        "codedeploy:CreateDeploymentGroup", 
        "codedeploy:GetApplication", 
        "codedeploy:GetDeployment", 
        "codedeploy:GetDeploymentGroup", 
        "codedeploy:ListApplications", 
        "codedeploy:ListDeploymentGroups", 
        "codedeploy:ListDeployments", 
        "codedeploy:StopDeployment", 
        "codedeploy:GetDeploymentTarget", 
        "codedeploy:ListDeploymentTargets", 
        "codedeploy:GetDeploymentConfig", 
        "codedeploy:GetApplicationRevision", 
        "codedeploy:RegisterApplicationRevision", 
        "codedeploy:BatchGetApplicationRevisions", 
        "codedeploy:BatchGetDeploymentGroups", 
        "codedeploy:BatchGetDeployments", 
        "codedeploy:BatchGetApplications", 
        "codedeploy:ListApplicationRevisions", 
        "codedeploy:ListDeploymentConfigs", 
        "codedeploy:ContinueDeployment"           
     ],
     "Resource":"*",
     "Effect":"Allow"
  },{"Action":[
        "iam:PassRole"
     ],
     "Effect":"Allow",
     "Resource":"*",
     "Condition":{"StringLike":{"iam:PassedToService":[
              "ecs-tasks.amazonaws.com",
              "codedeploy.amazonaws.com"
           ]
        }
     }
  }]
  }
  ```

------
**Note**  
The first time the role is used, use the following wildcard in the resource policy statement and then scope down the policy with the resource name after it is available.  

  ```
  "Resource": "*"
  ```
+ The following custom trust policy:

**Note**  
You can use the `CodeCatalystWorkflowDevelopmentRole-spaceName` role with this action, if you'd like. For more information about this role, see [Creating the **CodeCatalystWorkflowDevelopmentRole-*spaceName*** role for your account and space](ipa-iam-roles.md#ipa-iam-roles-service-create). Understand that the `CodeCatalystWorkflowDevelopmentRole-spaceName` role has full access permissions which may pose a security risk. We recommend that you only use this role in tutorials and scenarios where security is less of a concern. 

Corresponding UI: One of the following depending on the action version:
+ (Newer versions) Configuration tab/Environment/What's in *my-environment*?/three dot menu/**Switch role**
+ (Older versions) Configuration tab/'Environment/account/role'/**Role**

## Inputs
<a name="deploy.action.ecs.inputs"></a>

(*ECSDeployAction*/**Inputs**)

(Optional)

The `Inputs` section defines the data that the `ECSDeployAction` needs during a workflow run.

**Note**  
Only one input (either a source or an artifact) is allowed per **Deploy to Amazon ECS** action.

Corresponding UI: **Inputs** tab

## Sources
<a name="deploy.action.ecs.inputs.sources"></a>

(*ECSDeployAction*/Inputs/**Sources**)

(Required if your task definition file is stored in a source repository)

If your task definition file is stored in a source repository, specify the label of that source repository. Currently, the only supported label is `WorkflowSource`.

If your task definition file is not contained within a source repository, it must reside in an artifact generated by another action.

For more information about sources, see [Connecting source repositories to workflows](workflows-sources.md).

Corresponding UI: Inputs tab/**Sources - optional**

## Artifacts - input
<a name="deploy.action.ecs.inputs.artifacts"></a>

(*ECSDeployAction*/Inputs/**Artifacts**)

(Required if your task definition file is stored in an [output artifact](workflows-working-artifacts-output.md) from a previous action)

If the task definition file that you want to deploy is contained in an artifact generated by a previous action, specify that artifact here. If your task definition file is not contained within an artifact, it must reside in your source repository.

For more information about artifacts, including examples, see [Sharing artifacts and files between actions](workflows-working-artifacts.md).

Corresponding UI: Configuration tab/**Artifacts - optional**

## Configuration
<a name="deploy.action.ecs.configuration"></a>

(*ECSDeployAction*/**Configuration**)

(Required)

A section where you can define the configuration properties of the action.

Corresponding UI: **Configuration** tab

## region
<a name="deploy.action.ecs.region"></a>

(Configuration/**region**)

(Required)

Specify the AWS Region where your Amazon ECS cluster and service reside. For a list of Region codes, see [Regional endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html#regional-endpoints) in the *AWS General Reference*.

Corresponding UI: Configuration tab/**Region**

## cluster
<a name="deploy.action.ecs.cluster"></a>

(*ECSDeployAction*/Configuration/**cluster**)

(Required)

Specify the name of an existing Amazon ECS cluster. The **Deploy to Amazon ECS** action will deploy your containerized application as a task into this cluster. For more information about Amazon ECS clusters, see [Clusters](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html#welcome-clusters) in the *Amazon Elastic Container Service Developer Guide*.

Corresponding UI: Configuration tab/**Cluster**

## service
<a name="deploy.action.ecs.service"></a>

(*ECSDeployAction*/Configuration/**service**)

(Required)

Specify the name of an existing Amazon ECS service that will instantiate the task definition file. This service must reside under the cluster specified in the `cluster` field. For more information about Amazon ECS services, see [Amazon ECS services](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_services.html) in the *Amazon Elastic Container Service Developer Guide*.

Corresponding UI: Configuration tab/**Service**

## task-definition
<a name="deploy.action.ecs.task.definition"></a>

(*ECSDeployAction*/Configuration/**task-definition**)

(Required)

Specify the path to an existing task definition file. If the file resides in your source repository, the path is relative to the source repository root folder. If your file resides in an artifact from a previous workflow action, the path is relative to the artifact root folder. For more information about task definition files, see [Task definitions](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html#welcome-task-definitions) in the *Amazon Elastic Container Service Developer Guide*.

Corresponding UI: Configuration tab/**Task definition**

## force-new-deployment
<a name="deploy.action.ecs.forcenewdeployment"></a>

(*ECSDeployAction*/Configuration/**force-new-deployment**)

(Required)

If enabled, the Amazon ECS service is able to start new deployments without service definition changes. Forcing a deployment causes the service to stop all currently running tasks and launch new tasks. For more information about forcing new deployments, see [Updating a service](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/update-service.html) in the *Amazon Elastic Container Service Developer Guide*.

Default: `false`

Corresponding UI: Configuration tab/**Force a new deployment of the service**

## codedeploy-appspec
<a name="deploy.action.ecs.codedeploy.appspec"></a>

(*ECSDeployAction*/Configuration/**codedeploy-appspec**)

(Required if you have configured your Amazon ECS service to use blue/green deployments, otherwise, omit)

Specify the name and path to an existing CodeDeploy application specification (AppSpec) file. This file must reside in the root of your CodeCatalyst source repository. For more information about AppSpec files, see [CodeDeploy application specification (AppSpec) files](https://docs.aws.amazon.com/codedeploy/latest/userguide/application-specification-files.html) in the *AWS CodeDeploy User Guide*.

**Note**  
Only supply CodeDeploy information if you have configured your Amazon ECS service to perform blue/green deployments. For rolling update deployments (the default), omit CodeDeploy information. For more information about Amazon ECS deployments, see [Amazon ECS deployment types](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/deployment-types.html) in the *Amazon Elastic Container Service Developer Guide*.

**Note**  
The **CodeDeploy** fields may be hidden in the visual editor. To get them to appear, see [Why are CodeDeploy fields missing from the visual editor?](troubleshooting-workflows.md#troubleshooting-workflows-codedeploy).

Corresponding UI: Configuration tab/**CodeDeploy AppSpec**

## codedeploy-application
<a name="deploy.action.ecs.codedeploy.application"></a>

(*ECSDeployAction*/Configuration/**codedeploy-application**)

(Required if `codedeploy-appspec` is included)

Specify the name of an existing CodeDeploy application. For more information about CodeDeploy applications, see [Working with applications in CodeDeploy](https://docs.aws.amazon.com/codedeploy/latest/userguide/applications.html) in the *AWS CodeDeploy User Guide*.

Corresponding UI: Configuration tab/**CodeDeploy application**

## codedeploy-deployment-group
<a name="deploy.action.ecs.codedeploy.deploymentgroup"></a>

(*ECSDeployAction*/Configuration/**codedeploy-deployment-group**)

(Required if `codedeploy-appspec` is included)

Specify the name of an existing CodeDeploy deployment group. For more information about CodeDeploy deployment groups, see [Working with deployment groups in CodeDeploy](https://docs.aws.amazon.com/codedeploy/latest/userguide/deployment-groups.html) in the *AWS CodeDeploy User Guide*.

Corresponding UI: Configuration tab/**CodeDeploy deployment group**

## codedeploy-deployment-description
<a name="deploy.action.ecs.codedeploy.deploymentdescription"></a>

(*ECSDeployAction*/Configuration/**codedeploy-deployment-description**)

(Optional)

Specify a description of the deployment that this action will create. For more information, see [Working with deployments in CodeDeploy](https://docs.aws.amazon.com/codedeploy/latest/userguide/deployments.html) in the *AWS CodeDeploy User Guide*.

Corresponding UI: Configuration tab/**CodeDeploy deployment description**

# Deploying to Amazon EKS with a workflow
<a name="deploy-action-eks"></a>

**Tip**  
For a tutorial that shows you how to use the **Deploy to Kubernetes cluster ** action, see [Tutorial: Deploy an application to Amazon EKS](deploy-tut-eks.md).

This section describes how to deploy a containerized application into a Kubernetes cluster using a CodeCatalyst workflow. To accomplish this, you must add the **Deploy to Kubernetes cluster** action to your workflow. This action deploys your application to a Kubernetes cluster that you have set up in Amazon Elastic Kubernetes Service (EKS) using one or more Kubernetes manifest files. For a sample manifest, see [deployment.yaml](deploy-tut-eks.md#deploy-tut-eks-source-files-deployment-yml) in [Tutorial: Deploy an application to Amazon EKS](deploy-tut-eks.md).

For more information about Kubernetes, see the [Kubernetes Documentation](https://kubernetes.io/docs/home/).

For more information about Amazon EKS, see [What is Amazon EKS?](https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html) in the *Amazon EKS User Guide*.

**Topics**
+ [How the 'Deploy to Kubernetes cluster' action works](#deploy-action-eks-howitworks)
+ [Runtime image used by the 'Deploy to Amazon EKS' action](#deploy-action-eks-runtime)
+ [Tutorial: Deploy an application to Amazon EKS](deploy-tut-eks.md)
+ [Adding the 'Deploy to Kubernetes cluster' action](deploy-action-eks-adding.md)
+ ['Deploy to Kubernetes cluster' variables](deploy-action-eks-variables.md)
+ ['Deploy to Kubernetes cluster' action YAML](deploy-action-ref-eks.md)

## How the 'Deploy to Kubernetes cluster' action works
<a name="deploy-action-eks-howitworks"></a>

The **Deploy to Kubernetes cluster** works as follows:

1. At runtime, the action installs the Kubernetes `kubectl` utility to the CodeCatalyst compute machine where the action is running. The action configures `kubectl` to point to the Amazon EKS cluster you provided when you configured the action. The `kubectl` utility is necessary to run the `kubectl apply` command, next.

1. The action runs the `kubectl apply -f my-manifest.yaml` command, which carries out the instructions in *my-manifest.yaml* to deploy your application as a set of containers and pods into the configured cluster. For more information on this command, see the [kubectl apply](https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#apply) topic in the *Kubernetes Reference Documentation*.

## Runtime image used by the 'Deploy to Amazon EKS' action
<a name="deploy-action-eks-runtime"></a>

The **Deploy to Amazon EKS** action runs on a [November 2022 image](build-images.md#build.previous-image). For more information, see [Active images](build-images.md#build-curated-images).

# Tutorial: Deploy an application to Amazon EKS
<a name="deploy-tut-eks"></a>

In this tutorial, you learn how to deploy a containerized application into Amazon Elastic Kubernetes Service using an Amazon CodeCatalyst workflow, Amazon EKS, and a few other AWS services. The deployed application is a simple 'Hello, World\$1' website built on an Apache web server Docker image. The tutorial walks you through the required preparation work such as setting up a development machine and an Amazon EKS cluster, and then describes how to create a workflow to build the application and deploy it into the cluster.

After the initial deployment is complete, the tutorial instructs you to make a change to your application source. This change causes a new Docker image to be built and pushed to your Docker image repository with new revision information. The new revision of the Docker image is then deployed into Amazon EKS.

**Tip**  
Instead of working your way through this tutorial, you can use a blueprint that does a complete Amazon EKS setup for you. You'll need to use the **EKS App Deployment** blueprint. For more information, see [Creating a project with a blueprint](projects-create.md#projects-create-console-template).

**Topics**
+ [Prerequisites](#deploy-tut-eks-prereqs)
+ [Step 1: Set up your development machine](#deploy-tut-eks-dev-env-create)
+ [Step 2: Create an Amazon EKS cluster](#deploy-tut-eks-cluster)
+ [Step 3: Create an Amazon ECR image repository](#deploy-tut-eks-ecr)
+ [Step 4: Add source files](#deploy-tut-eks-source-files)
+ [Step 5: Create AWS roles](#deploy-tut-eks-roles)
+ [Step 6: Add AWS roles to CodeCatalyst](#deploy-tut-eks-import-roles)
+ [Step 7: Update the ConfigMap](#deploy-tut-eks-configmap)
+ [Step 8: Create and run a workflow](#deploy-tut-eks-workflow)
+ [Step 9: Make a change to your source files](#deploy-tut-eks-change)
+ [Clean up](#deploy-tut-eks-cleanup)

## Prerequisites
<a name="deploy-tut-eks-prereqs"></a>

Before you begin this tutorial:
+ You need an Amazon CodeCatalyst **space** with a connected AWS account. For more information, see [Creating a space](spaces-create.md).
+ In your space, you need an empty project called:

  ```
  codecatalyst-eks-project
  ```

  Use the **Start from scratch** option to create this project.

  For more information, see [Creating an empty project in Amazon CodeCatalyst](projects-create.md#projects-create-empty).
+ In your project, you need an empty CodeCatalyst **source repository** called:

  ```
  codecatalyst-eks-source-repository
  ```

  For more information, see [Store and collaborate on code with source repositories in CodeCatalystStore and collaborate on code with source repositories](source.md).
+ In your project, you need a CodeCatalyst CI/CD **environment** (not a Dev Environment) called:

  ```
  codecatalyst-eks-environment
  ```

  Configure this environment as follows:
  + Choose any type, such as **Non-production**.
  + Connect your AWS account to it. 
  + For the **Default IAM role**, choose any role. You'll specify a different role later.

  For more information, see [Deploying into AWS accounts and VPCs](deploy-environments.md).

## Step 1: Set up your development machine
<a name="deploy-tut-eks-dev-env-create"></a>

The first step in this tutorial is to configure a development machine with a few tools that you'll use throughout this tutorial. These tools are:
+ the `eksctl` utility – for cluster creation
+ the `kubectl` utility – a prerequisite for `eksctl`
+ the AWS CLI – also a prerequisite for `eksctl`

You can install these tools on your existing development machine if you have one, or you can use a CodeCatalyst Dev Environment, which is Cloud-based. The benefit of a CodeCatalyst Dev Environment is that it's easy to spin up and take down, and is integrated with other CodeCatalyst services, allowing you to work through this tutorial in fewer steps.

This tutorial assumes you'll be using a CodeCatalyst Dev Environment.

The following instructions describe a quick way to launch a CodeCatalyst Dev Environment and configure it with the required tools, but if you want detailed instructions, see:
+ [Creating a Dev Environment](devenvironment-create.md) in this guide.
+ [Installing kubectl](https://docs.aws.amazon.com/eks/latest/userguide/install-kubectl.html) in the **Amazon EKS User Guide**.
+ [Installing or upgrading eksctl](https://docs.aws.amazon.com/eks/latest/userguide/eksctl.html) in the **Amazon EKS User Guide**.
+ [Installing or updating the latest version of the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) in the *AWS Command Line Interface User Guide*.

**To launch a Dev Environment**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Navigate to your project, `codecatalyst-eks-project`.

1. In the navigation pane, choose **Code**, and then choose **Source repositories**. 

1. Choose the name of your source repository, `codecatalyst-eks-source-repository`.

1. Near the top choose **Create Dev Environment**, and then choose **AWS Cloud9 (in browser)**.

1. Make sure that **Work in existing branch** and **main** are selected, and then choose **Create**.

   Your Dev Environment launches in a new browser tab, and your repository (`codecatalyst-eks-source-repository`) is cloned into it.

**To install and configure kubectl**

1. In the Dev Environment terminal, enter:

   ```
   curl -o kubectl https://amazon-eks.s3.us-west-2.amazonaws.com/1.18.9/2020-11-02/bin/linux/amd64/kubectl
   ```

1. Enter:

   ```
   chmod +x ./kubectl
   ```

1. Enter:

   ```
   mkdir -p $HOME/bin && cp ./kubectl $HOME/bin/kubectl && export PATH=$PATH:$HOME/bin
   ```

1. Enter:

   ```
   echo 'export PATH=$PATH:$HOME/bin' >> ~/.bashrc
   ```

1. Enter:

   ```
   kubectl version --short --client
   ```

1. Check that a version appears.

   You have now installed `kubectl`.

**To install and configure eksctl**
**Note**  
`eksctl` is not strictly required because you can use `kubectl` instead. However, `eksctl` has the benefit of automating much of the cluster configuration, and is therefore the tool recommended for this tutorial.

1. In the Dev Environment terminal, enter:

   ```
   curl --silent --location "https://github.com/weaveworks/eksctl/releases/latest/download/eksctl_$(uname -s)_amd64.tar.gz" | tar xz -C /tmp
   ```

1. Enter:

   ```
   sudo cp /tmp/eksctl /usr/bin
   ```

1. Enter:

   ```
   eksctl version
   ```

1. Check that a version appears.

   You have now installed `eksctl`.

**To verify that the AWS CLI is installed**

1. In the Dev Environment terminal, enter:

   ```
   aws --version
   ```

1. Check that a version appears to verify that the AWS CLI is installed.

   Complete the remaining procedures to configure the AWS CLI with the necessary permissions to access AWS.

**To configure the AWS CLI**

You must configure the AWS CLI with access keys and a session token to give it access to AWS services. The following instructions provide a quick way to configure the keys and token, but if you want detailed instructions, see [Configuring the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html) in the *AWS Command Line Interface User Guide*.

1. Create an IAM Identity Center user, as follows:

   1. Sign in to the AWS Management Console and open the AWS IAM Identity Center console at [https://console.aws.amazon.com/singlesignon/](https://console.aws.amazon.com/singlesignon/).

      (You might need to choose **Enable** if you've never signed in to IAM Identity Center before.)
**Note**  
Make sure you sign in using the AWS account that is connected to your CodeCatalyst space. You can verify which account is connected by navigating to your space and choosing the **AWS accounts** tab. For more information, see [Creating a space](spaces-create.md).

   1. In the navigation pane, choose **Users**, and then choose **Add user**.

   1. In **Username**, enter:

      ```
      codecatalyst-eks-user
      ```

   1. Under **Password**, choose **Generate a one-time password that you can share with this user**.

   1. In **Email address** and **Confirm email address**, enter an email address that doesn't already exist in IAM Identity Center.

   1. In **First name**, enter:

      ```
      codecatalyst-eks-user
      ```

   1. In **Last name**, enter:

      ```
      codecatalyst-eks-user
      ```

   1. In **Display name**, keep:

      ```
      codecatalyst-eks-user codecatalyst-eks-user
      ```

   1. Choose **Next**.

   1. On the **Add user to groups** page, choose **Next**.

   1. On the **Review and add user** page, review the information and choose **Add user**.

      A **One-time password** dialog box appears.

   1. Choose **Copy** and then paste the sign-in information to a text file. The sign-in information consists of the AWS access portal URL, a user name, and a one-time password.

   1. Choose **Close**.

1. Create a permission set, as follows:

   1. In the navigation pane, choose **Permission sets**, and then choose **Create permission set**.

   1. Choose **Predefined permission set** and then select **AdministratorAccess**. This policy provides full permissions to all AWS services. 

   1. Choose **Next**.

   1. In **Permission set name**, remove `AdministratorAccess` and enter:

      ```
      codecatalyst-eks-permission-set
      ```

   1. Choose **Next**.

   1. On the **Review and create** page, review the information and choose **Create**.

1. Assign the permission set to `codecatalyst-eks-user`, as follows:

   1. In the navigation pane, choose **AWS accounts**, and then select the check box next to the AWS account that you're currently signed in to.

   1. Choose **Assign users or groups**.

   1. Choose the **Users** tab.

   1. Select the check box next to `codecatalyst-eks-user`.

   1. Choose **Next**.

   1. Select the check box next to `codecatalyst-eks-permission-set`.

   1. Choose **Next**.

   1. Review the information and choose **Submit**.

      You have now assigned `codecatalyst-eks-user` and `codecatalyst-eks-permission-set` to your AWS account, binding them together.

1. Obtain `codecatalyst-eks-user`'s access keys and session token, as follows:

   1. Make sure you have the AWS access portal URL and the username and one-time password for `codecatalyst-eks-user`. You should have copied this information to a text editor earlier.
**Note**  
If you do not have this information, go to the `codecatalyst-eks-user` details page in IAM Identity Center, choose **Reset password**, **Generate a one-time password [...]**, and **Reset password** again to display the information on the screen.

   1. Sign out of AWS.

   1. Paste the AWS access portal URL into your browser's address bar.

   1. Sign in with:
      + **Username**:

        ```
        codecatalyst-eks-user
        ```
      + **Password**:

        *one-time-password*

   1. In **Set new password**, enter a new password and choose **Set new password**.

      An **AWS account** box appears on the screen.

   1. Choose **AWS account**, and then choose the name of the AWS account to which you assigned the `codecatalyst-eks-user` user and permission set.

   1. Next to `codecatalyst-eks-permission-set`, choose **Command line or programmatic access**.

   1. Copy the commands in the middle of the page. They look similar to the following:

      ```
      export AWS_ACCESS_KEY_ID="AKIAIOSFODNN7EXAMPLE" 
      export AWS_SECRET_ACCESS_KEY="wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY" 
      export AWS_SESSION_TOKEN="session-token"
      ```

      ...where *session-token* is a long random string.

1. Add the access keys and session token to the AWS CLI, as follows:

   1. Return to your CodeCatalyst Dev Environment.

   1. At the terminal prompt, paste the commands you copied. Press Enter.

      You have now configured the AWS CLI with access keys and a session token. You can now use AWS CLI to complete the tasks required by this tutorial.
**Important**  
If at any time during this tutorial you see messages similar to:  
`Unable to locate credentials. You can configure credentials by running "aws configure".`  
Or:  
`ExpiredToken: The security token included in the request is expired`  
...it's because your AWS CLI session has expired. In this case, do *not* run the `aws configure` command. Instead, use the instructions in step 4 of this procedure that starts with `Obtain codecatalyst-eks-user's access key and session token` to refresh your session.

## Step 2: Create an Amazon EKS cluster
<a name="deploy-tut-eks-cluster"></a>

In this section, you create a cluster in Amazon EKS. The instructions below describe a quick way to create the cluster using `eksctl`, but if you want detailed instructions, see:
+ [Getting started with eksctl](https://docs.aws.amazon.com/eks/latest/userguide/getting-started-eksctl.html) in the **Amazon EKS User Guide**

  or
+ [Getting started with the console and AWS CLI](https://docs.aws.amazon.com/eks/latest/userguide/getting-started-console.html) in the **Amazon EKS User Guide** (this topic provides `kubectl` instructions for creating the cluster) 

**Note**  
[Private clusters](https://docs.aws.amazon.com/eks/latest/userguide/private-clusters.html) are not supported by the CodeCatalyst integration with Amazon EKS.

**Before you begin**

Make sure you have completed the following tasks on your development machine:
+ Installed the `eksctl` utility.
+ Installed the `kubectl` utility.
+ Installed the AWS CLI and configured it with access keys and a session token.

For information on how to complete these tasks, see [Step 1: Set up your development machine](#deploy-tut-eks-dev-env-create).

**To create a cluster**
**Important**  
Do not use the Amazon EKS service's user interface to create the cluster because the cluster won't be configured correctly. Use the `eksctl` utility, as described in the following steps.

1. Go to your Dev Environment.

1. Create a cluster and nodes:

   ```
   eksctl create cluster --name codecatalyst-eks-cluster --region us-west-2
   ```

   Where:
   + *codecatalyst-eks-cluster* is replaced with the name you want to give your cluster.
   + *us-west-2* is replaced with your Region.

   After 10-20 minutes, a message similar to the following appears: 

   `EKS cluster "codecatalyst-eks-cluster" in "us-west-2" region is ready`
**Note**  
You will see multiple `waiting for CloudFormation stack` messages while AWS creates your cluster. This is expected.

1. Verify that your cluster was created successfully:

   ```
   kubectl cluster-info
   ```

   You will see a message similar to the following, indicating a sucessful cluster creation:

   ```
   Kubernetes master is running at https://long-string.gr7.us-west-2.eks.amazonaws.com
   CoreDNS is running at https://long-string.gr7.us-west-2.eks.amazonaws.com/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
   ```

## Step 3: Create an Amazon ECR image repository
<a name="deploy-tut-eks-ecr"></a>

In this section, you create a private image repository in Amazon Elastic Container Registry (Amazon ECR). This repository stores the Docker image for the tutorial.

For more information about Amazon ECR, see the *Amazon Elastic Container Registry User Guide*.

**To create an image repository in Amazon ECR**

1. Go to your Dev Environment.

1. Create an empty repository in Amazon ECR:

   ```
   aws ecr create-repository --repository-name codecatalyst-eks-image-repo
   ```

   Replace *codecatalyst-eks-image-repo* with the name you want to give the Amazon ECR repository.

   This tutorial assumes you named your repository `codecatalyst-eks-image-repo`.

1. Display the Amazon ECR repository’s details:

   ```
   aws ecr describe-repositories \
         --repository-names codecatalyst-eks-image-repo
   ```

1. Note the `“repositoryUri”:` value, for example, `111122223333.dkr.ecr.us-west-2.amazonaws.com/codecatalyst-eks-image-repo`.

   You need it later when adding the repository to your workflow. 

## Step 4: Add source files
<a name="deploy-tut-eks-source-files"></a>

In this section, you add application source files to your source repository (`codecatalyst-eks-source-repository`). They consist of:
+ An `index.html` file – Displays a 'Hello, World\$1' message in the browser.
+ A Dockerfile – Describes the base image to use for your Docker image and the Docker commands to apply to it.
+ A `deployment.yaml` file – The Kubernetes manifest that defines the Kubernetes service and deployment. 

The folder structure is as follows:

```
|— codecatalyst-eks-source-repository
   |— Kubernetes
      |— deployment.yaml
   |— public-html
   |  |— index.html
   |— Dockerfile
```

**Topics**
+ [index.html](#deploy-tut-eks-source-files-index)
+ [Dockerfile](#deploy-tut-eks-source-files-dockerfile)
+ [deployment.yaml](#deploy-tut-eks-source-files-deployment-yml)

### index.html
<a name="deploy-tut-eks-source-files-index"></a>

The `index.html` file displays a 'Hello, World\$1' message in the browser. 

**To add the index.html file**

1. Go to your Dev Environment.

1. In `codecatalyst-eks-source-repository`, create a folder called `public-html`.

1. In `/public-html`, create a file called `index.html` with the following contents:

   ```
   <html>
     <head>
       <title>Hello World</title>
       <style>
         body {
         background-color: black;
         text-align: center;
         color: white;
         font-family: Arial, Helvetica, sans-serif;
         }  
       </style>
     </head>
     <body>
       <h1>Hello, World!</h1>
     </body>
   </html>
   ```

1. At the terminal prompt, enter:

   ```
   cd /projects/codecatalyst-eks-source-repository
   ```

1. Add, commit, and push:

   ```
   git add .
   git commit -m "add public-html/index.html"
   git push
   ```

   The `index.html` is added to your repository in a `public-html` folder. 

### Dockerfile
<a name="deploy-tut-eks-source-files-dockerfile"></a>

The Dockerfile describes the base Docker image to use and the Docker commands to apply to it. For more information about the Dockerfile, see the [Dockerfile Reference](https://docs.docker.com/engine/reference/builder/).

The Dockerfile specified here indicates to use the Apache 2.4 base image (`httpd`). It also includes instructions for copying a source file called `index.html` to a folder on the Apache server that serves webpages. The `EXPOSE` instruction in the Dockerfile tells Docker that the container is listening on port 80.

**To add the Dockerfile**

1. In `codecatalyst-eks-source-repository`, create a file called `Dockerfile` with the following contents:

   ```
   FROM httpd:2.4
   COPY ./public-html/index.html /usr/local/apache2/htdocs/index.html
   EXPOSE 80
   ```

   Do not include a file extension.
**Important**  
The Dockerfile must reside in your repository’s root folder. The workflow’s `Docker build` command expects it to be there.

1. Add, commit, and push:

   ```
   git add .
   git commit -m "add Dockerfile"
   git push
   ```

   The Dockerfile is added to your repository.

### deployment.yaml
<a name="deploy-tut-eks-source-files-deployment-yml"></a>

In this section, you add a `deployment.yaml` file to your repository. The `deployment.yaml` file is a Kubernetes manifest that defines two Kubernetes resources types or *kinds* to run: a 'service' and a 'deployment'.
+ The 'service' deploys a load balancer into Amazon EC2. The load balancer provides you with an Internet-facing public URL and standard port (port 80) that you can use to browse to the 'Hello, World\$1' application. 
+ The 'deployment' deploys three pods, and each pod will contain a Docker container with the 'Hello, World\$1' application. The three pods are deployed onto the nodes that were created when you created the cluster.

The manifest in this tutorial is short; however, a manifest can include any number of Kubernetes resource types, such as pods, jobs, ingresses, and network policies. Further, you can use multiple manifest files if your deployment is complex.

**To add a deployment.yaml file**

1. In `codecatalyst-eks-source-repository`, create a folder called `Kubernetes`.

1. In `/Kubernetes`, create a file called `deployment.yaml` with the following contents:

   ```
   apiVersion: v1
   kind: Service
   metadata:
     name: my-service
     labels:
       app: my-app
   spec:
     type: LoadBalancer
     selector:
       app: my-app
     ports:
       - protocol: TCP
         port: 80
         targetPort: 80
   ---
   apiVersion: apps/v1
   kind: Deployment
   metadata:
     name: my-deployment
     labels:
       app: my-app
   spec:
     replicas: 3
     selector:
       matchLabels:
         app: my-app
     template:
       metadata:
         labels:
           app: my-app
       spec:
         containers:
         - name: codecatalyst-eks-container
           # The $REPOSITORY_URI and $IMAGE_TAG placeholders will be replaced by actual values supplied by the build action in your workflow
           image: $REPOSITORY_URI:$IMAGE_TAG
           ports:
           - containerPort: 80
   ```

1. Add, commit, and push:

   ```
   git add .
   git commit -m "add Kubernetes/deployment.yaml"
   git push
   ```

   The `deployment.yaml` file is added to your repository in a folder called `Kubernetes`. 

You have now added all your source files.

Take a moment to double-check your work and make sure you placed all the files in the correct folders. The folder structure is as follows:

```
|— codecatalyst-eks-source-repository
   |— Kubernetes
      |— deployment.yaml
   |— public-html
   |  |— index.html
   |— Dockerfile
```

## Step 5: Create AWS roles
<a name="deploy-tut-eks-roles"></a>

In this section, you create AWS IAM roles that your CodeCatalyst workflow will need in order to function. These roles are:
+ **Build role** – Grants the CodeCatalyst build action (in the workflow) permission to access your AWS account and write to Amazon ECR and Amazon EC2.
+ **Deploy role** – Grants the CodeCatalyst **Deploy to Kubernetes cluster** action (in the workflow) permission to access your AWS account and Amazon EKS.

For more information about IAM roles, see [IAM roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) in the *AWS Identity and Access Management User Guide*.

**Note**  
To save time, you can create a single role, called the `CodeCatalystWorkflowDevelopmentRole-spaceName` role, instead of the two roles listed previously. For more information, see [Creating the **CodeCatalystWorkflowDevelopmentRole-*spaceName*** role for your account and space](ipa-iam-roles.md#ipa-iam-roles-service-create). Understand that the `CodeCatalystWorkflowDevelopmentRole-spaceName` role has very broad permissions which may pose a security risk. We recommend that you only use this role in tutorials and scenarios where security is less of a concern. This tutorial assumes you are creating the two roles listed previously.

To create the build and deploy roles, complete the following series of procedures.

**1. To create a trust policy for both roles**

1. Go to your Dev Environment.

1. In the `Cloud9-long-string` directory, create a file called `codecatalyst-eks-trust-policy.json` with the following contents:

**2. To create the build policy for the build role**
+ In the `Cloud9-long-string` directory, create a file called `codecatalyst-eks-build-policy.json` with the following contents:

------
#### [ JSON ]

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Statement": [
          {
              "Effect": "Allow",
              "Action": [
                  "ecr:*",
                  "ec2:*"
              ],
              "Resource": "*"
          }
      ]
  }
  ```

------
**Note**  
The first time the role is used to run workflow actions, use the wildcard in the resource policy statement and then scope down the policy with the resource name after it is available.  

  ```
  "Resource": "*"
  ```

**3. To create the deploy policy for the deploy role**
+ In the `Cloud9-long-string` directory, create a file called `codecatalyst-eks-deploy-policy.json` with the following contents:

------
#### [ JSON ]

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Statement": [
          {
              "Effect": "Allow",
              "Action": [
                  "eks:DescribeCluster",
                  "eks:ListClusters"
              ],
              "Resource": "*"
          }
      ]
  }
  ```

------
**Note**  
The first time the role is used to run workflow actions, use the wildcard in the resource policy statement and then scope down the policy with the resource name after it is available.  

  ```
  "Resource": "*"
  ```

You have now added three policy documents to your Dev Environment. Your directory structure now looks like this:

```
|— Cloud9-long-string
   |— .c9
   |— codecatalyst-eks-source-repository
      |— Kubernetes
      |— public-html
      |— Dockerfile
   codecatalyst-eks-build-policy.json
   codecatalyst-eks-deploy-policy.json
   codecatalyst-eks-trust-policy.json
```

**4. To add the build policy to AWS**

1. In the Dev Environment terminal, enter:

   ```
   cd /projects
   ```

1. Enter:

   ```
   aws iam create-policy \
       --policy-name codecatalyst-eks-build-policy \
       --policy-document file://codecatalyst-eks-build-policy.json
   ```

1. Press **Enter**.

1. In the command output, note the `"arn":` value, for example, `arn:aws:iam::111122223333:policy/codecatalyst-eks-build-policy`. You need this ARN later.

**5. To add the deploy policy to AWS**

1. Enter:

   ```
   aws iam create-policy \
       --policy-name codecatalyst-eks-deploy-policy \
       --policy-document file://codecatalyst-eks-deploy-policy.json
   ```

1. Press **Enter**.

1. In the command output, note the deploy policy's `"arn":` value, for example, `arn:aws:iam::111122223333:policy/codecatalyst-eks-deploy-policy`. You need this ARN later.

**6. To create the build role**

1. Enter: 

   ```
   aws iam create-role \
         --role-name codecatalyst-eks-build-role \
         --assume-role-policy-document file://codecatalyst-eks-trust-policy.json
   ```

1. Press **Enter**.

1. Enter:

   ```
   aws iam attach-role-policy \
         --role-name codecatalyst-eks-build-role \
         --policy-arn arn:aws:iam::111122223333:policy/codecatalyst-eks-build-policy
   ```

   Where *arn:aws:iam::111122223333:policy/codecatalyst-eks-build-policy* is replaced with the ARN of the build policy you noted earlier.

1. Press **Enter**.

1. At the terminal prompt, enter:

   ```
   aws iam get-role \
         --role-name codecatalyst-eks-build-role
   ```

1. Press **Enter**.

1. Note the role's `"Arn":` value, for example, `arn:aws:iam::111122223333:role/codecatalyst-eks-build-role`. You need this ARN later.

**7. To create the deploy role**

1. Enter:

   ```
   aws iam create-role \
         --role-name codecatalyst-eks-deploy-role \
         --assume-role-policy-document file://codecatalyst-eks-trust-policy.json
   ```

1. Press **Enter**.

1. Enter:

   ```
   aws iam attach-role-policy \
         --role-name codecatalyst-eks-deploy-role \
         --policy-arn arn:aws:iam::111122223333:policy/codecatalyst-eks-deploy-policy
   ```

   Where *arn:aws:iam::111122223333:policy/codecatalyst-eks-deploy-policy* is replaced with the ARN of the deploy policy you noted earlier.

1. Press **Enter**.

1. Enter:

   ```
   aws iam get-role \
         --role-name codecatalyst-eks-deploy-role
   ```

1. Press **Enter**.

1. Note the role's `"Arn":` value, for example, `arn:aws:iam::111122223333:role/codecatalyst-eks-deploy-role`. You need this ARN later.

You have now created build and deploy roles and noted their ARNs.

## Step 6: Add AWS roles to CodeCatalyst
<a name="deploy-tut-eks-import-roles"></a>

In this step, you add the build role (`codecatalyst-eks-build-role`) and deploy role (`codecatalyst-eks-deploy-role`) to the AWS account that you connected to your space. This makes the roles available for use in your workflow.

**To add build and deploy roles to your AWS account**

1. In the CodeCatalyst console, navigate to your space.

1. At the top, choose **Settings**.

1. In the navigation pane, choose **AWS accounts**. A list of accounts appears.

1. In the **Amazon CodeCatalyst display name** column, copy the display name of the AWS account where you created your build and deploy roles. (It might be a number.) You'll need this value later, when creating your workflow.

1. Choose the display name.

1. Choose **Manage roles from AWS management console**.

   The **Add IAM role to Amazon CodeCatalyst space** page appears. You might need to sign in to access the page.

1. Select **Add an existing role you have created in IAM**.

   A drop-down list appears. The list displays the build and deploy roles, and any other IAM roles with a trust policy that includes the `codecatalyst-runner.amazonaws.com` and `codecatalyst.amazonaws.com` service principals.

1. From the drop-down list, add:
   + `codecatalyst-eks-build-role`
   + `codecatalyst-eks-deploy-role`
**Note**  
If you see `The security token included in the request is invalid`, it might be because you do not have the right permissions. To fix this issue, sign out of AWS as sign back in with the AWS account that you used when you created your CodeCatalyst space.

1. Return to the CodeCatalyst console and refresh the page.

   The build and deploy roles should now appear under **IAM roles**.

   These roles are now available for use in CodeCatalyst workflows.

## Step 7: Update the ConfigMap
<a name="deploy-tut-eks-configmap"></a>

You must add the deploy role that you created in [Step 5: Create AWS roles](#deploy-tut-eks-roles) to the Kubernetes `ConfigMap` file to give the **Deploy to Kubernetes cluster** action (in your workflow) the ability to access and interact with your cluster. You can use `eksctl` or `kubectl` to perform this task.

**To configure the Kubernetes ConfigMap file using eksctl**
+ In the Dev Environment terminal, enter: 

  ```
  eksctl create iamidentitymapping --cluster codecatalyst-eks-cluster --arn arn:aws:iam::111122223333:role/codecatalyst-eks-deploy-role --group system:masters --username codecatalyst-eks-deploy-role --region us-west-2
  ```

  Where:
  + *codecatalyst-eks-cluster* is replaced with the cluster name of the Amazon EKS cluster.
  +  *arn:aws:iam::111122223333:role/codecatalyst-eks-deploy-role* is replaced with the ARN of the deploy role that you created in [Step 5: Create AWS roles](#deploy-tut-eks-roles).
  +  *codecatalyst-eks-deploy-role* (next to `--username`) is replaced with the name of the deploy role that you created in [Step 5: Create AWS roles](#deploy-tut-eks-roles).
**Note**  
If you decided not to create a deploy role, replace *codecatalyst-eks-deploy-role* with the name of the `CodeCatalystWorkflowDevelopmentRole-spaceName` role. For more information about this role, see [Step 5: Create AWS roles](#deploy-tut-eks-roles).
  +  *us-west-2* is replaced with your Region.

  For details on this command, see [Manage IAM users and roles](https://eksctl.io/usage/iam-identity-mappings/).

  A message similar to the following appears:

  ```
  2023-06-09 00:58:29 [ℹ]  checking arn arn:aws:iam::111122223333:role/codecatalyst-eks-deploy-role against entries in the auth ConfigMap
  2023-06-09 00:58:29 [ℹ]  adding identity "arn:aws:iam::111122223333:role/codecatalyst-eks-deploy-role" to auth ConfigMap
  ```

**To configure the Kubernetes ConfigMap file using kubectl**

1. In the Dev Environment terminal, enter:

   ```
   kubectl edit configmap -n kube-system aws-auth
   ```

   The ConfigMap file appears on the screen.

1. Add the text in red italics:

   ```
   # Please edit the object below. Lines beginning with a '#' will be ignored,
   # and an empty file will abort the edit. If an error occurs while saving this file will be
   # reopened with the relevant failures.
   #
   apiVersion: v1
   data:
     mapRoles: |
       - groups:
         - system:bootstrappers
         - system:nodes
         rolearn: arn:aws:iam::111122223333:role/eksctl-codecatalyst-eks-cluster-n-NodeInstanceRole-16BC456ME6YR5
         username: system:node:{{EC2PrivateDNSName}}
       - groups:
         - system:masters
         rolearn: arn:aws:iam::111122223333:role/codecatalyst-eks-deploy-role
         username: codecatalyst-eks-deploy-role
     mapUsers: |
       []
   kind: ConfigMap
   metadata:
     creationTimestamp: "2023-06-08T19:04:39Z"
     managedFields:
     ...
   ```

   Where:
   +  *arn:aws:iam::111122223333:role/codecatalyst-eks-deploy-role* is replaced with the ARN of the deploy role that you created in [Step 5: Create AWS roles](#deploy-tut-eks-roles). 
   +  *codecatalyst-eks-deploy-role* (next to `username:`)is replaced with the name of the deploy role that you created in [Step 5: Create AWS roles](#deploy-tut-eks-roles).
**Note**  
If you decided not to create a deploy role, replace *codecatalyst-eks-deploy-role* with the name of the `CodeCatalystWorkflowDevelopmentRole-spaceName` role. For more information about this role, see [Step 5: Create AWS roles](#deploy-tut-eks-roles).

   For details, see [Enabling IAM principal access to your cluster](https://docs.aws.amazon.com/eks/latest/userguide/add-user-role.html) in the **Amazon EKS User Guide**.

You have now given the deploy role, and by extension the **Deploy to Amazon EKS** action, `system:masters` permissions to your Kubernetes cluster.

## Step 8: Create and run a workflow
<a name="deploy-tut-eks-workflow"></a>

In this step, you create a workflow that takes your source files, builds them into a Docker image, and then deploys the image into tree pods in your Amazon EKS cluster.

The workflow consists of the following building blocks that run sequentially:
+ A trigger – This trigger starts the workflow run automatically when you push a change to your source repository. For more information about triggers, see [Starting a workflow run automatically using triggers](workflows-add-trigger.md).
+ A build action (`BuildBackend`) – On trigger, the action builds the Docker image using the Dockerfile and pushes the image to Amazon ECR. The build action also updates the `$REPOSITORY_URI` and `$IMAGE_TAG` variables in the `deployment.yaml` file with the correct values, and then creates an output artifact of this file and any others in the `Kubernetes` folder. In this tutorial, the only file in the `Kubernetes` folder is `deployment.yaml` but you could include more files. The artifact is used as the input for the deploy action, which is next.

  For more information about the build action, see [Building with workflows](build-workflow-actions.md).
+ A deploy action (`DeployToEKS`) – On completion of the build action, the deploy action looks for the output artifact generated by the build action (`Manifests`), and finds the `deployment.yaml` file inside of it. The action then follows the instructions in the `deployment.yaml` file to run three pods—each containing a single 'Hello, World\$1' Docker container—inside your Amazon EKS cluster. 

**To create a workflow**

1. Go to the CodeCatalyst console.

1. Navigate to your project (`codecatalyst-eks-project`).

1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

1. Choose **Create workflow**.

1. For **Source repository**, choose `codecatalyst-eks-source-repository`.

1. For **Branch**, choose `main`.

1. Choose **Create**.

1. Delete the YAML sample code.

1. Add the following YAML code to create a new workflow definition file:
**Note**  
For more information about the workflow definition file, see [Workflow YAML definition](workflow-reference.md).
**Note**  
In the YAML code that follows, you can omit the `Connections:` sections if you want. If you omit these sections, you must ensure that the role specified in the **Default IAM role** field in your environment includes the permissions and trust policies of both roles described in [Step 6: Add AWS roles to CodeCatalyst](#deploy-tut-eks-import-roles). For more information about setting up an environment with a default IAM role, see [Creating an environment](deploy-environments-creating-environment.md).

   ```
   Name: codecatalyst-eks-workflow
   SchemaVersion: 1.0
   
   Triggers:
     - Type: PUSH
       Branches:
         - main
   Actions:
     BuildBackend:
       Identifier: aws/build@v1
       Environment:
         Name: codecatalyst-eks-environment
         Connections:
           - Name: codecatalyst-account-connection
             Role: codecatalyst-eks-build-role
       Inputs:
         Sources:
           - WorkflowSource
         Variables:
           - Name: REPOSITORY_URI
             Value: 111122223333.dkr.ecr.us-west-2.amazonaws.com/codecatalyst-eks-image-repo
           - Name: IMAGE_TAG
             Value: ${WorkflowSource.CommitId}
       Configuration:
         Steps:
           #pre_build:
           - Run: echo Logging in to Amazon ECR...
           - Run: aws --version
           - Run: aws ecr get-login-password --region us-west-2 | docker login --username AWS --password-stdin 111122223333.dkr.ecr.us-west-2.amazonaws.com
           #build:
           - Run: echo Build started on `date`
           - Run: echo Building the Docker image...
           - Run: docker build -t $REPOSITORY_URI:latest .
           - Run: docker tag $REPOSITORY_URI:latest $REPOSITORY_URI:$IMAGE_TAG
           #post_build:
           - Run: echo Build completed on `date`
           - Run: echo Pushing the Docker images...
           - Run: docker push $REPOSITORY_URI:latest
           - Run: docker push $REPOSITORY_URI:$IMAGE_TAG
           # Replace the variables in deployment.yaml
           - Run: find Kubernetes/ -type f | xargs sed -i "s|\$REPOSITORY_URI|$REPOSITORY_URI|g"
           - Run: find Kubernetes/ -type f | xargs sed -i "s|\$IMAGE_TAG|$IMAGE_TAG|g"
           - Run: cat Kubernetes/*
           # The output artifact will be a zip file that contains Kubernetes manifest files.
       Outputs:
         Artifacts:
           - Name: Manifests
             Files: 
               - "Kubernetes/*"
     DeployToEKS:
       DependsOn: 
         - BuildBackend
       Identifier: aws/kubernetes-deploy@v1
       Environment:
         Name: codecatalyst-eks-environment
         Connections:
           - Name: codecatalyst-account-connection
             Role: codecatalyst-eks-deploy-role
       Inputs:
         Artifacts:
           - Manifests
       Configuration:
         Namespace: default
         Region: us-west-2
         Cluster: codecatalyst-eks-cluster
         Manifests: Kubernetes/
   ```

   In the preceding code, replace:
   + Both instances of *codecatalyst-eks-environment* with the name of the environment you created in [Prerequisites](#deploy-tut-eks-prereqs).
   + Both instances of *codecatalyst-account-connection* with the display name of your account connection. The display name might be a number. For more information, see [Step 6: Add AWS roles to CodeCatalyst](#deploy-tut-eks-import-roles).
   + *codecatalyst-eks-build-role* with the name of the build role you created in [Step 5: Create AWS roles](#deploy-tut-eks-roles).
   + *111122223333.dkr.ecr.us-west-2.amazonaws.com/codecatalyst-eks-image-repo* (in the `Value:` property) with the URI of the Amazon ECR repository you created in [Step 3: Create an Amazon ECR image repository](#deploy-tut-eks-ecr).
   + *111122223333.dkr.ecr.us-west-2.amazonaws.com* (in the `Run: aws ecr` command) with the URI of the Amazon ECR repository without the image suffix (`/codecatalyst-eks-image-repo`).
   + *codecatalyst-eks-deploy-role* with the name of the deploy role you created in [Step 5: Create AWS roles](#deploy-tut-eks-roles).
   + Both instances of *us-west-2* with your AWS Region code. For a list of Region codes, see [Regional endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html) in the *AWS General Reference*.
**Note**  
If you decided not to create build and deploy roles, replace *codecatalyst-eks-build-role* and *codecatalyst-eks-deploy-role* with the name of the `CodeCatalystWorkflowDevelopmentRole-spaceName` role. For more information about this role, see [Step 5: Create AWS roles](#deploy-tut-eks-roles).

1. (Optional) Choose **Validate** to make sure that the YAML code is valid before committing.

1. Choose **Commit**.

1. In the **Commit workflow** dialog box, enter the following:

   1. For **Commit message**, remove the text and enter:

      ```
      Add first workflow
      ```

   1. For **Repository**, choose `codecatalyst-eks-source-repository`.

   1. For **Branch name**, choose main.

   1. Choose **Commit**.

   You have now created a workflow. A workflow run starts automatically because of the trigger defined at the top of the workflow. Specifically, when you committed (and pushed) the `workflow.yaml` file to your source repository, the trigger started the workflow run.

**To view the workflow run progress**

1. In the navigation pane of the CodeCatalyst console, choose **CI/CD**, and then choose **Workflows**.

1. Choose the workflow you just created, `codecatalyst-eks-workflow`.

1. Choose **BuildBackend** to see the build progress.

1. Choose **DeployToEKS** to see the deployment progress.

   For more information about viewing run details, see [Viewing workflow run status and details](workflows-view-run.md).

**To verify the deployment**

1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

1. On the left, near the bottom, choose **Load Balancers**.

1. Select the load balancer that was created as part of your Kubernetes deployment. If you're not sure which load balancer to choose, look for the following tags under the **Tags** tab:
   + `kubernetes.io/service-name`
   + `kubernetes.io/cluster/ekstutorialcluster`

1. With the correct load balancer selected, choose the **Description** tab.

1. Copy and paste the **DNS name** value into your browser's address bar.

   The 'Hello, World\$1' webpage appears in your browser, indicating that you successfully deployed your application.

## Step 9: Make a change to your source files
<a name="deploy-tut-eks-change"></a>

In this section, you make a change to the `index.html` file in your source repository. This change causes the workflow to build a new Docker image, tag it with a commit ID, push it to Amazon ECR, and deploy it to Amazon ECS. 

**To change the index.html**

1. Go to your Dev Environment.

1. At the terminal prompt, change to your source repository:

   ```
   cd /projects/codecatalyst-eks-source-repository
   ```

1.  Pull the latest workflow changes:

   ```
   git pull
   ```

1. Open `codecatalyst-eks-source-repository/public-html/index.html`.

1. On line 14, change the `Hello, World!` text to `Tutorial complete!`.

1. Add, commit, and push:

   ```
   git add .
   git commit -m "update index.html title"
   git push
   ```

   A workflow run starts automatically.

1. (Optional) Enter:

   ```
   git show HEAD
   ```

   Note the commit ID for the `index.html` change. This commit ID will be tagged to the Docker image that will be deployed by the workflow run that you just started.

1. Watch the deployment progress:

   1. In the CodeCatalyst console, in the navigation pane, choose **CI/CD**, and then choose **Workflows**.

   1. Choose `codecatalyst-eks-workflow` to view the latest run.

   1. Choose **BuildBackend**, and **DeployToEKS** to see the workflow run progress.

1. Verify that your application was updated, as follows:

   1. Open the Amazon EC2 console at [https://console.aws.amazon.com/ec2/](https://console.aws.amazon.com/ec2/).

   1. On the left, near the bottom, choose **Load Balancers**.

   1. Select the load balancer that was created as part of your Kubernetes deployment.

   1. Copy and paste the **DNS name** value into your browser's address bar.

      The 'Tutorial Complete\$1' webpage appears in your browser, indicating that you successfully deployed a new revision of your application.

1. (Optional) In AWS, switch to the Amazon ECR console and verify that the new Docker image was tagged with the commit ID from step 7 of this procedure.

## Clean up
<a name="deploy-tut-eks-cleanup"></a>

You should clean up your environment so that you're not charged unnecessarily for the storage and compute resources used by this tutorial.

**To clean up**

1. Delete your cluster:

   1. In the Dev Environment terminal, enter:

     ```
     eksctl delete cluster --region=us-west-2 --name=codecatalyst-eks-cluster
     ```

     Where:
     + *us-west-2* is replaced with your Region.
     + *codecatalyst-eks-cluster* is replaced with the name of the cluster you created.

     After 5-10 minutes, the cluster and associated resources are deleted, including but not limited to CloudFormation stacks, nodes groups (in Amazon EC2), and load balancers.
**Important**  
If the `eksctl delete cluster` command doesn't work, you may need to refresh your AWS credentials or your `kubectl` credentials. If you're not sure which credentials to refresh, refresh the AWS credentials first. To refresh your AWS credentials, see [How do I fix "Unable to locate credentials" and "ExpiredToken" errors?](troubleshooting-workflows.md#troubleshooting-workflows-auth-errors-eks). To refresh your `kubectl` credentials, see [How do I fix "Unable to connect to the server" errors?](troubleshooting-workflows.md#troubleshooting-workflows-unable-connect-eks).

1. In the AWS console, clean up as follows:

   1. In Amazon ECR, delete `codecatalyst-eks-image-repo`.

   1. In IAM Identity Center, delete:

      1. `codecatalyst-eks-user`

      1. `codecatalyst-eks-permission-set`

   1. In IAM, delete:
      + `codecatalyst-eks-build-role`
      + `codecatalyst-eks-deploy-role`
      + `codecatalyst-eks-build-policy`
      + `codecatalyst-eks-deploy-policy`

1. In the CodeCatalyst console, clean up as follows:

   1. Delete `codecatalyst-eks-workflow`.

   1. Delete `codecatalyst-eks-environment`.

   1. Delete `codecatalyst-eks-source-repository`.

   1. Delete your Dev Environment.

   1. Delete `codecatalyst-eks-project`.

In this tutorial, you learned how to deploy an application to an Amazon EKS service using a CodeCatalyst workflow and a **Deploy to Kubernetes cluster** action.

# Adding the 'Deploy to Kubernetes cluster' action
<a name="deploy-action-eks-adding"></a>

Use the following instructions to add the **Deploy to Kubernetes cluster** action to your workflow. 

**Before you begin**

Before you add the **Deploy to Kubernetes cluster** action to your workflow, you must have the following prepared:

**Tip**  
To set up these prerequisites quickly, follow the instructions in [Tutorial: Deploy an application to Amazon EKS](deploy-tut-eks.md).
+ A Kubernetes cluster in Amazon EKS. For information about clusters, see [Amazon EKS clusters](https://docs.aws.amazon.com/eks/latest/userguide/clusters.html) in the **Amazon EKS User Guide**.
+ At least one Dockerfile that describes how to assemble your application into a Docker image. For more information about Dockerfiles, see the [Dockerfile reference](https://docs.docker.com/engine/reference/builder/).
+ At least one Kubernetes manifest file, which is called a *configuration file* or *configuration* in the Kubernetes documentation. For more information, see [Managing resources](https://kubernetes.io/docs/concepts/cluster-administration/manage-deployment/) in the Kubernetes documentation.
+ An IAM role that gives the **Deploy to Kubernetes cluster** action the ability to access and interact with your Amazon EKS cluster. For more information, see the [Role](deploy-action-ref-eks.md#deploy.action.eks.environment.connections.role) topic in the ['Deploy to Kubernetes cluster' action YAML](deploy-action-ref-eks.md).

  After creating this role, you must add it to:
  + Your Kubernetes ConfigMap file. To learn how to add a role to a ConfigMap file, see [Enabling IAM principal access to your cluster](https://docs.aws.amazon.com/eks/latest/userguide/add-user-role.html) in the **Amazon EKS User Guide**.
  + CodeCatalyst. To learn how to add an IAM role to CodeCatalyst, see [Adding IAM roles to account connections](ipa-connect-account-addroles.md).
+ A CodeCatalyst space, project, and environment. The space and environment must both be connected to the AWS account into which you will be deploying your application. For more information, see [Creating a space](spaces-create.md), [Creating an empty project in Amazon CodeCatalyst](projects-create.md#projects-create-empty), and [Deploying into AWS accounts and VPCs](deploy-environments.md).
+ A source repository supported by CodeCatalyst. The repository stores your application source files, Dockerfiles, and Kubernetes manifests. For more information, see [Store and collaborate on code with source repositories in CodeCatalystStore and collaborate on code with source repositories](source.md).

------
#### [ Visual ]

**To add the 'Deploy to Kubernetes cluster' action using the visual editor**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

1. Choose the name of your workflow. You can filter by the source repository or branch name where the workflow is defined, or filter by workflow name or status.

1. Choose **Edit**.

1. Choose **Visual**.

1. At the top-left, choose **\$1 Actions** to open the action catalog.

1. From the drop-down list, choose **Amazon CodeCatalyst**.

1. Search for the **Deploy to Kubernetes cluster** action, and do one of the following:
   + Choose the plus sign (**\$1**) to add the action to the workflow diagram and open its configuration pane.

     Or
   + Choose **Deploy to Kubernetes cluster**. The action details dialog box appears. On this dialog box:
     + (Optional) Choose **Download** to [view the action's source code](workflows-view-source.md#workflows-view-source.title).
     + Choose **Add to workflow** to add the action to the workflow diagram and open its configuration pane.

1. In the **Inputs** and **Configuration** tabs, complete the fields according to your needs. For a description of each field, see the ['Deploy to Kubernetes cluster' action YAML](deploy-action-ref-eks.md). This reference provides detailed information about each field (and corresponding YAML property value) as it appears in both the YAML and visual editors.

1. (Optional) Choose **Validate** to validate the workflow's YAML code before committing.

1. Choose **Commit**, enter a commit message, and choose **Commit** again.

------
#### [ YAML ]

**To add the 'Deploy to Kubernetes cluster' action using the YAML editor**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

1. Choose the name of your workflow. You can filter by the source repository or branch name where the workflow is defined, or filter by workflow name or status.

1. Choose **Edit**.

1. Choose **YAML**.

1. At the top-left, choose **\$1 Actions** to open the action catalog.

1. From the drop-down list, choose **Amazon CodeCatalyst**.

1. Search for the **Deploy to Kubernetes cluster** action, and do one of the following:
   + Choose the plus sign (**\$1**) to add the action to the workflow diagram and open its configuration pane.

     Or
   + Choose **Deploy to Kubernetes cluster**. The action details dialog box appears. On this dialog box:
     + (Optional) Choose **Download** to [view the action's source code](workflows-view-source.md#workflows-view-source.title).
     + Choose **Add to workflow** to add the action to the workflow diagram and open its configuration pane.

1. Modify the properties in the YAML code according to your needs. An explanation of each available property is provided in the ['Deploy to Kubernetes cluster' action YAML](deploy-action-ref-eks.md).

1. (Optional) Choose **Validate** to validate the workflow's YAML code before committing.

1. Choose **Commit**, enter a commit message, and choose **Commit** again.

------

# 'Deploy to Kubernetes cluster' variables
<a name="deploy-action-eks-variables"></a>

The **Deploy to Kubernetes cluster** action produces and sets the following variables at run time. These are known as *predefined variables*.

For information about referencing these variables in a workflow, see [Using predefined variables](workflows-using-predefined-variables.md).


| Key | Value | 
| --- | --- | 
|  cluster  |  The Amazon.com Resource Name (ARN) of the of the Amazon EKS cluster that was deployed to during the workflow run. Example: `arn:aws:eks:us-west-2:111122223333:cluster/codecatalyst-eks-cluster`  | 
|  deployment-platform  |  The name of the deployment platform. Hardcoded to `AWS:EKS`.  | 
|  metadata  |  Reserved. JSON-formatted metadata related to the cluster deployed during the workflow run.  | 
|  namespace  |  The Kubernetes namespace into which the cluster was deployed. Example: `default`  | 
|  resources  |  Reserved. JSON-formatted metadata related to the resources deployed during the workflow run.  | 
|  server  |  The name of the API server endpoint that you can use to communicate with your cluster using management tools such as `kubectl`. For more information about the API service endpoint, see [Amazon EKS cluster endpoint access control](https://docs.aws.amazon.com/eks/latest/userguide/cluster-endpoint.html) in the **Amazon EKS User Guide**. Example: `https://random-string.gr7.us-west-2.eks.amazonaws.com`  | 

# 'Deploy to Kubernetes cluster' action YAML
<a name="deploy-action-ref-eks"></a>

The following is the YAML definition of the **Deploy to Kubernetes cluster** action. To learn how to use this action, see [Deploying to Amazon EKS with a workflow](deploy-action-eks.md).

This action definition exists as a section within a broader workflow definition file. For more information about this file, see [Workflow YAML definition](workflow-reference.md).

**Note**  
Most of the YAML properties that follow have corresponding UI elements in the visual editor. To look up a UI element, use **Ctrl\$1F**. The element will be listed with its associated YAML property.

```
# The workflow definition starts here.
# See Top-level properties for details.
        
Name: MyWorkflow
SchemaVersion: 1.0 
Actions:

# The action definition starts here.   
  DeployToKubernetesCluster\$1nn: 
    Identifier: aws/kubernetes-deploy@v1
    DependsOn:
      - build-action
    Compute:  
        - Type: EC2 | Lambda
        - Fleet: fleet-name
    Timeout: timeout-minutes
    Environment:
      Name: environment-name
      Connections:
        - Name: account-connection-name
          Role: DeployToEKS
    Inputs:
      # Specify a source or an artifact, but not both.
      Sources:
        - source-name-1
      Artifacts:
        - manifest-artifact
    Configuration:
      Namespace: namespace
      Region: us-east-1 
      Cluster: eks-cluster
      Manifests: manifest-path
```

## DeployToKubernetesCluster
<a name="deploy.action.eks.name"></a>

(Required)

Specify the name of the action. All action names must be unique within the workflow. Action names are limited to alphanumeric characters (a-z, A-Z, 0-9), hyphens (-), and underscores (\$1). Spaces are not allowed. You cannot use quotation marks to enable special characters and spaces in action names.

Default: `DeployToKubernetesCluster_nn`.

Corresponding UI: Configuration tab/**Action display name**

## Identifier
<a name="deploy.action.eks.identifier"></a>

(*DeployToKubernetesCluster*/**Identifier**)

(Required)

Identifies the action. Do not change this property unless you want to change the version. For more information, see [Specifying the action version to use](workflows-action-versions.md).

Default: `aws/kubernetes-deploy@v1`.

Corresponding UI: Workflow diagram/DeployToKubernetesCluster\$1nn/**aws/kubernetes-deploy@v1** label

## DependsOn
<a name="deploy.action.eks.dependson"></a>

(*DeployToKubernetesCluster*/**DependsOn**)

(Optional)

Specify an action, action group, or gate that must run successfully in order for this action to run.

For more information about the 'depends on' functionality, see [Sequencing actions](workflows-depends-on.md).

Corresponding UI: Inputs tab/**Depends on - optional**

## Compute
<a name="deploy.action.eks.computename"></a>

(*DeployToKubernetesCluster*/**Compute**)

(Optional)

The computing engine used to run your workflow actions. You can specify compute either at the workflow level or at the action level, but not both. When specified at the workflow level, the compute configuration applies to all actions defined in the workflow. At the workflow level, you can also run multiple actions on the same instance. For more information, see [Sharing compute across actions](compute-sharing.md).

Corresponding UI: *none*

## Type
<a name="deploy.action.eks.computetype"></a>

(*DeployToKubernetesCluster*/Compute/**Type**)

(Required if [Compute](#deploy.action.eks.computename) is included)

The type of compute engine. You can use one of the following values:
+ **EC2** (visual editor) or `EC2` (YAML editor)

  Optimized for flexibility during action runs.
+ **Lambda** (visual editor) or `Lambda` (YAML editor)

  Optimized action start-up speeds.

For more information about compute types, see [Compute types](workflows-working-compute.md#compute.types).

Corresponding UI: Configuration tab/Advanced - optional/**Compute type**

## Fleet
<a name="deploy.action.eks.computefleet"></a>

(*DeployToKubernetesCluster*/Compute/**Fleet**)

(Optional)

Specify the machine or fleet that will run your workflow or workflow actions. With on-demand fleets, when an action starts, the workflow provisions the resources it needs, and the machines are destroyed when the action finishes. Examples of on-demand fleets: `Linux.x86-64.Large`, `Linux.x86-64.XLarge`. For more information about on-demand fleets, see [On-demand fleet properties](workflows-working-compute.md#compute.on-demand).

With provisioned fleets, you configure a set of dedicated machines to run your workflow actions. These machines remain idle, ready to process actions immediately. For more information about provisioned fleets, see [Provisioned fleet properties](workflows-working-compute.md#compute.provisioned-fleets).

If `Fleet` is omitted, the default is `Linux.x86-64.Large`.

Corresponding UI: Configuration tab/Advanced - optional/**Compute fleet**

## Timeout
<a name="deploy.action.eks.timeout"></a>

(*DeployToKubernetesCluster*/**Timeout**)

(Optional)

Specify the amount of time in minutes (YAML editor), or hours and minutes (visual editor), that the action can run before CodeCatalyst ends the action. The minimum is 5 minutes and the maximum is described in [Quotas for workflows in CodeCatalyst](workflows-quotas.md). The default timeout is the same as the maximum timeout.

Corresponding UI: Configuration tab/**Timeout - optional **

## Environment
<a name="deploy.action.eks.environment"></a>

(*DeployToKubernetesCluster*/**Environment**)

(Required)

Specify the CodeCatalyst environment to use with the action. The action connects to the AWS account and optional Amazon VPC specified in the chosen environment. The action uses the default IAM role specified in the environment to connect to the AWS account, and uses the IAM role specified in the [Amazon VPC connection](https://docs.aws.amazon.com/codecatalyst/latest/adminguide/managing-vpcs.add.html) to connect to the Amazon VPC.

**Note**  
If the default IAM role does not have the permissions required by the action, you can configure the action to use a different role. For more information, see [Changing the IAM role of an action](deploy-environments-switch-role.md).

For more information about environments, see [Deploying into AWS accounts and VPCs](deploy-environments.md) and [Creating an environment](deploy-environments-creating-environment.md).

Corresponding UI: Configuration tab/**Environment**

## Name
<a name="deploy.action.eks.environment.name"></a>

(*DeployToKubernetesCluster*/Environment/**Name**)

(Required if [Environment](#deploy.action.eks.environment) is included)

Specify the name of an existing environment that you want to associate with the action.

Corresponding UI: Configuration tab/**Environment**

## Connections
<a name="deploy.action.eks.environment.connections"></a>

(*DeployToKubernetesCluster*/Environment/**Connections**)

(Optional in newer versions of the action; required in older versions)

Specify the account connection to associate with the action. You can specify a maximum of one account connection under `Environment`.

If you do not specify an account connection:
+ The action uses the AWS account connection and default IAM role specified in the environment in the CodeCatalyst console. For information about adding an account connection and default IAM role to environment, see [Creating an environment](deploy-environments-creating-environment.md).
+ The default IAM role must include the policies and permissions required by the action. To determine what those policies and permissions are, see the description of the **Role** property in the action's YAML definition documentation.

For more information about account connections, see [Allowing access to AWS resources with connected AWS accounts](ipa-connect-account.md). For information about adding an account connection to an environment, see [Creating an environment](deploy-environments-creating-environment.md).

Corresponding UI: One of the following depending on the action version:
+ (Newer versions) Configuration tab/Environment/What's in *my-environment*?/three dot menu/**Switch role**
+ (Older versions) Configuration tab/'Environment/account/role'/**AWS account connection**

## Name
<a name="deploy.action.eks.environment.connections.name"></a>

(*DeployToKubernetesCluster*/Environment/Connections/**Name**)

(Optional)

Specify the name of the account connection.

Corresponding UI: One of the following depending on the action version:
+ (Newer versions) Configuration tab/Environment/What's in *my-environment*?/three dot menu/**Switch role**
+ (Older versions) Configuration tab/'Environment/account/role'/**AWS account connection**

## Role
<a name="deploy.action.eks.environment.connections.role"></a>

(*DeployToKubernetesCluster*/Environment/Connections/**Role**)

(Required if [Connections](#deploy.action.eks.environment.connections) is included)

Specify the name of the IAM role that the **Deploy to Kubernetes cluster ** action uses to access AWS. Make sure that you have [added the role to your CodeCatalyst space](ipa-connect-account-addroles.md), and that the role includes the following policies.

If you do not specify an IAM role, then the action uses the default IAM role listed in the [environment](deploy-environments.md) in the CodeCatalyst console. If you use the default role in the environment, make sure it has the following policies.
+ The following permissions policy:
**Warning**  
Limit the permissions to those shown in the following policy. Using a role with broader permissions might pose a security risk.

------
#### [ JSON ]

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Statement": [
          {
              "Effect": "Allow",
              "Action": [
                  "eks:DescribeCluster",
                  "eks:ListClusters"
              ],
              "Resource": "*"
          }
      ]
  }
  ```

------
**Note**  
The first time the role is used, use the following wildcard in the resource policy statement and then scope down the policy with the resource name after it is available.  

  ```
  "Resource": "*"
  ```
+ The following custom trust policy:

Make sure that this role is added to:
+ Your account connection. To learn more about adding an IAM role to an account connection, see [Adding IAM roles to account connections](ipa-connect-account-addroles.md).
+ Your Kubernetes ConfigMap. To learn more about adding an IAM role to a ConfigMap, see [Manage IAM users and roles](https://eksctl.io/usage/iam-identity-mappings/) in the `eksctl` documentation.

**Tip**  
See also [Tutorial: Deploy an application to Amazon EKS](deploy-tut-eks.md) for instructions on adding am IAM role to an account connection and ConfigMap.

**Note**  
You can use the `CodeCatalystWorkflowDevelopmentRole-spaceName` role with this action, if you'd like. For more information about this role, see [Creating the **CodeCatalystWorkflowDevelopmentRole-*spaceName*** role for your account and space](ipa-iam-roles.md#ipa-iam-roles-service-create). Understand that the `CodeCatalystWorkflowDevelopmentRole-spaceName` role has full access permissions which may pose a security risk. We recommend that you only use this role in tutorials and scenarios where security is less of a concern. 

Corresponding UI: One of the following depending on the action version:
+ (Newer versions) Configuration tab/Environment/What's in *my-environment*?/three dot menu/**Switch role**
+ (Older versions) Configuration tab/'Environment/account/role'/**Role**

## Inputs
<a name="deploy.action.eks.inputs"></a>

(*DeployToKubernetesCluster*/**Inputs**)

(Required if [Connections](#deploy.action.eks.environment.connections) is included)

The `Inputs` section defines the data that the `DeployToKubernetesCluster` needs during a workflow run.

**Note**  
Only one input (either a source or an artifact) is allowed per **Deploy to Amazon EKS** action.

Corresponding UI: **Inputs** tab

## Sources
<a name="deploy.action.eks.inputs.sources"></a>

(*DeployToKubernetesCluster*/Inputs/**Sources**)

(Required if your manifest file is stored in a source repository)

If your Kubernetes manifest file or files are stored in a source repository, specify the label of that source repository. Currently, the only supported label is `WorkflowSource`.

If your manifest files are not contained within a source repository, they must reside in an artifact generated by another action.

For more information about sources, see [Connecting source repositories to workflows](workflows-sources.md).

Corresponding UI: Inputs tab/**Sources - optional**

## Artifacts - input
<a name="deploy.action.eks.inputs.artifacts"></a>

(*DeployToKubernetesCluster*/Inputs/**Artifacts**)

(Required if your manifest file is stored in an [output artifact](workflows-working-artifacts-output.md) from a previous action)

If the Kubernetes manifest file or files are contained in an artifact generated by a previous action, specify that artifact here. If your manifest files are not contained within an artifact, they must reside in your source repository.

For more information about artifacts, including examples, see [Sharing artifacts and files between actions](workflows-working-artifacts.md).

Corresponding UI: Configuration tab/**Artifacts - optional**

## Configuration
<a name="deploy.action.eks.configuration"></a>

(*DeployToKubernetesCluster*/**Configuration**)

(Required)

A section where you can define the configuration properties of the action.

Corresponding UI: **Configuration** tab

## Namespace
<a name="deploy.action.eks.namespace"></a>

(*DeployToKubernetesCluster*/Configuration/**Namespace**)

(Optional)

Specify the Kubernetes namespace into which your Kubernetes application will be deployed. Use `default` if you are not using namespaces with your cluster. For more information on namespaces, see [Subdividing your cluster using Kubernetes namespaces](https://kubernetes.io/docs/tasks/administer-cluster/namespaces/#subdividing-your-cluster-using-kubernetes-namespaces) in the Kubernetes documentation.

If you omit the namespace, a value of `default` is used.

Corresponding UI: Configuration tab/**Namespace**

## Region
<a name="deploy.action.eks.region"></a>

(*DeployToKubernetesCluster*/Configuration/**Region**)

(Required)

Specify the AWS Region where your Amazon EKS cluster and service reside. For a list of Region codes, see [Regional endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html#region-names-codes) in the *AWS General Reference*.

Corresponding UI: Configuration tab/**Region**

## Cluster
<a name="deploy.action.eks.cluster"></a>

(*DeployToKubernetesCluster*/Configuration/**Cluster**)

(Required)

Specify the name of an existing Amazon EKS cluster. The **Deploy to Kubernetes cluster** action will deploy your containerized application into this cluster. For more information about Amazon EKS clusters, see [Clusters](https://docs.aws.amazon.com/eks/latest/userguide/clusters.html) in the **Amazon EKS User Guide**.

Corresponding UI: Configuration tab/**Cluster**

## Manifests
<a name="deploy.action.eks.manifest"></a>

(*DeployToKubernetesCluster*/Configuration/**Manifests**)

(Required)

Specify the path to your YAML-formatted Kubernetes manifest file(s), which are called *configuration files*, *config files*, or simply, *configurations* in the Kubernetes documentation.

If you're using multiple manifest files, place them in a single folder and reference that folder. Manifest files are processed alphanumerically by Kubernetes, so make sure to prefix file names with increasing numbers or letters to control the processing order. For example:

`00-namespace.yaml`

`01-deployment.yaml`

If your manifest files reside in your source repository, the path is relative to the source repository root folder. If the files reside in an artifact from a previous workflow action, the path is relative to the artifact root folder. 

Examples:

`Manifests/`

`deployment.yaml`

`my-deployment.yml`

Do not use wildcards (`*`).

**Note**  
[Helm charts](https://helm.sh/docs/topics/charts/) and [kustomization files](https://kubernetes.io/docs/tasks/manage-kubernetes-objects/kustomization/) are not supported.

For more information about manifest files, see [Organizing resource configurations](https://kubernetes.io/docs/concepts/cluster-administration/manage-deployment/#organizing-resource-configurations) in the Kubernetes documentation.

Corresponding UI: Configuration tab/**Manifests**

# Deploying an CloudFormation stack
<a name="deploy-action-cfn"></a>

This section describes how to deploy a AWS CloudFormation stack using a CodeCatalyst workflow. To accomplish this, you must add the **Deploy CloudFormation stack** action to your workflow. The action deploys a CloudFormation stack of resources into AWS based on a template that you provide. The template can be a:
+ CloudFormation template – For more information, see [Working with CloudFormation templates](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-guide.html).
+ AWS SAM template – For more information, see [AWS Serverless Application Model (AWS SAM) specification](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-specification.html).
**Note**  
To use a AWS SAM template, you must first package your AWS SAM application using the `[sam package](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-package.html)` operation. For a tutorial that shows you how to do this packaging automatically as part of a Amazon CodeCatalyst workflow, see [Tutorial: Deploy a serverless application](deploy-tut-lambda.md).

If the stack already exists, the action runs the CloudFormation `[CreateChangeSet](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_CreateChangeSet.html)` operation, and then the `[ExecuteChangeSet](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_ExecuteChangeSet.html)` operation. The action then waits for the changes to be deployed and marks itself as either succeeded for failed, depending on the results.

Use the **Deploy CloudFormation stack** action if you already have an CloudFormation or AWS SAM template that contains resources you'd like to deploy, or you plan on generating one automatically as part of a workflow [build action](build-add-action.md) using tools like AWS SAM and [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/home.html).

There are no restrictions on the template you can use—whatever you can author in CloudFormation or AWS SAM you can use with the **Deploy CloudFormation stack** action.

**Tip**  
For a tutorial that shows you how to deploy a serverless application using the **Deploy CloudFormation stack** action, see [Tutorial: Deploy a serverless application](deploy-tut-lambda.md).

**Topics**
+ [Runtime image used by the 'Deploy CloudFormation stack' action](#deploy-action-cfn-runtime)
+ [Tutorial: Deploy a serverless application](deploy-tut-lambda.md)
+ [Adding the 'Deploy CloudFormation stack' action](deploy-action-cfn-adding.md)
+ [Configuring rollbacks](deploy-consumption-enable-alarms.md)
+ ['Deploy CloudFormation stack' variables](deploy-action-cfn-variables.md)
+ ['Deploy CloudFormation stack' action YAML](deploy-action-ref-cfn.md)

## Runtime image used by the 'Deploy CloudFormation stack' action
<a name="deploy-action-cfn-runtime"></a>

The **Deploy CloudFormation stack** action runs on a [November 2022 image](build-images.md#build.previous-image). For more information, see [Active images](build-images.md#build-curated-images).

# Tutorial: Deploy a serverless application
<a name="deploy-tut-lambda"></a>

In this tutorial, you learn how to build, test, and deploy a serverless application as a CloudFormation stack using a workflow.

The application in this tutorial is a simple web application that outputs a 'Hello World' message. It consists of an AWS Lambda function and an Amazon API Gateway, and you build it using the [AWS Serverless Application Model (AWS SAM)](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html), which is an extension of [CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html).

**Topics**
+ [Prerequisites](#deploy-tut-lambda-cfn-prereqs)
+ [Step 1: Create a source repository](#deploy-tut-lambda-cfn-source)
+ [Step 2: Create AWS roles](#deploy-tut-lambda-cfn-roles)
+ [Step 3: Add AWS roles to CodeCatalyst](#deploy-tut-lambda-cfn-roles-add)
+ [Step 4: Create an Amazon S3 bucket](#deploy-tut-lambda-cfn-s3)
+ [Step 5: Add source files](#deploy-tut-lambda-cfn-files)
+ [Step 6: Create and run a workflow](#deploy-tut-lambda-cfn-workflow)
+ [Step 7: Make a change](#deploy-tut-lambda-cfn-change)
+ [Clean up](#deploy-tut-lambda-cfn-clean-up)

## Prerequisites
<a name="deploy-tut-lambda-cfn-prereqs"></a>

Before you begin:
+ You need a CodeCatalyst **space** with a connected AWS account. For more information, see [Creating a space](spaces-create.md).
+ In your space, you need an empty project called:

  ```
  codecatalyst-cfn-project
  ```

  Use the **Start from scratch** option to create this project.

  For more information, see [Creating an empty project in Amazon CodeCatalyst](projects-create.md#projects-create-empty).
+ In your project, you need a CodeCatalyst **environment** called:

  ```
  codecatalyst-cfn-environment
  ```

  Configure this environment as follows:
  + Choose any type, such as **Non-production**.
  + Connect your AWS account to it.
  + For the **Default IAM role**, choose any role. You'll specify a different role later.

  For more information, see [Deploying into AWS accounts and VPCs](deploy-environments.md).

## Step 1: Create a source repository
<a name="deploy-tut-lambda-cfn-source"></a>

In this step, you create a source repository in CodeCatalyst. This repository is used to store the tutorial's source files, such as the Lambda function file. 

For more information about source repositories, see [Creating a source repository](source-repositories-create.md).

**To create a source repository**

1. In CodeCatalyst, in the navigation pane, choose **Code**, and then choose **Source repositories**. 

1. Choose **Add repository**, and then choose **Create repository**.

1. In **Repository name**, enter:

   ```
   codecatalyst-cfn-source-repository
   ```

1. Choose **Create**.

You have now created a repository called `codecatalyst-cfn-source-repository`.

## Step 2: Create AWS roles
<a name="deploy-tut-lambda-cfn-roles"></a>

In this step, you create the following AWS IAM roles:
+ **Deploy role** – Grants the CodeCatalyst **Deploy CloudFormation stack** action permission to access your AWS account and CloudFormation service where you’ll deploy your serverless application. The **Deploy CloudFormation stack** action is part of your workflow.
+ **Build role** – Grants the CodeCatalyst build action permission to access your AWS account and write to Amazon S3 where your serverless application package will be stored. The build action is part of your workflow.
+ **Stack role** – Grants CloudFormation permission to read and modify the resources specified in the AWS SAM template that you will provide later. Also grants permission to CloudWatch.

For more information about IAM roles, see [IAM roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) in the *AWS Identity and Access Management User Guide*.

**Note**  
To save time, you can create a single role, called the `CodeCatalystWorkflowDevelopmentRole-spaceName` role, instead of the three roles listed previously. For more information, see [Creating the **CodeCatalystWorkflowDevelopmentRole-*spaceName*** role for your account and space](ipa-iam-roles.md#ipa-iam-roles-service-create). Understand that the `CodeCatalystWorkflowDevelopmentRole-spaceName` role has very broad permissions that may pose a security risk. We recommend that you only use this role in tutorials and scenarios where security is less of a concern. This tutorial assumes you are creating the three roles listed previously.

**Note**  
A [Lambda execution role](https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html) is also required, but you don't need to create it now because the `sam-template.yml` file creates it for you when you run the workflow in step 5.



**To create a deploy role**

1. Create a policy for the role, as follows:

   1. Sign in to AWS.

   1. Open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

   1. In the navigation pane, choose **Policies**.

   1. Choose **Create policy**.

   1. Choose the **JSON** tab.

   1. Delete the existing code.

   1. Paste the following code:
**Note**  
The first time the role is used to run workflow actions, use the wildcard in the resource policy statement and then scope down the policy with the resource name after it is available.  

      ```
      "Resource": "*"
      ```

   1. Choose **Next: Tags**.

   1. Choose **Next: Review**.

   1. In **Name**, enter:

      ```
      codecatalyst-deploy-policy
      ```

   1. Choose **Create policy**.

      You have now created a permissions policy.

1. Create the deploy role, as follows:

   1. In the navigation pane, choose **Roles**, and then choose **Create role**.

   1. Choose **Custom trust policy**.

   1. Delete the existing custom trust policy.

   1. Add the following custom trust policy:

   1. Choose **Next**.

   1. In **Permissions policies**, search for `codecatalyst-deploy-policy` and select its check box.

   1. Choose **Next**.

   1. For **Role name**, enter:

      ```
      codecatalyst-deploy-role
      ```

   1. For **Role description**, enter:

      ```
      CodeCatalyst deploy role
      ```

   1. Choose **Create role**.

   You have now created a deploy role with a trust policy and permissions policy.

1. Obtain the deploy role ARN, as follows:

   1. In the navigation pane, choose **Roles**.

   1. In the search box, enter the name of the role you just created (`codecatalyst-deploy-role`).

   1. Choose the role from the list.

      The role's **Summary** page appears.

   1. At the top, copy the **ARN** value.

   You have now created the deploy role with the appropriate permissions, and obtained its ARN.

**To create a build role**

1. Create a policy for the role, as follows:

   1. Sign in to AWS.

   1. Open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

   1. In the navigation pane, choose **Policies**.

   1. Choose **Create policy**.

   1. Choose the **JSON** tab.

   1. Delete the existing code.

   1. Paste the following code:
**Note**  
The first time the role is used to run workflow actions, use the wildcard in the resource policy statement and then scope down the policy with the resource name after it is available.  

      ```
      "Resource": "*"
      ```

   1. Choose **Next: Tags**.

   1. Choose **Next: Review**.

   1. In **Name**, enter:

      ```
      codecatalyst-build-policy
      ```

   1. Choose **Create policy**.

      You have now created a permissions policy.

1. Create the build role, as follows:

   1. In the navigation pane, choose **Roles**, and then choose **Create role**.

   1. Choose **Custom trust policy**.

   1. Delete the existing custom trust policy.

   1. Add the following custom trust policy:

   1. Choose **Next**.

   1. In **Permissions policies**, search for `codecatalyst-build-policy` and select its check box.

   1. Choose **Next**.

   1. For **Role name**, enter:

      ```
      codecatalyst-build-role
      ```

   1. For **Role description**, enter:

      ```
      CodeCatalyst build role
      ```

   1. Choose **Create role**.

   You have now created a build role with a trust policy and permissions policy.

1. Obtain the build role ARN, as follows:

   1. In the navigation pane, choose **Roles**.

   1. In the search box, enter the name of the role you just created (`codecatalyst-build-role`).

   1. Choose the role from the list.

      The role's **Summary** page appears.

   1. At the top, copy the **ARN** value.

   You have now created the build role with the appropriate permissions, and obtained its ARN.<a name="deploy-tut-lambda-cfn-roles-stack"></a>

**To create a stack role**

1. Sign in to AWS using the account where you want to deploy your stack.

1. Open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. Create the stack role as follows:

   1. In the navigation pane, choose **Roles**.

   1. Choose **Create role**.

   1. Choose **AWS service**.

   1. In the **Use case** section, choose **CloudFormation** from the drop-down list.

   1. Select the **CloudFormation** radio button.

   1. At the bottom, choose **Next**.

   1. Using the search box, find the following permissions policies, and then select their respective check boxes.
**Note**  
If you search for a policy and it doesn't appear, make sure to choose **Clear filters** and try again.
      + **CloudWatchFullAccess**
      + **AWSCloudFormationFullAccess**
      + **IAMFullAccess**
      + **AWSLambda\$1FullAccess**
      + **AmazonAPIGatewayAdministrator**
      + **AmazonS3FullAccess**
      + **AmazonEC2ContainerRegistryFullAccess**

      The first policy allows access to CloudWatch to enable stack rollbacks when an alarm occurs.

      The remaining policies allow AWS SAM to access the services and resources in the stack that will be deployed in this tutorial. For more information, see [Permissions](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-permissions.html) in the *AWS Serverless Application Model Developer Guide*.

   1. Choose **Next**.

   1. For **Role name**, enter:

      ```
      codecatalyst-stack-role
      ```

   1. Choose **Create role**.

1. Obtain the stack role's ARN, as follows:

   1. In the navigation pane, choose **Roles**.

   1. In the search box, enter the name of the role you just created (`codecatalyst-stack-role`).

   1. Choose the role from the list.

   1. In the **Summary** section, copy the **ARN** value. You need it later.

   You have now created the stack role with the appropriate permissions, and you have obtained its ARN.

## Step 3: Add AWS roles to CodeCatalyst
<a name="deploy-tut-lambda-cfn-roles-add"></a>

In this step, you add the build role (`codecatalyst-build-role`) and deploy role (`codecatalyst-deploy-role`) to the CodeCatalyst account connection in your space.

**Note**  
You don't need to add the stack role (`codecatalyst-stack-role`) to the connection. This is because the stack role is used by *CloudFormation* (not CodeCatalyst), *after* a connection is already established between CodeCatalyst and AWS using the deploy role. Since the stack role is not used by CodeCatalyst to gain access to AWS, it does not need to be associated with an account connection.

**To add build and deploy roles to your account connection**

1. In CodeCatalyst, navigate to your space.

1. Choose **AWS accounts**. A list of account connections appears.

1. Choose the account connection that represents the AWS account where you created your build and deploy roles.

1. Choose **Manage roles from AWS management console**.

   The **Add IAM role to Amazon CodeCatalyst space** page appears. You might need to sign in to access the page.

1. Select **Add an existing role you have created in IAM**.

   A drop-down list appears. The list displays all IAM roles with a trust policy that includes the `codecatalyst-runner.amazonaws.com` and `codecatalyst.amazonaws.com` service principals.

1. In the drop-down list, choose `codecatalyst-build-role`, and choose **Add role**.

1. Choose **Add IAM role**, choose **Add an existing role you have created in IAM**, and in the drop-down list, choose `codecatalyst-deploy-role`. Choose **Add role**.

   You have now added the build and deploy roles to your space.

1. Copy the value of the **Amazon CodeCatalyst display name**. You'll need this value later, when creating your workflow.

## Step 4: Create an Amazon S3 bucket
<a name="deploy-tut-lambda-cfn-s3"></a>

In this step, you create an Amazon S3 bucket where you store your serverless application's deployment package .zip file.

**To create an Amazon S3 bucket**

1. Open the Amazon S3 console at [https://console.aws.amazon.com/s3/](https://console.aws.amazon.com/s3/).

1. In the main pane, choose **Create bucket**.

1. For **Bucket name**, enter:

   ```
   codecatalyst-cfn-s3-bucket
   ```

1. For **AWS Region**, choose a Region. This tutorial assumes you chose **US West (Oregon) us-west-2**. For information about Regions supported by Amazon S3, see [Amazon Simple Storage Service endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/s3.html) in the *AWS General Reference*.

1. At the bottom of the page, choose **Create bucket**.

You have now created a bucket called **codecatalyst-cfn-s3-bucket** in the US West (Oregon) us-west-2 Region.

## Step 5: Add source files
<a name="deploy-tut-lambda-cfn-files"></a>

In this step, you add several application source files to your CodeCatalyst source repository. The `hello-world` folder contains the application files that you'll deploy. The `tests` folder contains unit tests. The folder structure is as follows:

```
.
|— hello-world
|  |— tests
|     |— unit
|        |— test-handler.js
|  |— app.js
|— .npmignore
|— package.json
|— sam-template.yml
|— setup-sam.sh
```

### .npmignore file
<a name="deploy-tut-lambda-cfn-files-npmignore"></a>

The `.npmignore` file indicates which files and folders npm should exclude from the application package. In this tutorial, npm excludes the `tests` folder because it is not part of the application.

**To add the .npmignore file**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project, `codecatalyst-cfn-project`

1. In the navigation pane, choose **Code**, and then choose **Source repositories**.

1. From the list of source repositories, choose your repository, `codecatalyst-cfn-source-repository`. 

1. In **Files**, choose **Create file**.

1. For **File name**, enter:

   ```
   .npmignore
   ```

1. In the text box, enter the following code:

   ```
   tests/*
   ```

1. Choose **Commit**, and then choose **Commit** again.

   You have now created a file called `.npmignore` in the root of your repository.

### package.json file
<a name="deploy-tut-lambda-cfn-files-package-json"></a>

The `package.json` file contains important metadata about your Node project such as the project name, version number, description, dependencies, and other details that describe how to interact with and run your application.

The `package.json` in this tutorial includes a list of dependencies and a `test` script. The test script does the following:
+ Using [mocha](https://mochajs.org/), the test script runs the unit tests specified in `hello-world/tests/unit/` and writes the results to a `junit.xml` file using the [xunit]() reporter.
+ Using [Istanbul (nyc)](https://istanbul.js.org/), the test script generates a code coverage report (`clover.xml`) using the [clover](https://openclover.org/doc/manual/4.2.0/general--about-openclover.html) reporter. For more information, see [Using alternative reporters](https://istanbul.js.org/docs/advanced/alternative-reporters/#clover) in the Istanbul documentation.

**To add the package.json file**

1. In your repository, in **Files**, choose **Create file**.

1. For **File name**, enter:

   ```
   package.json
   ```

1. In the text box, enter the following code:

   ```
   {
     "name": "hello_world",
     "version": "1.0.0",
     "description": "hello world sample for NodeJS",
     "main": "app.js",
     "repository": "https://github.com/awslabs/aws-sam-cli/tree/develop/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs",
     "author": "SAM CLI",
     "license": "MIT",
     "dependencies": {
       "axios": "^0.21.1",
       "nyc": "^15.1.0"
     },
     "scripts": {
       "test": "nyc --reporter=clover mocha hello-world/tests/unit/ --reporter xunit --reporter-option output=junit.xml"
     },
     "devDependencies": {
       "aws-sdk": "^2.815.0",
       "chai": "^4.2.0",
       "mocha": "^8.2.1"
     }
   }
   ```

1. Choose **Commit**, and then choose **Commit** again.

   You have now added a file called `package.json` to the root of the repository.

### sam-template.yml file
<a name="deploy-tut-lambda-cfn-files-sam-template-yml"></a>

The `sam-template.yml` file contains the instructions for deploying the Lambda function and API Gateway and configuring them together. It follows the [AWS Serverless Application Model template specification](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-specification.html), which extends the CloudFormation template specification.

You use an AWS SAM template in this tutorial instead of a regular CloudFormation template because AWS SAM offers a helpful [AWS::Serverless::Function](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-function.html) resource type. This type performs much behind-the-scenes configuration that you normally have to write out to use the basic CloudFormation syntax. For example, the `AWS::Serverless::Function` creates a Lambda function, Lambda execution role, and event source mappings that start the function. You have to code all of this if you want to write it using basic CloudFormation.

Although this tutorial uses a pre-written template, you can generate one as part of your workflow using a build action. For more information, see [Deploying an CloudFormation stack](deploy-action-cfn.md).

**To add the sam-template.yml file**

1. In your repository, in **Files**, choose **Create file**.

1. For **File name**, enter:

   ```
   sam-template.yml
   ```

1. In the text box, enter the following code:

   ```
   AWSTemplateFormatVersion: '2010-09-09'
   Transform: AWS::Serverless-2016-10-31
   Description: >
     serverless-api
   
     Sample SAM Template for serverless-api
     
   # More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
   Globals:
     Function:
       Timeout: 3
   
   Resources:
     HelloWorldFunction:
       Type: AWS::Serverless::Function # For details on this resource type, see https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
       Properties:
         CodeUri: hello-world/
         Handler: app.lambdaHandler
         Runtime: nodejs12.x
         Events:
           HelloWorld:
             Type: Api # For details on this event source type, see https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
             Properties:
               Path: /hello
               Method: get
   
   Outputs:
     # ServerlessRestApi is an implicit API created out of the events key under Serverless::Function
     # Find out about other implicit resources you can reference within AWS SAM at
     # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
     HelloWorldApi:
       Description: "API Gateway endpoint URL for the Hello World function"
       Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
     HelloWorldFunction:
       Description: "Hello World Lambda function ARN"
       Value: !GetAtt HelloWorldFunction.Arn
     HelloWorldFunctionIamRole:
       Description: "Implicit Lambda execution role created for the Hello World function"
       Value: !GetAtt HelloWorldFunctionRole.Arn
   ```

1. Choose **Commit**, and then choose **Commit** again.

   You have now added a file called `sam-template.yml` under the root folder of your repository.

### setup-sam.sh file
<a name="deploy-tut-lambda-cfn-files-setup-sam"></a>

The `setup-sam.sh` file contains the instructions for downloading and installing the AWS SAM CLI utility. The workflow uses this utility to package the `hello-world` source.

**To add the setup-sam.sh file**

1. In your repository, in **Files**, choose **Create file**.

1. For **File name**, enter:

   ```
   setup-sam.sh
   ```

1. In the text box, enter the following code:

   ```
   #!/usr/bin/env bash
   echo "Setting up sam"
   
   yum install unzip -y
   
   curl -LO https://github.com/aws/aws-sam-cli/releases/latest/download/aws-sam-cli-linux-x86_64.zip
   unzip -qq aws-sam-cli-linux-x86_64.zip -d sam-installation-directory
   
   ./sam-installation-directory/install; export AWS_DEFAULT_REGION=us-west-2
   ```

   In the preceding code, replace *us-west-2* with your AWS Region.

1. Choose **Commit**, and then choose **Commit** again.

   You have now added a file called `setup-sam.sh` to the root of the repository.

### app.js file
<a name="deploy-tut-lambda-cfn-files-app-js"></a>

The `app.js` contains the Lambda function code. In this tutorial, the code returns the text `hello world`.

**To add the app.js file**

1. In your repository, in **Files**, choose **Create file**.

1. For **File name**, enter:

   ```
   hello-world/app.js
   ```

1. In the text box, enter the following code:

   ```
   // const axios = require('axios')
   // const url = 'http://checkip.amazonaws.com/';
   let response;
   
   /**
    *
    * Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format
    * @param {Object} event - API Gateway Lambda Proxy Input Format
    *
    * Context doc: https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html 
    * @param {Object} context
    *
    * Return doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html
    * @returns {Object} object - API Gateway Lambda Proxy Output Format
    * 
    */
   exports.lambdaHandler = async (event, context) => {
       try {
           // const ret = await axios(url);
           response = {
               'statusCode': 200,
               'body': JSON.stringify({
                   message: 'hello world',
                   // location: ret.data.trim()
               })
           }
       } catch (err) {
           console.log(err);
           return err;
       }
   
       return response
   };
   ```

1. Choose **Commit**, and then choose **Commit** again.

   You have now created a folder called `hello-world` and a file called `app.js`.

### test-handler.js file
<a name="deploy-tut-lambda-cfn-files-test-handler-js"></a>

The `test-handler.js` file contains unit tests for the Lambda function.

**To add the test-handler.js file**

1. In your repository, in **Files**, choose **Create file**.

1. For **File name**, enter:

   ```
   hello-world/tests/unit/test-handler.js
   ```

1. In the text box, enter the following code:

   ```
   'use strict';
   
   const app = require('../../app.js');
   const chai = require('chai');
   const expect = chai.expect;
   var event, context;
   
   describe('Tests index', function () {
       it('verifies successful response', async () => {
           const result = await app.lambdaHandler(event, context)
   
           expect(result).to.be.an('object');
           expect(result.statusCode).to.equal(200);
           expect(result.body).to.be.an('string');
   
           let response = JSON.parse(result.body);
   
           expect(response).to.be.an('object');
           expect(response.message).to.be.equal("hello world");
           // expect(response.location).to.be.an("string");
       });
   });
   ```

1. Choose **Commit**, and then choose **Commit** again.

   You have now added a file called `test-handler.js` under the `hello-world/tests/unit` folder.

You have now added all your source files.

Take a moment to double-check your work and make sure you placed all the files in the correct folders. The folder structure is as follows:

```
.
|— hello-world
|  |— tests
|     |— unit
|        |— test-handler.js
|  |— app.js
|— .npmignore
|— README.md
|— package.json
|— sam-template.yml
|— setup-sam.sh
```

## Step 6: Create and run a workflow
<a name="deploy-tut-lambda-cfn-workflow"></a>

In this step, you create a workflow that packages your Lambda source code and deploys it. The workflow consists of the following building blocks that run sequentially:
+ A trigger – This trigger starts the workflow run automatically when you push a change to your source repository. For more information about triggers, see [Starting a workflow run automatically using triggers](workflows-add-trigger.md).
+ A test action (`Test`) – On trigger, this action installs [Node package manager (npm)](https://www.npmjs.com/), and then runs the `npm run test` command. This command tells npm to run the `test` script defined in the `package.json` file. The `test` script, in turn, runs the unit tests and generates two reports: a test report (`junit.xml`) and a code coverage report (`clover.xml`). For more information, see [package.json file](#deploy-tut-lambda-cfn-files-package-json).

  Next, the test action transforms the XML reports into CodeCatalyst reports and displays them in the CodeCatalyst console, under the **Reports** tab of the test action.

  For more information about the test action, see [Testing with workflowsTesting with workflows](test-workflow-actions.md).
+ A build action (`BuildBackend`) – On completion of the test action, the build action downloads and installs the AWS SAM CLI, packages the `hello-world` source, and copies the package to your Amazon S3 bucket, where the Lambda service expects it to be. The action also outputs a new AWS SAM template file called `sam-template-packaged.yml` and places it in an output artifact called `buildArtifact`.

  For more information about the build action, see [Building with workflows](build-workflow-actions.md).
+ A deploy action (`DeployCloudFormationStack`) – On completion of the build action, the deploy action looks for the output artifact generated by the build action (`buildArtifact`), finds the AWS SAM template inside of it, and then runs the template. The AWS SAM template creates a stack that deploys the serverless application.

**To create a workflow**

1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

1. Choose **Create workflow**.

1. For **Source repository**, choose `codecatalyst-cfn-source-repository`.

1. For **Branch**, choose `main`.

1. Choose **Create**.

1. Delete the YAML sample code.

1. Add the following YAML code:
**Note**  
In the YAML code that follows, you can omit the `Connections:` sections if you want. If you omit these sections, you must ensure that the role specified in the **Default IAM role** field in your environment includes the permissions and trust policies of both roles described in [Step 2: Create AWS roles](#deploy-tut-lambda-cfn-roles). For more information about setting up an environment with a default IAM role, see [Creating an environment](deploy-environments-creating-environment.md).

   ```
   Name: codecatalyst-cfn-workflow
   SchemaVersion: 1.0
   
   Triggers:
     - Type: PUSH
       Branches:
         - main   
   Actions:
     Test:
       Identifier: aws/managed-test@v1
       Inputs:
         Sources:
           - WorkflowSource
       Outputs:
         Reports:
           CoverageReport:
             Format: CLOVERXML
             IncludePaths:
               - "coverage/*"
           TestReport:
             Format: JUNITXML
             IncludePaths:
               - junit.xml
       Configuration:
         Steps:
           - Run: npm install
           - Run: npm run test  
     BuildBackend:
       Identifier: aws/build@v1
       DependsOn:
         - Test
       Environment:
         Name: codecatalyst-cfn-environment
         Connections:
           - Name: codecatalyst-account-connection
             Role: codecatalyst-build-role
       Inputs:
         Sources:
           - WorkflowSource
       Configuration: 
         Steps:
           - Run: . ./setup-sam.sh
           - Run: sam package --template-file sam-template.yml --s3-bucket codecatalyst-cfn-s3-bucket --output-template-file sam-template-packaged.yml --region us-west-2
       Outputs:
         Artifacts:
           - Name: buildArtifact
             Files:
               - "**/*"
     DeployCloudFormationStack:
       Identifier: aws/cfn-deploy@v1
       DependsOn: 
         - BuildBackend
       Environment:
         Name: codecatalyst-cfn-environment
         Connections:
           - Name: codecatalyst-account-connection
             Role: codecatalyst-deploy-role
       Inputs:
         Artifacts:
           - buildArtifact
         Sources: []
       Configuration:
         name: codecatalyst-cfn-stack
         region: us-west-2
         role-arn: arn:aws:iam::111122223333:role/StackRole
         template: ./sam-template-packaged.yml
         capabilities: CAPABILITY_IAM,CAPABILITY_AUTO_EXPAND
   ```

   In the preceding code, replace:
   + Both instances of *codecatalyst-cfn-environment* with the name of your environment.
   + Both instances of *codecatalyst-account-connection* with the display name of your account connection. The display name might be a number. For more information, see [Step 3: Add AWS roles to CodeCatalyst](#deploy-tut-lambda-cfn-roles-add).
   + *codecatalyst-build-role* with the name of the build role that you created in [Step 2: Create AWS roles](#deploy-tut-lambda-cfn-roles).
   + *codecatalyst-cfn-s3-bucket* with the name of the Amazon S3 bucket you created in [Step 4: Create an Amazon S3 bucket](#deploy-tut-lambda-cfn-s3).
   + Both instances of *us-west-2* with the Region where your Amazon S3 bucket resides (first instance) and where your stack will be deployed (second instance). These Regions can be different. This tutorial assumes that both Regions are set to `us-west-2`. For details about Regions supported by Amazon S3 and CloudFormation, see [Service endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html) in the *AWS General Reference*.
   + *codecatalyst-deploy-role* with the name of the deploy role that you created in [Step 2: Create AWS roles](#deploy-tut-lambda-cfn-roles).
   + *codecatalyst-cfn-environment* with the name of the environment that you created in [Prerequisites](#deploy-tut-lambda-cfn-prereqs).
   + *arn:aws:iam::111122223333:role/StackRole* with the Amazon Resource Name (ARN) of the stack role that you created in [Step 2: Create AWS roles](#deploy-tut-lambda-cfn-roles).
**Note**  
If you decided not to create build, deploy, and stack roles, replace *codecatalyst-build-role*, *codecatalyst-deploy-role*, and *arn:aws:iam::111122223333:role/StackRole* with the name or ARN of the `CodeCatalystWorkflowDevelopmentRole-spaceName` role. For more information about this role, see [Step 2: Create AWS roles](#deploy-tut-lambda-cfn-roles).

   For information about the properties in the code shown previously, see the ['Deploy CloudFormation stack' action YAML](deploy-action-ref-cfn.md).

1. (Optional) Choose **Validate** to make sure the YAML code is valid before committing.

1. Choose **Commit**.

1. On the **Commit workflow** dialog box, enter the following:

   1. For **Workflow file name**, keep the default, `codecatalyst-cfn-workflow`.

   1. For **Commit message**, enter:

      ```
      add initial workflow file
      ```

   1. For **Repository**, choose **codecatalyst-cfn-source-repository**.

   1. For **Branch name**, choose **main**.

   1. Choose **Commit**.

   You have now created a workflow. A workflow run starts automatically because of the trigger defined at the top of the workflow. Specifically, when you committed (and pushed) the `codecatalyst-cfn-workflow.yaml` file to your source repository, the trigger started the workflow run.

**To view the workflow run in progress**

1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

1. Choose the workflow you just created: `codecatalyst-cfn-workflow`.

1. Choose the **Runs** tab.

1. In the **Run ID** column, choose the run ID.

1. Choose **Test** to see the tests progress.

1. Choose **BuildBackend** to see the build progress.

1. Choose **DeployCloudFormationStack** to see the deployment progress.

   For more information about viewing run details, see [Viewing workflow run status and details](workflows-view-run.md).

1. When the **DeployCloudFormationStack** action finishes, do the following:
   + If the workflow run succeeded, go to the next procedure.
   + If the workflow run failed on the **Test** or **BuildBackend** action, choose **Logs** to troubleshoot the issue.
   + If the workflow run failed on the **DeployCloudFormationStack** action, choose the deploy action, and then choose the **Summary** tab. Scroll to the **CloudFormation events** section to view the detailed error message. If a rollback occurred, delete the `codecatalyst-cfn-stack` stack through the CloudFormation console in AWS before re-running the workflow.

**To verify the deployment**

1. After a successful deployment, choose **Variables (7)** from the horizontal menu bar near the top. (Do not choose **Variables** in the pane on the right.)

1. Next to **HelloWorldApi**, paste the `https://` URL into a browser.

   A **hello world** JSON message from the Lambda function is displayed, indicating that the workflow deployed and configured the Lambda function and API Gateway successfully.
**Tip**  
You can have CodeCatalyst display this URL in the workflow diagram with a few small configurations. For more information, see [Displaying the app URL in the workflow diagram](deploy-app-url.md).

**To verify unit test results and code coverage**

1. In the workflow diagram, choose **Test**, and then choose **Reports**.

1. Choose **TestReport** to view the unit test results, or choose **CoverageReport** to view the code coverage details of the files being tested, in this case, `app.js` and `test-handler.js`.

**To verify deployed resources**

1. Sign in to the AWS Management Console and open the API Gateway console at [https://console.aws.amazon.com/apigateway/](https://console.aws.amazon.com/apigateway/). 

1. Observe the **codecatalyst-cfn-stack** API that the AWS SAM template created. The API name comes from the `Configuration/name` value in the workflow definition file (`codecatalyst-cfn-workflow.yaml`).

1. Open the AWS Lambda console at [https://console.aws.amazon.com/lambda/](https://console.aws.amazon.com/lambda/).

1. In the navigation pane, choose **Functions**.

1. Choose your Lambda function, `codecatalyst-cfn-stack-HelloWorldFunction-string`.

1. You can see how the API Gateway is a trigger for the function. This integration was automatically configured by the AWS SAM `AWS::Serverless::Function` resource type.

## Step 7: Make a change
<a name="deploy-tut-lambda-cfn-change"></a>

In this step, you make a change to your Lambda source code and commit it. This commit starts a new workflow run. This run deploys the new Lambda function in a blue-green scheme that uses the default traffic shifting configuration specified in the Lambda console.

**To make a change to your Lambda source**

1. In CodeCatalyst, navigate to your project.

1. In the navigation pane, choose **Code**, and then choose **Source repositories**.

1. Choose your source repository `codecatalyst-cfn-source-repository`.

1. Change the application file:

   1. Choose the `hello-world` folder.

   1. Choose the `app.js` file.

   1. Choose **Edit**.

   1. On line 23, change `hello world` to **Tutorial complete\$1**.

   1. Choose **Commit**, and then choose **Commit** again.

      The commit causes a workflow run to start. This run will fail because you haven't updated the unit tests to reflect the name change.

1. Update the unit tests:

   1. Choose `hello-world\tests\unit\test-handler.js`.

   1. Choose **Edit**.

   1. On line 19, change `hello world` to **Tutorial complete\$1**.

   1. Choose **Commit**, and then choose **Commit** again.

      The commit causes another workflow run to start. This run will succeed.

1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

1. Choose `codecatalyst-cfn-workflow`, and then choose **Runs**.

1. Choose the run ID of the latest run. It should still be in progress.

1. Choose **Test**, **BuildBackend**, and **DeployCloudFormationStack** to see the workflow run progress.

1. When the workflow finishes, choose **Variables (7)** near the top.

1. Next to **HelloWorldApi**, paste the `https://` URL into a browser.

   A `Tutorial complete!` message appears in the browser, indicating that your new application was deployed successfully.

## Clean up
<a name="deploy-tut-lambda-cfn-clean-up"></a>

Clean up the files and services used in this tutorial to avoid being charged for them.

**To clean up in the CodeCatalyst console**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Delete `codecatalyst-cfn-workflow`.

1. Delete `codecatalyst-cfn-environment`.

1. Delete `codecatalyst-cfn-source-repository`.

1. Delete `codecatalyst-cfn-project`.

**To clean up in the AWS Management Console**

1. Clean up in CloudFormation, as follows:

   1. Open the CloudFormation console at [https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/).

   1. Delete the `codecatalyst-cfn-stack`.

      Deleting the stack removes all tutorial resources from the API Gateway and Lambda services.

1. Clean up in Amazon S3, as follows:

   1. Open the Amazon S3 console at [https://console.aws.amazon.com/s3/](https://console.aws.amazon.com/s3/).

   1. Choose the `codecatalyst-cfn-s3-bucket`.

   1. Delete the bucket contents.

   1. Delete the bucket.

1. Clean up in IAM, as follows:

   1. Open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

   1. Delete the `codecatalyst-deploy-policy`.

   1. Delete the `codecatalyst-build-policy`.

   1. Delete the `codecatalyst-stack-policy`.

   1. Delete the `codecatalyst-deploy-role`.

   1. Delete the `codecatalyst-build-role`.

   1. Delete the `codecatalyst-stack-role`.

In this tutorial, you learned how to deploy a serverless application as a CloudFormation stack using a CodeCatalyst workflow and a **Deploy CloudFormation stack** action.

# Adding the 'Deploy CloudFormation stack' action
<a name="deploy-action-cfn-adding"></a>

Use the following instructions to add the **Deploy CloudFormation stack** action to your workflow. 

------
#### [ Visual ]

**To add the 'Deploy CloudFormation stack' action using the visual editor**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

1. Choose the name of your workflow. You can filter by the source repository or branch name where the workflow is defined, or filter by workflow name or status.

1. Choose **Edit**.

1. Choose **Visual**.

1. At the top-left, choose **\$1 Actions** to open the action catalog.

1. From the drop-down list, choose **Amazon CodeCatalyst**.

1. Search for the **Deploy CloudFormation stack** action, and do one of the following:
   + Choose the plus sign (**\$1**) to add the action to the workflow diagram and open its configuration pane.

     Or
   + Choose **Deploy CloudFormation stack**. The action details dialog box appears. On this dialog box:
     + (Optional) Choose **Download** to [view the action's source code](workflows-view-source.md#workflows-view-source.title).
     + Choose **Add to workflow** to add the action to the workflow diagram and open its configuration pane.

1. In the **Inputs** and **Configuration** tabs, complete the fields according to your needs. For a description of each field, see the ['Deploy CloudFormation stack' action YAML](deploy-action-ref-cfn.md). This reference provides detailed information about each field (and corresponding YAML property value) as it appears in both the YAML and visual editors.

1. (Optional) Choose **Validate** to validate the workflow's YAML code before committing.

1. Choose **Commit**, enter a commit message, and choose **Commit** again.

------
#### [ YAML ]

**To add the 'Deploy CloudFormation stack' action using the YAML editor**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

1. Choose the name of your workflow. You can filter by the source repository or branch name where the workflow is defined, or filter by workflow name or status.

1. Choose **Edit**.

1. Choose **YAML**.

1. At the top-left, choose **\$1 Actions** to open the action catalog.

1. From the drop-down list, choose **Amazon CodeCatalyst**.

1. Search for the **Deploy CloudFormation stack** action, and do one of the following:
   + Choose the plus sign (**\$1**) to add the action to the workflow diagram and open its configuration pane.

     Or
   + Choose **Deploy CloudFormation stack**. The action details dialog box appears. On this dialog box:
     + (Optional) Choose **Download** to [view the action's source code](workflows-view-source.md#workflows-view-source.title).
     + Choose **Add to workflow** to add the action to the workflow diagram and open its configuration pane.

1. Modify the properties in the YAML code according to your needs. An explanation of each available property is provided in the ['Deploy CloudFormation stack' action YAML](deploy-action-ref-cfn.md).

1. (Optional) Choose **Validate** to validate the workflow's YAML code before committing.

1. Choose **Commit**, enter a commit message, and choose **Commit** again.

------

# Configuring rollbacks
<a name="deploy-consumption-enable-alarms"></a>

By default, if the **Deploy CloudFormation stack** action fails, it will cause CloudFormation to roll back the stack to the last known stable state. You can change the behavior so that rollbacks occur not only when the action fails, but also when a specified Amazon CloudWatch alarm occurs. For more information about CloudWatch alarms, see [Using Amazon CloudWatch alarms](https://docs.aws.amazon.com/) in the *Amazon CloudWatch User Guide*.

You can also change the default behavior so that CloudFormation does not roll back the stack when the action fails. 

Use the following instructions to configure rollbacks.

**Note**  
You cannot start a rollback manually.

------
#### [ Visual ]

**Before you begin**

1. Make sure you have a [workflow](workflow.md) that includes a functioning **Deploy CloudFormation stack** action. For more information, see [Deploying an CloudFormation stack](deploy-action-cfn.md).

1. In the role specified in the **Stack role - optional** field of the **Deploy CloudFormation stack** action, make sure to include the **CloudWatchFullAccess** permission. For information about creating this role with the appropriate permissions, see [Step 2: Create AWS roles](deploy-tut-lambda.md#deploy-tut-lambda-cfn-roles).

**To configure rollback alarms for the 'Deploy CloudFormation stack' action**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

1. Choose the name of your workflow. You can filter by the source repository or branch name where the workflow is defined, or filter by workflow name or status.

1. Choose **Edit**.

1. Choose **Visual**.

1. Choose your **Deploy CloudFormation stack** action.

1. In the details pane, choose **Configuration**.

1. At the bottom, expand **Advanced**.

1. Under **Monitor alarm ARNs**, choose **Add alarm**.

1. Enter information into the following fields.
   + **Alarm ARN**

     Specify the Amazon Resource Name (ARN) of an Amazon CloudWatch alarm to use as a rollback trigger. For example, `arn:aws:cloudwatch::123456789012:alarm/MyAlarm`. You can have a maximum of five rollback triggers.
**Note**  
If you specify a CloudWatch alarm ARN, you'll also need to configure additional permissions to enable the action to access CloudWatch. For more information, see [Configuring rollbacks](#deploy-consumption-enable-alarms).
   + **Monitoring time**

     Specify an amount of time, from 0 to 180 minutes, during which CloudFormation monitors the specified alarms. Monitoring begins *after* all the stack resources have been deployed. If the alarm occurs within the specified monitoring time, then the deployment fails, and CloudFormation rolls back the entire stack operation.

     Default: 0. CloudFormation only monitors alarms while the stack resources are being deployed, not after.

------
#### [ YAML ]

**To configure rollback triggers for the 'Deploy CloudFormation stack' action**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

1. Choose the name of a workflow that includes the **Deploy CloudFormation stack** action. You can filter by the source repository or branch name where the workflow is defined, or filter by workflow name or status.

1. Choose **Edit**.

1. Choose **YAML**.

1. Add the `monitor-alarm-arns` and `monitor-timeout-in-minutes` properties in the YAML code to add rollback triggers. For an explanation of each property, see ['Deploy CloudFormation stack' action YAML](deploy-action-ref-cfn.md).

1. In the role specified in the `role-arn` property of the **Deploy CloudFormation stack** action, make sure to include the **CloudWatchFullAccess** permission. For information about creating this role with the appropriate permissions, see [Step 2: Create AWS roles](deploy-tut-lambda.md#deploy-tut-lambda-cfn-roles).

------

------
#### [ Visual ]

**To turn off rollbacks for the 'Deploy CloudFormation stack' action**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

1. Choose the name of a workflow that includes the **Deploy CloudFormation stack** action. You can filter by the source repository or branch name where the workflow is defined, or filter by workflow name or status.

1. Choose **Edit**.

1. Choose **Visual**.

1. Choose your **Deploy CloudFormation stack** action.

1. In the details pane, choose **Configuration**.

1. At the bottom, expand **Advanced**.

1. Turn on **Disable rollback**.

------
#### [ YAML ]

**To turn off rollbacks for the 'Deploy CloudFormation stack' action**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

1. Choose the name of a workflow that includes the **Deploy CloudFormation stack** action. You can filter by the source repository or branch name where the workflow is defined, or filter by workflow name or status.

1. Choose **Edit**.

1. Choose **YAML**.

1. Add the `disable-rollback: 1` property in the YAML code to stop rollbacks. For an explanation of this property, see ['Deploy CloudFormation stack' action YAML](deploy-action-ref-cfn.md).

------

# 'Deploy CloudFormation stack' variables
<a name="deploy-action-cfn-variables"></a>

The **Deploy CloudFormation stack** action produces and sets the following variables at run time. These are known as *predefined variables*.

For information about referencing these variables in a workflow, see [Using predefined variables](workflows-using-predefined-variables.md).


| Key | Value | 
| --- | --- | 
|  deployment-platform  |  The name of the deployment platform. Hardcoded to `AWS:CloudFormation`.  | 
|  region  |  The region code of the AWS Region that was deployed to during the workflow run. Example: `us-west-2`  | 
|  stack-id  |  The Amazon Resource Name (ARN) of the deployed stack. Example: `arn:aws:cloudformation:us-west-2:111122223333:stack/codecatalyst-cfn-stack/6aad4380-100a-11ec-a10a-03b8a84d40df`  | 

# 'Deploy CloudFormation stack' action YAML
<a name="deploy-action-ref-cfn"></a>

The following is the YAML definition of the **Deploy CloudFormation stack** action. To learn how to use this action, see [Deploying an CloudFormation stack](deploy-action-cfn.md).

This action definition exists as a section within a broader workflow definition file. For more information about this file, see [Workflow YAML definition](workflow-reference.md).

**Note**  
Most of the YAML properties that follow have corresponding UI elements in the visual editor. To look up a UI element, use **Ctrl\$1F**. The element will be listed with its associated YAML property.

```
# The workflow definition starts here.
# See Top-level properties for details.
        
Name: MyWorkflow
SchemaVersion: 1.0 
Actions:

# The action definition starts here.    
  DeployCloudFormationStack:  
    Identifier: aws/cfn-deploy@v1
    DependsOn:
      - build-action
    Compute:  
      Type: EC2 | Lambda
      Fleet: fleet-name
    Timeout: timeout-minutes
    Environment:
      Name: environment-name
      Connections:
        - Name: account-connection-name
          Role: DeployRole
    Inputs:
      Sources:
        - source-name-1
      Artifacts:
        - CloudFormation-artifact
    Configuration:
      name: stack-name
      region: us-west-2
      template: template-path
      role-arn: arn:aws:iam::123456789012:role/StackRole        
      capabilities: CAPABILITY_IAM,CAPABILITY_NAMED_IAM,CAPABILITY_AUTO_EXPAND
      parameter-overrides: KeyOne=ValueOne,KeyTwo=ValueTwo | path-to-JSON-file
      no-execute-changeset: 1|0
      fail-on-empty-changeset: 1|0
      disable-rollback: 1|0
      termination-protection: 1|0
      timeout-in-minutes: minutes
      notification-arns: arn:aws:sns:us-east-1:123456789012:MyTopic,arn:aws:sns:us-east-1:123456789012:MyOtherTopic
      monitor-alarm-arns: arn:aws:cloudwatch::123456789012:alarm/MyAlarm,arn:aws:cloudwatch::123456789012:alarm/MyOtherAlarm
      monitor-timeout-in-minutes: minutes       
      tags: '[{"Key":"MyKey1","Value":"MyValue1"},{"Key":"MyKey2","Value":"MyValue2"}]'
```

## DeployCloudFormationStack
<a name="deploy.action.cfn.deploycloudformationstack"></a>

(Required)

Specify the name of the action. All action names must be unique within the workflow. Action names are limited to alphanumeric characters (a-z, A-Z, 0-9), hyphens (-), and underscores (\$1). Spaces are not allowed. You cannot use quotation marks to enable special characters and spaces in action names.

Default: `DeployCloudFormationStack_nn`.

Corresponding UI: Configuration tab/**Action display name**

## Identifier
<a name="deploy.action.cfn.identifier"></a>

(*DeployCloudFormationStack*/**Identifier**)

(Required)

Identifies the action. Do not change this property unless you want to change the version. For more information, see [Specifying the action version to use](workflows-action-versions.md).

Default: `aws/cfn-deploy@v1`.

Corresponding UI: Workflow diagram/DeployCloudFormationStack\$1nn/**aws/cfn-deploy@v1** label

## DependsOn
<a name="deploy.action.cfn.dependson"></a>

(*DeployCloudFormationStack*/**DependsOn**)

(Optional)

Specify an action, action group, or gate that must run successfully in order for this action to run.

For more information about the 'depends on' functionality, see [Sequencing actions](workflows-depends-on.md).

Corresponding UI: Inputs tab/**Depends on - optional**

## Compute
<a name="deploy.action.cfn.computename"></a>

(*DeployCloudFormationStack*/**Compute**)

(Optional)

The computing engine used to run your workflow actions. You can specify compute either at the workflow level or at the action level, but not both. When specified at the workflow level, the compute configuration applies to all actions defined in the workflow. At the workflow level, you can also run multiple actions on the same instance. For more information, see [Sharing compute across actions](compute-sharing.md).

Corresponding UI: *none*

## Type
<a name="deploy.action.cfn.computetype"></a>

(*DeployCloudFormationStack*/Compute/**Type**)

(Required if [Compute](#deploy.action.cfn.computename) is included)

The type of compute engine. You can use one of the following values:
+ **EC2** (visual editor) or `EC2` (YAML editor)

  Optimized for flexibility during action runs.
+ **Lambda** (visual editor) or `Lambda` (YAML editor)

  Optimized action start-up speeds.

For more information about compute types, see [Compute types](workflows-working-compute.md#compute.types).

Corresponding UI: Configuration tab/Advanced - optional/**Compute type**

## Fleet
<a name="deploy.action.cfn.computefleet"></a>

(*DeployCloudFormationStack*/Compute/**Fleet**)

(Optional)

Specify the machine or fleet that will run your workflow or workflow actions. With on-demand fleets, when an action starts, the workflow provisions the resources it needs, and the machines are destroyed when the action finishes. Examples of on-demand fleets: `Linux.x86-64.Large`, `Linux.x86-64.XLarge`. For more information about on-demand fleets, see [On-demand fleet properties](workflows-working-compute.md#compute.on-demand).

With provisioned fleets, you configure a set of dedicated machines to run your workflow actions. These machines remain idle, ready to process actions immediately. For more information about provisioned fleets, see [Provisioned fleet properties](workflows-working-compute.md#compute.provisioned-fleets).

If `Fleet` is omitted, the default is `Linux.x86-64.Large`.

Corresponding UI: Configuration tab/Advanced - optional/**Compute fleet**

## Timeout
<a name="deploy.action.cfn.timeout"></a>

(*DeployCloudFormationStack*/**Timeout**)

(Optional)

Specify the amount of time in minutes (YAML editor), or hours and minutes (visual editor), that the action can run before CodeCatalyst ends the action. The minimum is 5 minutes and the maximum is described in [Quotas for workflows in CodeCatalyst](workflows-quotas.md). The default timeout is the same as the maximum timeout.

Corresponding UI: Configuration tab/**Timeout in minutes - optional **

## Environment
<a name="deploy.action.cfn.environment"></a>

(*DeployCloudFormationStack*/**Environment**)

(Required)

Specify the CodeCatalyst environment to use with the action. The action connects to the AWS account and optional Amazon VPC specified in the chosen environment. The action uses the default IAM role specified in the environment to connect to the AWS account, and uses the IAM role specified in the [Amazon VPC connection](https://docs.aws.amazon.com/codecatalyst/latest/adminguide/managing-vpcs.add.html) to connect to the Amazon VPC.

**Note**  
If the default IAM role does not have the permissions required by the action, you can configure the action to use a different role. For more information, see [Changing the IAM role of an action](deploy-environments-switch-role.md).

For more information about environments, see [Deploying into AWS accounts and VPCs](deploy-environments.md) and [Creating an environment](deploy-environments-creating-environment.md).

Corresponding UI: Configuration tab/**Environment**

## Name
<a name="deploy.action.cfn.environment.name"></a>

(*DeployCloudFormationStack*/Environment/**Name**)

(Required if [Environment](#deploy.action.cfn.environment) is included)

Specify the name of an existing environment that you want to associate with the action.

Corresponding UI: Configuration tab/**Environment**

## Connections
<a name="deploy.action.cfn.environment.connections"></a>

(*DeployCloudFormationStack*/Environment/**Connections**)

(Optional in newer versions of the action; required in older versions)

Specify the account connection to associate with the action. You can specify a maximum of one account connection under `Environment`.

If you do not specify an account connection:
+ The action uses the AWS account connection and default IAM role specified in the environment in the CodeCatalyst console. For information about adding an account connection and default IAM role to environment, see [Creating an environment](deploy-environments-creating-environment.md).
+ The default IAM role must include the policies and permissions required by the action. To determine what those policies and permissions are, see the description of the **Role** property in the action's YAML definition documentation.

For more information about account connections, see [Allowing access to AWS resources with connected AWS accounts](ipa-connect-account.md). For information about adding an account connection to an environment, see [Creating an environment](deploy-environments-creating-environment.md).

Corresponding UI: One of the following depending on the action version:
+ (Newer versions) Configuration tab/Environment/What's in *my-environment*?/three dot menu/**Switch role**
+ (Older versions) Configuration tab/'Environment/account/role'/**AWS account connection**

## Name
<a name="deploy.action.cfn.environment.connections.name"></a>

(*DeployCloudFormationStack*/Environment/Connections/**Name**)

(Required if [Connections](#deploy.action.cfn.environment.connections) is included)

Specify the name of the account connection.

Corresponding UI: One of the following depending on the action version:
+ (Newer versions) Configuration tab/Environment/What's in *my-environment*?/three dot menu/**Switch role**
+ (Older versions) Configuration tab/'Environment/account/role'/**AWS account connection**

## Role
<a name="deploy.action.cfn.environment.connections.role"></a>

(*DeployCloudFormationStack*/Environment/Connections/**Role**)

(Required if [Connections](#deploy.action.cfn.environment.connections) is included)

Specify the name of the IAM role that the **Deploy CloudFormation stack** action uses to access AWS and the CloudFormation service. Make sure that you have [added the role to your CodeCatalyst space](ipa-connect-account-addroles.md), and that the role includes the following policies.

If you do not specify an IAM role, then the action uses the default IAM role listed in the [environment](deploy-environments.md) in the CodeCatalyst console. If you use the default role in the environment, make sure it has the following policies.
+ The following permissions policy:
**Warning**  
Limit the permissions to those shown in the following policy. Using a role with broader permissions might pose a security risk.
**Note**  
The first time the role is used, use the following wildcard in the resource policy statement and then scope down the policy with the resource name after it is available.  

  ```
  "Resource": "*"
  ```
+ The following custom trust policy:

**Note**  
You can use the `CodeCatalystWorkflowDevelopmentRole-spaceName` role with this action, if you'd like. For more information about this role, see [Creating the **CodeCatalystWorkflowDevelopmentRole-*spaceName*** role for your account and space](ipa-iam-roles.md#ipa-iam-roles-service-create). Understand that the `CodeCatalystWorkflowDevelopmentRole-spaceName` role has full access permissions which may pose a security risk. We recommend that you only use this role in tutorials and scenarios where security is less of a concern. 

Corresponding UI: One of the following depending on the action version:
+ (Newer versions) Configuration tab/Environment/What's in *my-environment*?/three dot menu/**Switch role**
+ (Older versions) Configuration tab/'Environment/account/role'/**Role**

## Inputs
<a name="deploy.action.cfn.inputs"></a>

(*DeployCloudFormationStack*/**Inputs**)

(Optional)

The `Inputs` section defines the data that the `DeployCloudFormationStack` needs during a workflow run.

**Note**  
A maximum of four inputs (one source and three artifacts) are allowed per **Deploy CloudFormation stack** action.

If you need to refer to files residing in different inputs (say a source and an artifact), the source input is the primary input, and the artifact is the secondary input. References to files in secondary inputs take a special prefix to distiguish them from the primary. For details, see [Example: Referencing files in multiple artifacts](workflows-working-artifacts-ex.md#workflows-working-artifacts-ex-ref-file).

Corresponding UI: **Inputs** tab

## Sources
<a name="deploy.action.cfn.inputs.sources"></a>

(*DeployCloudFormationStack*/Inputs/**Sources**)

(Required if your CloudFormation or AWS SAM template is stored in a source repository)

If your CloudFormation or AWS SAM template is stored in a source repository, specify the label of that source repository. Currently, the only supported label is `WorkflowSource`.

If your CloudFormation or AWS SAM template is not contained within a source repository, it must reside in an artifact generated by another action, or in an Amazon S3 bucket.

For more information about sources, see [Connecting source repositories to workflows](workflows-sources.md).

Corresponding UI: Inputs tab/**Sources - optional**

## Artifacts - input
<a name="deploy.action.cfn.inputs.artifacts"></a>

(*DeployCloudFormationStack*/Inputs/**Artifacts**)

(Required if your CloudFormation or AWS SAM template is stored in an [output artifact](workflows-working-artifacts-output.md) from a previous action)

If the CloudFormation or AWS SAM template that you want to deploy is contained in an artifact generated by a previous action, specify that artifact here. If your CloudFormation template is not contained within an artifact, it must reside in your source repository or in an Amazon S3 bucket.

For more information about artifacts, including examples, see [Sharing artifacts and files between actions](workflows-working-artifacts.md).

Corresponding UI: Configuration tab/**Artifacts - optional**

## Configuration
<a name="deploy.action.cfn.configuration"></a>

(*DeployCloudFormationStack*/**Configuration**)

(Required)

A section where you can define the configuration properties of the action.

Corresponding UI: **Configuration** tab

## name
<a name="deploy.action.cfn.stackname"></a>

(*DeployCloudFormationStack*/Configuration/**name**)

(Required)

Specify a name for the CloudFormation stack that the **Deploy CloudFormation stack** action creates or updates.

Corresponding UI: Configuration tab/**Stack name**

## region
<a name="deploy.action.cfn.stackregion"></a>

(*DeployCloudFormationStack*/Configuration/**region**)

(Required)

Specify the AWS Region into which the stack will be deployed. For a list of Region codes, see [Regional endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html#region-names-codes).

Corresponding UI: Configuration tab/**Stack region**

## template
<a name="deploy.action.cfn.templatepath"></a>

(*DeployCloudFormationStack*/Configuration/**template**)

(Required)

Specify the name and path to your CloudFormation or AWS SAM template file. The template can be in JSON or YAML format, and can reside in a source repository, an artifact from a previous action, or an Amazon S3 bucket. If the template file is in a source repository or artifact, the path is relative to the source or artifact root. If the template is in an Amazon S3 bucket, the path is the template's **Object URL** value.

Examples:

`./MyFolder/MyTemplate.json`

`MyFolder/MyTemplate.yml`

`https://MyBucket.s3.us-west-2.amazonaws.com/MyTemplate.yml`

**Note**  
You may need to add a prefix to the template's file path to indicate which artifact or source to find it in. For more information, see [Referencing source repository files](workflows-sources-reference-files.md) and [Referencing files in an artifact](workflows-working-artifacts-refer-files.md).

Corresponding UI: Configuration tab/**Template**

## role-arn
<a name="deploy.action.cfn.stackrolearn"></a>

(*DeployCloudFormationStack*/Configuration/**role-arn**)

(Required)

Specify the Amazon Resource Name (ARN) of the stack role. CloudFormation uses this role to access and modify resources in your stack. For example: `arn:aws:iam::123456789012:role/StackRole`.

Make sure the stack role includes:
+ One or more permissions policies. The policies depend on the resources you have in your stack. For example, if your stack includes an AWS Lambda function, you need to add permissions that grant access to Lambda. If you followed the tutorial described in [Tutorial: Deploy a serverless application](deploy-tut-lambda.md), it includes a procedure titled, [To create a stack role](deploy-tut-lambda.md#deploy-tut-lambda-cfn-roles-stack) that lists the permissions that the stack role needs if you're deploying a typical serverless application stack.
**Warning**  
Limit the permissions to those required by the CloudFormation service to access resources in your stack. Using a role with broader permissions might pose a security risk.
+ The following trust policy:

------
#### [ JSON ]

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Statement": [
          {
              "Sid": "",
              "Effect": "Allow",
              "Principal": {
                  "Service": "cloudformation.amazonaws.com"
              },
              "Action": "sts:AssumeRole"
          }
      ]
  }
  ```

------

Optionally, associate this role with your account connection. To learn more about associating an IAM role with an account connection, see [Adding IAM roles to account connections](ipa-connect-account-addroles.md). If you do not associate the stack role with the account connection, then the stack role will not appear in the **Stack role** drop-down list in the visual editor; however, the role ARN can still be specified in the `role-arn` field using the YAML editor.

**Note**  
You can use the `CodeCatalystWorkflowDevelopmentRole-spaceName` role with this action, if you'd like. For more information about this role, see [Creating the **CodeCatalystWorkflowDevelopmentRole-*spaceName*** role for your account and space](ipa-iam-roles.md#ipa-iam-roles-service-create). Understand that the `CodeCatalystWorkflowDevelopmentRole-spaceName` role has full access permissions which may pose a security risk. We recommend that you only use this role in tutorials and scenarios where security is less of a concern. 

Corresponding UI: Configuration tab/**Stack role - optional**

## capabilities
<a name="deploy.action.cfn.capabilities"></a>

(*DeployCloudFormationStack*/Configuration/**capabilities**)

(Required)

Specify a list of IAM capabilities that are required to allow CloudFormation to create certain stacks. In most cases, you can leave `capabilities` with the default value of `CAPABILITY_IAM,CAPABILITY_NAMED_IAM,CAPABILITY_AUTO_EXPAND`.

If you see `##[error] requires capabilities: [capability-name]` in your **Deploy CloudFormation stack** action's logs, see [How do I fix IAM capabilities errors?](troubleshooting-workflows.md#troubleshooting-workflows-capabilities) for information about how to fix the problem.

For more information about IAM capabilities, see [Acknowledging IAM resources in CloudFormation templates](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#using-iam-capabilities) in the *IAM User Guide*.

Corresponding UI: Configuration tab/Advanced/**Capabilities**

## parameter-overrides
<a name="deploy.action.cfn.parameter.overrides"></a>

(*DeployCloudFormationStack*/Configuration/**parameter-overrides**)

(Optional)

Specify parameters in your CloudFormation or AWS SAM template that don't have default values, or for which you want to specify non-default values. For more information about parameters, see [Parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html) in the * AWS CloudFormation User Guide*.

The `parameter-overrides` property accepts:
+ A JSON file containing the parameters and values.
+ A comma-separate list of parameters and values.

**To specify a JSON file**

1. Make sure the JSON file uses one of the following syntaxes:

   ```
   {
     "Parameters": {
       "Param1": "Value1",
       "Param2": "Value2",
       ...
     }
   }
   ```

   Or...

   ```
   [
     {
        "ParameterKey": "Param1",
        "ParameterValue": "Value1"
     },
     ...
   ]
   ```

   (There are other syntaxes, but they are not supported by CodeCatalyst at the time of writing.) For more information about specifying CloudFormation parameters in a JSON file, see [Supported JSON syntax](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/deploy/index.html#supported-json-syntax) in the *AWS CLI Command Reference*.

1. Specify the path to the JSON file using one of the following formats:
   + If your JSON file resides in an output artifact from a previous action, use:

     `file:///artifacts/current-action-name/output-artifact-name/path-to-json-file`

     See **Example 1** for details.
   + If your JSON file resides in your source repository, use:

     `file:///sources/WorkflowSource/path-to-json-file`

     See **Example 2** for details.

     **Example 1** – The JSON file resides in an output artifact

     ```
     ##My workflow YAML
     ...
     Actions:
       MyBuildAction:
         Identifier: aws/build@v1
         Outputs:
           Artifacts:
             - Name: ParamArtifact
               Files:
                 - params.json
         Configuration:
         ...
       MyDeployCFNStackAction:
         Identifier: aws/cfn-deploy@v1
         Configuration:
           parameter-overrides: file:///artifacts/MyDeployCFNStackAction/ParamArtifact/params.json
     ```

     **Example 2** – The JSON file resides in your source repository, in a folder called `my/folder`

     ```
     ##My workflow YAML
     ...
     Actions:
       MyDeployCloudFormationStack:
         Identifier: aws/cfn-deploy@v1
         Inputs:
           Sources:
             - WorkflowSource
         Configuration:
           parameter-overrides: file:///sources/WorkflowSource/my/folder/params.json
     ```

**To use a comma-separate list of parameters**
+ Add parameter name-value pairs in the `parameter-overrides` property using the following format:

  `param-1=value-1,param-2=value-2`

  For example, assuming the following CloudFormation template:

  ```
  ##My CloudFormation template
  
  Description: My CloudFormation template
  
  Parameters:
    InstanceType:
      Description: Defines the Amazon EC2 compute for the production server.
      Type: String
      Default: t2.micro
      AllowedValues:
        - t2.micro
        - t2.small
        - t3.medium
      
  Resources:
  ...
  ```

  ...you might set the `parameter-overrides` property as follows:

  ```
  ##My workflow YAML
  ...
  Actions:
  ...
    DeployCloudFormationStack:
      Identifier: aws/cfn-deploy@v1
      Configuration:
        parameter-overrides: InstanceType=t3.medium,UseVPC=true
  ```
**Note**  
You can specify a parameter name without a corresponding value using `undefined` as the value. For example:  
`parameter-overrides: MyParameter=undefined`  
 The effect is that during a stack update, CloudFormation uses the existing parameter value for the given parameter name.

Corresponding UI:
+ Configuration tab/Advanced/**Parameter overrides**
+ Configuration tab/Advanced/Parameter overrides/**Specify overrides using a file**
+ Configuration tab/Advanced/Parameter overrides/**Specify overrides using a value set**

## no-execute-changeset
<a name="deploy.action.cfn.noexecutechangeset"></a>

(*DeployCloudFormationStack*/Configuration/**no-execute-changeset**)

(Optional)

Specify whether you want CodeCatalyst to create the CloudFormation change set and then stop before running it. This gives you the opportunity to review the change set in the CloudFormation console. If you determine that the change set looks good, disable this option and then re-run the workflow so that CodeCatalyst can create and run the change set without stopping. The default is to create and run the change set without stopping. For more information, see the CloudFormation [deploy](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/deploy/index.html) parameter in the *AWS CLI Command Reference*. For more information about viewing change sets, see [Viewing a change set](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-changesets-view.html) in the *AWS CloudFormation User Guide*.

Corresponding UI: Configuration tab/Advanced/**No execute change set**

## fail-on-empty-changeset
<a name="deploy.action.cfn.failonemptychangeset"></a>

(*DeployCloudFormationStack*/Configuration/**fail-on-empty-changeset**)

(Optional)

Specify whether you want CodeCatalyst to fail the **Deploy CloudFormation stack** action if the CloudFormation change set is empty. (If a change set is empty, it means there were no changes made to the stack during the latest deployment.) The default is to allow the action to proceed if the change set is empty, and to return an `UPDATE_COMPLETE` message even though the stack was not updated.

For more information about this setting, see the CloudFormation [deploy](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/deploy/index.html) parameter in the *AWS CLI Command Reference*. For more information about change sets, see [Updating stacks using change sets](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-changesets.html) in the *AWS CloudFormation User Guide*.

Corresponding UI: Configuration tab/Advanced/**Fail on empty changeset**

## disable-rollback
<a name="deploy.action.cfn.disablerollback"></a>

(*DeployCloudFormationStack*/Configuration/**disable-rollback**)

(Optional)

Specify whether you want CodeCatalyst to roll back the stack deployment if it fails. The rollback returns the stack to the last known stable state. The default is to enable rollbacks. For more information about this setting, see the CloudFormation [deploy](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/deploy/index.html) parameter in the *AWS CLI Command Reference*.

For more information about how the **Deploy CloudFormation stack** action handles rollbacks, see [Configuring rollbacks](deploy-consumption-enable-alarms.md).

For more information about rolling back a stack, see [Stack failure options](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stack-failure-options.html) in the *AWS CloudFormation User Guide*.

Corresponding UI: Configuration tab/Advanced/**Disable rollback**

## termination-protection
<a name="deploy.action.cfn.terminationprotection"></a>

(*DeployCloudFormationStack*/Configuration/**termination-protection**)

(Optional)

Specify whether you want the **Deploy CloudFormation stack** to add termination protection to the stack that it is deploying. If a user attempts to delete a stack with termination protection enabled, the deletion fails and the stack, including its status, remains unchanged. The default is to disable termination protection. For more information, see [Protecting a stack from being deleted](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-protect-stacks.html) in the *AWS CloudFormation User Guide*.

Corresponding UI: Configuration tab/Advanced/**Termination protection**

## timeout-in-minutes
<a name="deploy.action.cfn.timeoutinminutes"></a>

(*DeployCloudFormationStack*/Configuration/**timeout-in-minutes**)

(Optional)

Specify the amount of time, in minutes, that CloudFormation should allot before timing out stack creation operations and setting the stack status to `CREATE_FAILED`. If CloudFormation can't create the entire stack in the time allotted, it fails the stack creation due to timeout and rolls back the stack.

By default, there is no timeout for stack creation. However, individual resources may have their own timeouts based on the nature of the service they implement. For example, if an individual resource in your stack times out, stack creation also times out even if the timeout you specified for stack creation hasn't yet been reached.

Corresponding UI: Configuration tab/Advanced/**CloudFormation timeout**

## notification-arns
<a name="deploy.action.cfn.notificationarns"></a>

(*DeployCloudFormationStack*/Configuration/**notification-arns**)

(Optional)

Specify the ARN of an Amazon SNS topic that you want CodeCatalyst to send notification messages to. For example, `arn:aws:sns:us-east-1:111222333:MyTopic`. When the **Deploy CloudFormation stack** action runs, CodeCatalyst coordinates with CloudFormation to send one notification per CloudFormation event that occurs during the stack creation or update process. (The events are visible in the CloudFormation console's **Events** tab for the stack.) You can specify up to five topics. For more information, see [What is Amazon SNS?](https://docs.aws.amazon.com/sns/latest/dg/welcome.html).

Corresponding UI: Configuration tab/Advanced/**Notification ARNs**

## monitor-alarm-arns
<a name="deploy.action.cfn.monitoralarmarns"></a>

(*DeployCloudFormationStack*/Configuration/**monitor-alarm-arns**)

(Optional)

Specify the Amazon Resource Name (ARN) of an Amazon CloudWatch alarm to use as a rollback trigger. For example, `arn:aws:cloudwatch::123456789012:alarm/MyAlarm`. You can have a maximum of five rollback triggers.

**Note**  
If you specify a CloudWatch alarm ARN, you'll also need to configure additional permissions to enable the action to access CloudWatch. For more information, see [Configuring rollbacks](deploy-consumption-enable-alarms.md).

Corresponding UI: Configuration tab/Advanced/**Monitor alarm ARNs **

## monitor-timeout-in-minutes
<a name="deploy.action.cfn.monitortimeinminutes"></a>

(*DeployCloudFormationStack*/Configuration/**monitor-timeout-in-minutes**)

(Optional)

Specify an amount of time, from 0 to 180 minutes, during which CloudFormation monitors the specified alarms. Monitoring begins *after* all the stack resources have been deployed. If the alarm occurs within the specified monitoring time, then the deployment fails, and CloudFormation rolls back the entire stack operation.

Default: 0. CloudFormation only monitors alarms while the stack resources are being deployed, not after.

Corresponding UI: Configuration tab/Advanced/**Monitoring time**

## tags
<a name="deploy.action.cfn.tags"></a>

(*DeployCloudFormationStack*/Configuration/**tags**)

(Optional)

Specify tags to attach to your CloudFormation stack. Tags are arbitrary key-value pairs that you can use to identify your stack for purposes such as cost allocation. For more information about what tags are and how they can be used, see [Tagging your resources](https://docs.aws.amazon.com/) in the *Amazon EC2 User Guide*. For more information about tagging in CloudFormation, see [Setting CloudFormation stack options](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-add-tags.html) in the *AWS CloudFormation User Guide*.

A key can have alphanumeric characters or spaces, and can have up to 127 characters. A value can have alphanumeric characters or spaces, and can have up to 255 characters.

You can add up to 50 unique tags for each stack.

Corresponding UI: Configuration tab/Advanced/**Tags**

# Deploying an AWS CDK app with a workflow
<a name="cdk-dep-action"></a>

This section describes how to deploy an AWS Cloud Development Kit (AWS CDK) app into your AWS account using a workflow. To accomplish this, you must add the **AWS CDK deploy** action to your workflow. The **AWS CDK deploy** action synthesizes and deploys your AWS Cloud Development Kit (AWS CDK) app into AWS. If your app already exists in AWS, the action updates it if necessary. 

For general information about writing apps using the AWS CDK, see [What is the AWS CDK?](https://docs.aws.amazon.com/cdk/v2/guide/home.html) in the *AWS Cloud Development Kit (AWS CDK) Developer Guide*.

**Topics**
+ [When to use the 'AWS CDK deploy' action](#cdk-dep-action-when-to-use)
+ [How the 'AWS CDK deploy' action works](#cdk-dep-action-how-it-works)
+ [CDK CLI versions used by the 'AWS CDK deploy' action](#cdk-dep-action-cdk-version)
+ [Runtime image used by the 'AWS CDK deploy' action](#cdk-dep-action-runtime)
+ [How many stacks can the action deploy?](#cdk-dep-action-how-many-stacks)
+ [Example: Deploying an AWS CDK app](cdk-dep-action-example-workflow.md)
+ [Adding the 'AWS CDK deploy' action](cdk-dep-action-add.md)
+ ['AWS CDK deploy' variables](cdk-dep-action-variables.md)
+ ['AWS CDK deploy' action YAML](cdk-dep-action-ref.md)

## When to use the 'AWS CDK deploy' action
<a name="cdk-dep-action-when-to-use"></a>

Use this action if you have developed an app using the AWS CDK, and you now want to deploy it automatically as part of automated continuous integration and delivery (CI/CD) workflow. For example, you might want to deploy your AWS CDK app automatically whenever someone merges a pull request related to your AWS CDK app source. 

## How the 'AWS CDK deploy' action works
<a name="cdk-dep-action-how-it-works"></a>

The **AWS CDK deploy** works as follows:

1. At runtime, if you specified version 1.0.12 or earlier of the action, the action downloads the latest CDK CLI (also called the AWS CDK Tookit) to the CodeCatalyst [runtime environment image](#cdk-dep-action-runtime).

   If you specified version 1.0.13 or later, the action comes bundled with a [specific version](#cdk-dep-action-cdk-version) of the CDK CLI, so no download occurs.

1. The action uses the CDK CLI to run the `cdk deploy` command. This command synthesizes and deploys your AWS CDK app into AWS. For more information about this command, see the [AWS CDK Toolkit (cdk command)](https://docs.aws.amazon.com/cli/latest/reference/s3/sync.html) topic in the *AWS Cloud Development Kit (AWS CDK) Developer Guide*.

## CDK CLI versions used by the 'AWS CDK deploy' action
<a name="cdk-dep-action-cdk-version"></a>

The following table shows which version of the CDK CLI is used by default by different versions of the **AWS CDK deploy** action.

**Note**  
You might be able to override the default. For more information, see [CdkCliVersion](cdk-dep-action-ref.md#cdk.dep.cdk.cli.version) in the ['AWS CDK deploy' action YAML](cdk-dep-action-ref.md).


| 'AWS CDK deploy' action version | AWS CDK CLI version | 
| --- | --- | 
|  1.0.0 – 1.0.12  |  latest  | 
|  1.0.13 or later  |  2.99.1  | 

## Runtime image used by the 'AWS CDK deploy' action
<a name="cdk-dep-action-runtime"></a>

The following table shows the runtime environment images that CodeCatalyst uses to run different versions of the **AWS CDK deploy** action. The images include different sets of preinstalled tooling. For more information, see [Active images](build-images.md#build-curated-images).

**Note**  
We recommend upgrading your **AWS CDK deploy** action to version 2.x to take advantage of the latest tooling available on the March 2024 image. To upgrade the action, set its `Identifier` property to `aws/cdk-deploy@v2` in your workflow definition file. For more information, see ['AWS CDK deploy' action YAML](cdk-dep-action-ref.md). 


| 'AWS CDK deploy' action version | Runtime environment images | 
| --- | --- | 
|  1.x  |  November 2022 images  | 
|  2.x  |  March 2024 images  | 

## How many stacks can the action deploy?
<a name="cdk-dep-action-how-many-stacks"></a>

The **AWS CDK deploy** can deploy a single stack only. If your AWS CDK app consists of multiple stacks, you must create a parent stack with nested stacks, and deploy the parent using this action.

# Example: Deploying an AWS CDK app
<a name="cdk-dep-action-example-workflow"></a>

The following example workflow includes the **AWS CDK deploy** action, along with the **AWS CDK bootstrap** action. The workflow consists of the following building blocks that run sequentially:
+ A **trigger** – This trigger starts the workflow run automatically when you push a change to your source repository. This repository contains your AWS CDK app. For more information about triggers, see [Starting a workflow run automatically using triggers](workflows-add-trigger.md).
+ An **AWS CDK bootstrap** action (`CDKBootstrap`) – On trigger, the action deploys the `CDKToolkit` bootstrap stack into AWS. If the `CDKToolkit` stack already exists in the environment, it will be upgraded if necessary; otherwise, nothing happens, and the action is marked as succeeded.
+ An **AWS CDK deploy** action (`AWS CDKDeploy`) – On completion of the **AWS CDK bootstrap** action, the **AWS CDK deploy** action synthesizes your AWS CDK app code into an CloudFormation template and deploys the stack defined in the template into AWS.

**Note**  
The following workflow example is for illustrative purposes, and will not work without additional configuration.

**Note**  
In the YAML code that follows, you can omit the `Connections:` sections if you want. If you omit these sections, you must ensure that the role specified in the **Default IAM role** field in your environment includes the permissions and trust policies required by the **AWS CDK bootstrap** and **AWS CDK deploy** actions. For more information about setting up an environment with a default IAM role, see [Creating an environment](deploy-environments-creating-environment.md). For more information about the permissions and trust policies required by the **AWS CDK bootstrap** and **AWS CDK deploy** actions, see the description of the `Role` property in the ['AWS CDK bootstrap' action YAML](cdk-boot-action-ref.md) and ['AWS CDK deploy' action YAML](cdk-dep-action-ref.md).

```
Name: codecatalyst-cdk-deploy-workflow
SchemaVersion: 1.0

Triggers:
  - Type: PUSH
    Branches:
      - main
Actions:
  CDKBootstrap:
    Identifier: aws/cdk-bootstrap@v2
    Inputs:
      Sources:
        - WorkflowSource
    Environment:
      Name: codecatalyst-cdk-deploy-environment
      Connections:
        - Name: codecatalyst-account-connection
          Role: codecatalyst-cdk-bootstrap-role
    Configuration:
      Region: us-west-2
        
  CDKDeploy:
    Identifier: aws/cdk-deploy@v2
    DependsOn: 
      - CDKBootstrap
    Environment:
      Name: codecatalyst-cdk-deploy-environment
      Connections:
        - Name: codecatalyst-account-connection
          Role: codecatalyst-cdk-deploy-role
    Inputs:
      Sources:
        - WorkflowSource
    Configuration:
      StackName: my-app-stack
      Region: us-west-2
```

# Adding the 'AWS CDK deploy' action
<a name="cdk-dep-action-add"></a>

 Use the following instructions to add the **AWS CDK deploy** action to your workflow. 

**Before you begin**

Before you can add the **AWS CDK deploy** action to your workflow, complete the following tasks:

1. **Have an AWS CDK app ready**. You can write your AWS CDK app using AWS CDK v1 or v2, in any programming language supported by the AWS CDK. Make sure your AWS CDK app files are available in:
   + A CodeCatalyst [source repository](source.md), or 
   + A CodeCatalyst [output artifact](workflows-working-artifacts.md) generated by another workflow action

1. **Bootstrap your AWS environment**. To bootstrap, you can:
   + Use one of the methods described in [How to bootstrap](https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html#bootstrapping-howto) in the *AWS Cloud Development Kit (AWS CDK) Developer Guide*.
   + Use the **AWS CDK bootstrap** action. You can add this action in the same workflow as your **AWS CDK deploy**, or in a different one. Just make sure the bootstrap action runs at least once prior to running the **AWS CDK deploy** action so that the necessary resources are in place. For more information about the**AWS CDK bootstrap** action, see [Bootstrapping an AWS CDK app with a workflow](cdk-boot-action.md).

     For more information about bootstrapping, see [Bootstrapping](https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html) in the *AWS Cloud Development Kit (AWS CDK) Developer Guide*.

------
#### [ Visual ]

**To add the 'AWS CDK deploy' action using the visual editor**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

1. Choose the name of your workflow. You can filter by the source repository or branch name where the workflow is defined, or filter by workflow name or status.

1. Choose **Edit**.

1. Choose **Visual**.

1. At the top-left, choose **\$1 Actions** to open the action catalog.

1. From the drop-down list, choose **Amazon CodeCatalyst**.

1. Search for the **AWS CDK deploy** action, and do one of the following:
   + Choose the plus sign (**\$1**) to add the action to the workflow diagram and open its configuration pane.

     Or
   + Choose **AWS CDK deploy**. The action details dialog box appears. On this dialog box:
     + (Optional) Choose **Download** to [view the action's source code](workflows-view-source.md#workflows-view-source.title).
     + Choose **Add to workflow** to add the action to the workflow diagram and open its configuration pane.

1. In the **Inputs** and **Configuration** tabs, complete the fields according to your needs. For a description of each field, see the ['AWS CDK deploy' action YAML](cdk-dep-action-ref.md). This reference provides detailed information about each field (and corresponding YAML property value) as it appears in both the YAML and visual editors.

1. (Optional) Choose **Validate** to validate the workflow's YAML code before committing.

1. Choose **Commit**, enter a commit message, and then choose **Commit** again.
**Note**  
If your **AWS CDK deploy** action fails with an `npm install` error, see [How do I fix "npm install" errors?](troubleshooting-workflows.md#troubleshooting-workflows-npm) for information about how to fix the error.

------
#### [ YAML ]

**To add the 'AWS CDK deploy' action using the YAML editor**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

1. Choose the name of your workflow. You can filter by the source repository or branch name where the workflow is defined, or filter by workflow name or status.

1. Choose **Edit**.

1. Choose **YAML**.

1. At the top-left, choose **\$1 Actions** to open the action catalog.

1. From the drop-down list, choose **Amazon CodeCatalyst**.

1. Search for the **AWS CDK deploy** action, and do one of the following:
   + Choose the plus sign (**\$1**) to add the action to the workflow diagram and open its configuration pane.

     Or
   + Choose **AWS CDK deploy**. The action details dialog box appears. On this dialog box:
     + (Optional) Choose **Download** to [view the action's source code](workflows-view-source.md#workflows-view-source.title).
     + Choose **Add to workflow** to add the action to the workflow diagram and open its configuration pane.

1. Modify the properties in the YAML code according to your needs. An explanation of each available property is provided in the ['AWS CDK deploy' action YAML](cdk-dep-action-ref.md).

1. (Optional) Choose **Validate** to validate the workflow's YAML code before committing.

1. Choose **Commit**, enter a commit message, and then choose **Commit** again.
**Note**  
If your **AWS CDK deploy** action fails with an `npm install` error, see [How do I fix "npm install" errors?](troubleshooting-workflows.md#troubleshooting-workflows-npm) for information about how to fix the error.

------

# 'AWS CDK deploy' variables
<a name="cdk-dep-action-variables"></a>

The **AWS CDK deploy** action produces and sets the following variables at run time. These are known as *predefined variables*.

For information about referencing these variables in a workflow, see [Using predefined variables](workflows-using-predefined-variables.md).


| Key | Value | 
| --- | --- | 
|  stack-id  |  The Amazon Resource Name (ARN) of the AWS CDK application stack that was deployed to during the workflow run. Example: `arn:aws:cloudformation:us-west-2:111122223333:stack/codecatalyst-cdk-app-stack/6aad4380-100a-11ec-a10a-03b8a84d40df`  | 
|  deployment-platform  |  The name of the deployment platform. Hardcoded to `AWS:CloudFormation`.  | 
|  region  |  The region code of the AWS Region that was deployed to during the workflow run. Example: `us-west-2`  | 
|  SKIP-DEPLOYMENT  |  A value of `true` indicates that deployment of your AWS CDK application stack was skipped during the workflow run. A stack deployment will be skipped if there is no change in the stack since the last deployment. This variable is only produced if its value is `true`. Hardcoded to `true`.  | 
|  *CloudFormation variables*  |  In addition to generating the variables listed previously, the **AWS CDK deploy** action also exposes *CloudFormation* output variables as *workflow* variables for use in subsequent workflow actions. By default, the action only exposes the first four (or fewer) CloudFormation variables that it finds. To determine which ones are exposed, run the **AWS CDK deploy** action once, and then look in the **Variables** tab of the run details page. If the variables listed on the **Variables** tab are not what you want, you can configure different ones using the `CfnOutputVariables` YAML property. For more information, see the [CfnOutputVariables](cdk-dep-action-ref.md#cdk.dep.cfn.out) property description in the ['AWS CDK deploy' action YAML](cdk-dep-action-ref.md).  | 

# 'AWS CDK deploy' action YAML
<a name="cdk-dep-action-ref"></a>

The following is the YAML definition of the **AWS CDK deploy** action. To learn how to use this action, see [Deploying an AWS CDK app with a workflow](cdk-dep-action.md).

This action definition exists as a section within a broader workflow definition file. For more information about this file, see [Workflow YAML definition](workflow-reference.md).

**Note**  
Most of the YAML properties that follow have corresponding UI elements in the visual editor. To look up a UI element, use **Ctrl\$1F**. The element will be listed with its associated YAML property.

```
# The workflow definition starts here.
# See Top-level properties for details.
        
Name: MyWorkflow
SchemaVersion: 1.0 
Actions:

# The action definition starts here.   
  CDKDeploy\$1nn: 
    Identifier: aws/cdk-deploy@v2
    DependsOn:
      - CDKBootstrap
    Compute:  
      Type: EC2 | Lambda
      Fleet: fleet-name
    Timeout: timeout-minutes
    Inputs:
      # Specify a source or an artifact, but not both.
      Sources:
        - source-name-1
      Artifacts:
        - artifact-name
    Outputs:
      Artifacts:
        - Name: cdk_artifact
          Files: 
            - "cdk.out/**/*"
    Environment:
      Name: environment-name
      Connections:
        - Name: account-connection-name
          Role: iam-role-name
    Configuration:
      StackName: my-cdk-stack
      Region: us-west-2
      Tags: '{"key1": "value1", "key2": "value2"}'
      Context: '{"key1": "value1", "key2": "value2"}'
      CdkCliVersion: version
      CdkRootPath: directory-containing-cdk.json-file
      CfnOutputVariables: '["CnfOutputKey1","CfnOutputKey2","CfnOutputKey3"]'
      CloudAssemblyRootPath: path-to-cdk.out
```

## CDKDeploy
<a name="cdk.dep.name"></a>

(Required)

Specify the name of the action. All action names must be unique within the workflow. Action names are limited to alphanumeric characters (a-z, A-Z, 0-9), hyphens (-), and underscores (\$1). Spaces are not allowed. You cannot use quotation marks to enable special characters and spaces in action names.

Default: `CDKDeploy_nn`.

Corresponding UI: Configuration tab/**Action name**

## Identifier
<a name="cdk.dep.identifier"></a>

(*CDKDeploy*/**Identifier**)

(Required)

Identifies the action. Do not change this property unless you want to change the version. For more information, see [Specifying the action version to use](workflows-action-versions.md).

**Note**  
Specifying `aws/cdk-deploy@v2` causes the action to run on the [March 2024 image](build-images.md#build.default-image) which includes newer tooling such as Node.js 18. Specifying `aws/cdk-deploy@v1` causes the action to run on the [November 2022 image](build-images.md#build.previous-image) which includes older tooling such as Node.js 16.

Default: `aws/cdk-deploy@v2`.

Corresponding UI: Workflow diagram/CDKDeploy\$1nn/**aws/cdk-deploy@v2** label

## DependsOn
<a name="cdk.dep.dependson"></a>

(*CDKDeploy*/**DependsOn**)

(Optional)

Specify an action or action group that must run successfully in order for the **AWS CDK deploy** action to run. We recommend specifying the **AWS CDK bootstrap** action in the `DependsOn` property, like this:

```
CDKDeploy:
  Identifier: aws/cdk-deploy@v2
  DependsOn:
    - CDKBootstrap
```

**Note**  
[Bootstrapping](https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html) is a mandatory prerequisite for deploying an AWS CDK app. If you do not include the **AWS CDK Bootstrap** action in your workflow, then you must find another way to deploy the AWS CDK bootstrap stack before running your **AWS CDK deploy** action. For more information, see [Adding the 'AWS CDK deploy' action](cdk-dep-action-add.md) in [Deploying an AWS CDK app with a workflow](cdk-dep-action.md).

For more information about the 'depends on' functionality, see [Sequencing actions](workflows-depends-on.md).

Corresponding UI: Inputs tab/**Depends on - optional**

## Compute
<a name="cdk.dep.computename"></a>

(*CDKDeploy*/**Compute**)

(Optional)

The computing engine used to run your workflow actions. You can specify compute either at the workflow level or at the action level, but not both. When specified at the workflow level, the compute configuration applies to all actions defined in the workflow. At the workflow level, you can also run multiple actions on the same instance. For more information, see [Sharing compute across actions](compute-sharing.md).

Corresponding UI: *none*

## Type
<a name="cdk.dep.computetype"></a>

(*CDKDeploy*/Compute/**Type**)

(Required if [Compute](#cdk.dep.computename) is included)

The type of compute engine. You can use one of the following values:
+ **EC2** (visual editor) or `EC2` (YAML editor)

  Optimized for flexibility during action runs.
+ **Lambda** (visual editor) or `Lambda` (YAML editor)

  Optimized action start-up speeds.

For more information about compute types, see [Compute types](workflows-working-compute.md#compute.types).

Corresponding UI: Configuration tab/Advanced - optional/**Compute type**

## Fleet
<a name="cdk.dep.computefleet"></a>

(*CDKDeploy*/Compute/**Fleet**)

(Optional)

Specify the machine or fleet that will run your workflow or workflow actions. With on-demand fleets, when an action starts, the workflow provisions the resources it needs, and the machines are destroyed when the action finishes. Examples of on-demand fleets: `Linux.x86-64.Large`, `Linux.x86-64.XLarge`. For more information about on-demand fleets, see [On-demand fleet properties](workflows-working-compute.md#compute.on-demand).

With provisioned fleets, you configure a set of dedicated machines to run your workflow actions. These machines remain idle, ready to process actions immediately. For more information about provisioned fleets, see [Provisioned fleet properties](workflows-working-compute.md#compute.provisioned-fleets).

If `Fleet` is omitted, the default is `Linux.x86-64.Large`.

Corresponding UI: Configuration tab/Advanced - optional/**Compute fleet**

## Timeout
<a name="cdk.dep.timeout"></a>

(*CDKDeploy*/**Timeout**)

(Required)

Specify the amount of time in minutes (YAML editor), or hours and minutes (visual editor), that the action can run before CodeCatalyst ends the action. The minimum is 5 minutes and the maximum is described in [Quotas for workflows in CodeCatalyst](workflows-quotas.md). The default timeout is the same as the maximum timeout.

Corresponding UI: Configuration tab/**Timeout - optional **

## Inputs
<a name="cdk.dep.inputs"></a>

(*CDKDeploy*/**Inputs**)

(Optional)

The `Inputs` section defines the data that the `CDKDeploy` needs during a workflow run.

**Note**  
Only one input (either a source or an artifact) is allowed for each **AWS CDK deploy** action.

Corresponding UI: **Inputs** tab

## Sources
<a name="cdk.dep.inputs.sources"></a>

(*CDKDeploy*/Inputs/**Sources**)

(Required if the AWS CDK app you want to deploy is stored in a source repository)

If your AWS CDK app is stored in a source repository, specify the label of that source repository. The **AWS CDK deploy** action synthesizes the app in this repository before starting the deployment process. Currently, the only supported label is `WorkflowSource`.

If your AWS CDK app is not contained within a source repository, it must reside in an artifact generated by another action.

For more information about sources, see [Connecting source repositories to workflows](workflows-sources.md).

Corresponding UI: Inputs tab/**Sources - optional**

## Artifacts - input
<a name="cdk.dep.inputs.artifacts"></a>

(*CDKDeploy*/Inputs/**Artifacts**)

(Required if the AWS CDK app you want to deploy is stored in an [output artifact](workflows-working-artifacts-output.md) from a previous action)

If your AWS CDK app is contained in an artifact generated by a previous action, specify that artifact here. The **AWS CDK deploy** action synthesizes the app in the specified artifact into a CloudFormation template before starting the deployment process. If your AWS CDK app is not contained within an artifact, it must reside in your source repository.

For more information about artifacts, including examples, see [Sharing artifacts and files between actions](workflows-working-artifacts.md).

Corresponding UI: Inputs tab/**Artifacts - optional**

## Outputs
<a name="cdk.dep.outputs"></a>

(*CDKDeploy*/**Outputs**)

(Optional)

Defines the data that is output by the action during a workflow run.

Corresponding UI: **Outputs** tab

## Artifacts - output
<a name="cdk.dep.outputs.artifacts"></a>

(*CDKDeploy*/Outputs/**Artifacts**

(Optional)

Specify the artifacts generated by the action. You can reference these artifacts as input in other actions.

For more information about artifacts, including examples, see [Sharing artifacts and files between actions](workflows-working-artifacts.md).

Corresponding UI: Outputs tab/**Artifacts**

## Name
<a name="cdk.dep.outputs.artifacts.name"></a>

(*CDKDeploy*/Outputs/Artifacts/**Name**)

(Required if [Artifacts - output](#cdk.dep.outputs.artifacts) is included)

Specify the name of the artifact that will contain the CloudFormation template that is synthesized by the **AWS CDK deploy** action at runtime. The default value is `cdk_artifact`. If you do not specify an artifact, then the action synthesizes the template but won't save it in an artifact. Consider saving the synthesized template in an artifact to preserve a record of it for testing or troubleshooting purposes.

Corresponding UI: Outputs tab/Artifacts/Add artifact/**Build artifact name**

## Files
<a name="cdk.dep.outputs.artifacts.files"></a>

(*CDKDeploy*/Outputs/Artifacts/**Files**)

(Required if [Artifacts - output](#cdk.dep.outputs.artifacts) is included)

Specify the files to include in the artifact. You must specify `"cdk.out/**/*"` to include your AWS CDK app's synthesized CloudFormation template.

**Note**  
`cdk.out` is the default directory into which synthesized files are saved. If you specified an output directory other than `cdk.out` in your `cdk.json` file, specify that directory here instead of `cdk.out`.

Corresponding UI: Outputs tab/Artifacts/Add artifact/**Files produced by build**

## Environment
<a name="cdk.dep.environment"></a>

(*CDKDeploy*/**Environment**)

(Required)

Specify the CodeCatalyst environment to use with the action. The action connects to the AWS account and optional Amazon VPC specified in the chosen environment. The action uses the default IAM role specified in the environment to connect to the AWS account, and uses the IAM role specified in the [Amazon VPC connection](https://docs.aws.amazon.com/codecatalyst/latest/adminguide/managing-vpcs.add.html) to connect to the Amazon VPC.

**Note**  
If the default IAM role does not have the permissions required by the action, you can configure the action to use a different role. For more information, see [Changing the IAM role of an action](deploy-environments-switch-role.md).

For more information about environments, see [Deploying into AWS accounts and VPCs](deploy-environments.md) and [Creating an environment](deploy-environments-creating-environment.md).

Corresponding UI: Configuration tab/**Environment**

## Name
<a name="cdk.dep.environment.name"></a>

(*CDKDeploy*/Environment/**Name**)

(Required if [Environment](#cdk.dep.environment) is included)

Specify the name of an existing environment that you want to associate with the action.

Corresponding UI: Configuration tab/**Environment**

## Connections
<a name="cdk.dep.environment.connections"></a>

(*CDKDeploy*/Environment/**Connections**)

(Optional in newer versions of the action; required in older versions)

Specify the account connection to associate with the action. You can specify a maximum of one account connection under `Environment`.

If you do not specify an account connection:
+ The action uses the AWS account connection and default IAM role specified in the environment in the CodeCatalyst console. For information about adding an account connection and default IAM role to environment, see [Creating an environment](deploy-environments-creating-environment.md).
+ The default IAM role must include the policies and permissions required by the action. To determine what those policies and permissions are, see the description of the **Role** property in the action's YAML definition documentation.

For more information about account connections, see [Allowing access to AWS resources with connected AWS accounts](ipa-connect-account.md). For information about adding an account connection to an environment, see [Creating an environment](deploy-environments-creating-environment.md).

Corresponding UI: One of the following depending on the action version:
+ (Newer versions) Configuration tab/Environment/What's in *my-environment*?/three dot menu/**Switch role**
+ (Older versions) Configuration tab/'Environment/account/role'/**AWS account connection**

## Name
<a name="cdk.dep.environment.connections.name"></a>

(*CDKDeploy*/Environment/Connections/**Name**)

(Required if [Connections](#cdk.dep.environment.connections) is included)

Specify the name of the account connection.

Corresponding UI: One of the following depending on the action version:
+ (Newer versions) Configuration tab/Environment/What's in *my-environment*?/three dot menu/**Switch role**
+ (Older versions) Configuration tab/'Environment/account/role'/**AWS account connection**

## Role
<a name="cdk.dep.environment.connections.role"></a>

(*CDKDeploy*/Environment/Connections/**Role**)

(Required if [Connections](#cdk.dep.environment.connections) is included)

Specify the name of the account connection.

Specify the name of the IAM role that the **AWS CDK deploy** action uses to access AWS and deploy the AWS CDK application stack. Make sure that you have [added the role to your CodeCatalyst space](ipa-connect-account-addroles.md), and that the role includes the following policies.

If you do not specify an IAM role, then the action uses the default IAM role listed in the [environment](deploy-environments.md) in the CodeCatalyst console. If you use the default role in the environment, make sure it has the following policies.
+ The following permissions policy:
**Warning**  
Limit the permissions to those shown in the following policy. Using a role with broader permissions might pose a security risk.

------
#### [ JSON ]

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Statement": [
          {
              "Sid": "VisualEditor0",
              "Effect": "Allow",
              "Action": [
                  "cloudformation:DescribeStackEvents",
                  "cloudformation:DescribeChangeSet",
                  "cloudformation:DescribeStacks",
                  "cloudformation:ListStackResources"
              ],
              "Resource": "*"
          },
          {
              "Sid": "VisualEditor1",
              "Effect": "Allow",
              "Action": "sts:AssumeRole",
              "Resource": "arn:aws:iam::111122223333:role/cdk-*"
          }
      ]
  }
  ```

------
+ The following custom trust policy:

**Note**  
You can use the `CodeCatalystWorkflowDevelopmentRole-spaceName` role with this action, if you'd like. For more information about this role, see [Creating the **CodeCatalystWorkflowDevelopmentRole-*spaceName*** role for your account and space](ipa-iam-roles.md#ipa-iam-roles-service-create). Understand that the `CodeCatalystWorkflowDevelopmentRole-spaceName` role has full access permissions which may pose a security risk. We recommend that you only use this role in tutorials and scenarios where security is less of a concern. 

Corresponding UI: One of the following depending on the action version:
+ (Newer versions) Configuration tab/Environment/What's in *my-environment*?/three dot menu/**Switch role**
+ (Older versions) Configuration tab/'Environment/account/role'/**Role**

## Configuration
<a name="cdk.dep.configuration"></a>

(*CDKDeploy*/**Configuration**)

(Required)

A section where you can define the configuration properties of the action.

Corresponding UI: **Configuration** tab

## StackName
<a name="cdk.dep.stack.name"></a>

(*CDKDeploy*/Configuration/**StackName**)

(Required)

The name of your AWS CDK app stack, as it appears in the entrypoint file in your AWS CDK app's `bin` directory. The following example shows the contents of a TypeScript entrypoint file, with the stack name highlighted in *red italics*. If your entrypoint file is in a different language, it will look similar.

```
import * as cdk from 'aws-cdk-lib';
import { CdkWorksopTypescriptStack } from '../lib/cdk_workshop_typescript-stack';

const app = new cdk.App();
new CdkWorkshopTypescriptStack(app, 'CdkWorkshopTypescriptStack');
```

You can only specify one stack.

**Tip**  
If you have multiple stacks, you can create a parent stack with nested stacks. You can then specify the parent stack in this action to deploy all stacks.

Corresponding UI: Configuration tab/**Stack name**

## Region
<a name="cdk.dep.region"></a>

(*CDKDeploy*/Configuration/**Region**)

(Optional)

Specify the AWS Region into which the AWS CDK application stack will be deployed. For a list of Region codes, see [Regional endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html#region-names-codes).

If you do not specify a Region, the **AWS CDK deploy** action deploys into the Region specified in your AWS CDK code. For more information, see [Environments](https://docs.aws.amazon.com/cdk/v2/guide/environments.html) in the *AWS Cloud Development Kit (AWS CDK) Developer Guide*.

Corresponding UI: Configuration tab/**Region**

## Tags
<a name="cdk.dep.tags"></a>

(*CDKDeploy*/Configuration/**Tags**)

(Optional)

Specify tags that you want to apply to the AWS resources in the AWS CDK application stack. Tags are applied to the stack itself as well as to individual resources in the stack. For more information about tagging, see [Tagging](https://docs.aws.amazon.com/cdk/v2/guide/tagging.html) in the *AWS Cloud Development Kit (AWS CDK) Developer Guide*.

Corresponding UI: Configuration tab/Advanced - optional/**Tags**

## Context
<a name="cdk.dep.context"></a>

(*CDKDeploy*/Configuration/**Context**)

(Optional)

Specify contexts, in the form of key-value pairs, to associate with the AWS CDK application stack. For more information about contexts, see [Runtime contexts](https://docs.aws.amazon.com/cdk/v2/guide/context.html) in the *AWS Cloud Development Kit (AWS CDK) Developer Guide*.

Corresponding UI: Configuration tab/Advanced - optional/**Context**

## CdkCliVersion
<a name="cdk.dep.cdk.cli.version"></a>

(*CDKDeploy*/Configuration/**CdkCliVersion**)

(Optional)

This property is available with version 1.0.13 or later of the **AWS CDK deploy** action, and version 1.0.8 or later of the **AWS CDK bootstrap** action.

Specify one of the following:
+ The full version of the AWS Cloud Development Kit (AWS CDK) Command Line Interface (CLI) (also called the AWS CDK Toolkit) that you want this action to use. Example: `2.102.1`. Consider specifying a full version to ensure consistency and stability when building and deploying your application.

  Or
+ `latest`. Consider specifying `latest` to take advantage of the latest features and fixes of the CDK CLI.

The action will download the specified version (or the latest version) of the AWS CDK CLI to the CodeCatalyst [build image](build-images.md), and then use this version to run the commands necessary to deploy your CDK application or bootstrap your AWS environment.

For a list of supported CDK CLI versions you can use, see [AWS CDK Versions](https://docs.aws.amazon.com/cdk/api/versions.html).

If you omit this property, the action uses a default AWS CDK CLI version described in one of the following topics:
+ [CDK CLI versions used by the 'AWS CDK deploy' action](cdk-dep-action.md#cdk-dep-action-cdk-version) 
+ [CDK CLI versions used by the "AWS CDK bootstrap" action](cdk-boot-action.md#cdk-boot-action-cdk-version)

Corresponding UI: Configuration tab/**AWS CDK CLI version**

## CdkRootPath
<a name="cdk.dep.cdk.root.path"></a>

(*CDKDeploy*/Configuration/**CdkRootPath**)

(Optional)

The path to the directory that contains your AWS CDK project's `cdk.json` file. The **AWS CDK deploy** action runs from this folder, and any outputs created by the action will be added to this directory. If unspecified, the **AWS CDK deploy** action assumes that the `cdk.json` file is in the root of your AWS CDK project.

Corresponding UI: Configuration tab/**Directory where the cdk.json resides**

## CfnOutputVariables
<a name="cdk.dep.cfn.out"></a>

(*CDKDeploy*/Configuration/**CfnOutputVariables**)

(Optional)

Specify which `CfnOutput` constructs in your AWS CDK application code you want to expose as workflow output variables. You can then reference the workflow output variables in subsequent actions in your workflow. For more information about variables in CodeCatalyst, see [Using variables in workflows](workflows-working-with-variables.md).

For example, if your AWS CDK application code looks like this:

```
import { Duration, Stack, StackProps, CfnOutput, RemovalPolicy} from 'aws-cdk-lib';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
import * as s3 from 'aws-cdk-lib/aws-s3';
import { Construct } from 'constructs';
import * as cdk from 'aws-cdk-lib';
export class HelloCdkStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);
    const bucket = new s3.Bucket(this, 'amzn-s3-demo-bucket', {
      removalPolicy: RemovalPolicy.DESTROY,
    });
    new CfnOutput(this, 'bucketName', {
      value: bucket.bucketName,
      description: 'The name of the s3 bucket',
      exportName: 'amzn-s3-demo-bucket',
    });
    const table = new dynamodb.Table(this, 'todos-table', {
      partitionKey: {name: 'todoId', type: dynamodb.AttributeType.NUMBER},
      billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
      removalPolicy: RemovalPolicy.DESTROY,
    })
    new CfnOutput(this, 'tableName', {
      value: table.tableName,
      description: 'The name of the dynamodb table',
      exportName: 'myDynamoDbTable',
    });
    ...
  }
}
```

...and your `CfnOutputVariables` property looks like this:

```
Configuration:
  ...
  CfnOutputVariables: '["bucketName","tableName"]'
```

...then the action generates the following workflow output variables:


| Key | Value | 
| --- | --- | 
|  bucketName  |  `bucket.bucketName`  | 
|  tableName  |  `table.tableName`  | 

You can then reference the `bucketName` and `tableName` variables in subsequent actions. To learn how to reference workflow output variables in subsequent actions, see [Referencing a predefined variable](workflows-working-with-variables-reference-output-vars.md).

If you do not specify any `CfnOutput` constructs in the `CfnOutputVariables` property, then the action exposes the first four (or fewer) CloudFormation output variables it finds as workflow output variables. For more information, see ['AWS CDK deploy' variables](cdk-dep-action-variables.md).

**Tip**  
To obtain a list of all the CloudFormation output variables the action produces, run the workflow containing the **AWS CDK deploy** action once, and then look in the action's **Logs** tab. The logs contain a list of all the CloudFormation output variables associated with your AWS CDK app. Once you know what all the CloudFormation variables are, you can specify which ones you want to convert to workflow output variables using the `CfnOutputVariables` property.

For more information about CloudFormation output variables, see the documentation for the `CfnOutput` construct, available at [class CfnOutput (construct)](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnOutput.html) in the *AWS Cloud Development Kit (AWS CDK) API Reference*.

Corresponding UI: Configuration tab/**CloudFormation output variables**

## CloudAssemblyRootPath
<a name="cdk.dep.cloud"></a>

(*CDKDeploy*/Configuration/**CloudAssemblyRootPath**)

(Optional)

If you have already synthesized your AWS CDK app's stack into a cloud assembly (using the `cdk synth` operation), specify the root path of the cloud assembly directory (`cdk.out`). The CloudFormation template located in the specified cloud assembly directory will be deployed by the **AWS CDK deploy** action into your AWS account using the `cdk deploy --app` command. When the `--app` option is present, the `cdk synth` operation does not occur.

If you do not specify a cloud assembly directory, then the **AWS CDK deploy** action will run the `cdk deploy` command without the `--app` option. Without the `--app` option, the `cdk deploy` operation will both synthesize (`cdk synth`) and deploy your AWS CDK app into your AWS account. 

**Why would I specify an existing, synthesized cloud assembly when the "AWS CDK deploy" action can do the synthesis at run time?**

You might want to specify an existing, synthesized cloud assembly to:
+ **Ensure that the exact same set of resources are deployed every time the "AWS CDK deploy" action runs**

  If you don't specify a cloud assembly, it's possible for the **AWS CDK deploy** action to synthesize and deploy different files depending on when it is run. For example, the **AWS CDK deploy** action might synthesize a cloud assembly with one set of dependencies during a testing stage, and another set of dependencies during a production stage (if those dependencies changed between stages). To guarantee exact parity between what is tested and what is deployed, we recommend synthesizing once and then using the **Path to cloud assembly directory** field (visual editor) or `CloudAssemblyRootPath` property (YAML editor) to specify the already-synthesized cloud assembly.
+ **Use non-standard package managers and tooling with the AWS CDK app**

  During a `synth` operation, the **AWS CDK deploy** action tries to run your app using standard tools such as npm or pip. If the action can't successfully run your app using those tools, the synthesis will not occur and the action will fail. To work around this issue, you can specify the exact commands needed to run your app successfully in the AWS CDK app's `cdk.json` file, and then synthesize your app using a method that does not involve the **AWS CDK deploy** action. After the cloud assembly has been generated, you can specify it in the **Path to cloud assembly directory** field (visual editor) or `CloudAssemblyRootPath` property (YAML editor) of the **AWS CDK deploy** action. 

For information about configuring the `cdk.json` file to include commands for installing and running your AWS CDK app, see [Specifying the app command](https://docs.aws.amazon.com/cdk/v2/guide/cli.html#cli-app-command).

For information about the `cdk deploy` and `cdk synth` commands, as well as the `--app` option, see [Deploying stacks](https://docs.aws.amazon.com/cdk/v2/guide/cli.html#cli-deploy), [Synthesizing stacks](https://docs.aws.amazon.com/cdk/v2/guide/cli.html#cli-synth) and [Skipping synthesis](https://docs.aws.amazon.com/cdk/v2/guide/cli.html#cli-deploy-nosynth) in the *AWS Cloud Development Kit (AWS CDK) Developer Guide*.

For information about cloud assemblies, see [Cloud Assembly](https://docs.aws.amazon.com/cdk/api/v2/docs/cloud-assembly-schema-readme.html) in the *AWS Cloud Development Kit (AWS CDK) API Reference*.

Corresponding UI: Configuration tab/**Path to cloud assembly directory**

# Bootstrapping an AWS CDK app with a workflow
<a name="cdk-boot-action"></a>

This section describes how to bootstrap an AWS CDK application using a CodeCatalyst workflow. To accomplish this, you must add the **AWS CDK bootstrap** action to your workflow. The **AWS CDK bootstrap** action provisions a bootstrap stack in your AWS environment using the [modern template](https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html#bootstrapping-template). If a bootstrap stack already exists, the action updates it if necessary. Having a bootstrap stack present in AWS is a prerequisite for deploying an AWS CDK app.

For more information about bootstrapping, see [Bootstrapping](https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html) in the *AWS Cloud Development Kit (AWS CDK) Developer Guide*.

**Topics**
+ [When to use the 'AWS CDK bootstrap' action](#cdk-boot-action-when-to-use)
+ [How the 'AWS CDK bootstrap' action works](#cdk-boot-action-how-it-works)
+ [CDK CLI versions used by the "AWS CDK bootstrap" action](#cdk-boot-action-cdk-version)
+ [Runtime image used by the 'AWS CDK bootstrap' action](#cdk-boot-action-runtime)
+ [Example: Bootstrapping an AWS CDK app](cdk-boot-action-example-workflow.md)
+ [Adding the 'AWS CDK bootstrap' action](cdk-boot-action-add.md)
+ ['AWS CDK bootstrap' variables](cdk-boot-action-variables.md)
+ ['AWS CDK bootstrap' action YAML](cdk-boot-action-ref.md)

## When to use the 'AWS CDK bootstrap' action
<a name="cdk-boot-action-when-to-use"></a>

Use this action if you have a workflow that deploys an AWS CDK app, and you want to deploy (and update, if needed) the bootstrap stack at the same time. In this case, you would add the **AWS CDK bootstrap** action to the same workflow as the one that deploys your AWS CDK app.

**Do not** use this action if either of the following applies:
+ You already deployed a bootstrap stack using another mechanism, and you want to keep it intact (no updates).
+ You want to use a [custom bootstrap template](https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html#bootstrapping-customizing), which is not supported with the **AWS CDK bootstrap** action.

## How the 'AWS CDK bootstrap' action works
<a name="cdk-boot-action-how-it-works"></a>

The **AWS CDK bootstrap** works as follows:

1. At runtime, if you specified version 1.0.7 or earlier of the action, the action downloads the latest CDK CLI (also called the AWS CDK Tookit) to the CodeCatalyst [build image](build-images.md).

   If you specified version 1.0.8 or later, the action comes bundled with a [specific version](cdk-dep-action.md#cdk-dep-action-cdk-version) of the CDK CLI, so no download occurs.

1. The action uses the CDK CLI to run the `cdk bootstrap` command. This command performs the bootstrapping tasks described in the [Bootstrapping](https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html) topic in the *AWS Cloud Development Kit (AWS CDK) Developer Guide*.

## CDK CLI versions used by the "AWS CDK bootstrap" action
<a name="cdk-boot-action-cdk-version"></a>

The following table shows which version of the CDK CLI is used by default by different versions of the **AWS CDK bootstrap** action.

**Note**  
You might be able to override the default. For more information, see [CdkCliVersion](cdk-boot-action-ref.md#cdk.boot.cdk.cli.version) in the ['AWS CDK bootstrap' action YAML](cdk-boot-action-ref.md).


| 'AWS CDK bootstrap' action version | AWS CDK CLI version | 
| --- | --- | 
|  1.0.0 – 1.0.7  |  latest  | 
|  1.0.8 or later  |  2.99.1  | 

## Runtime image used by the 'AWS CDK bootstrap' action
<a name="cdk-boot-action-runtime"></a>

The following table shows the runtime environment images that CodeCatalyst uses to run different versions of the **AWS CDK bootstrap** action. The images include different sets of preinstalled tooling. For more information, see [Active images](build-images.md#build-curated-images).

**Note**  
We recommend upgrading your **AWS CDK bootstrap** action to version 2.x to take advantage of the latest tooling available on the March 2024 image. To upgrade the action, set its `Identifier` property to `aws/cdk-bootstrap@v2` in your workflow definition file. For more information, see ['AWS CDK deploy' action YAML](cdk-dep-action-ref.md). 


| 'AWS CDK bootstrap' action version | Runtime environment images | 
| --- | --- | 
|  1.x  |  November 2022 images  | 
|  2.x  |  March 2024 images  | 

# Example: Bootstrapping an AWS CDK app
<a name="cdk-boot-action-example-workflow"></a>

Refer to the [Example: Deploying an AWS CDK app](cdk-dep-action-example-workflow.md) in the [Deploying an AWS CDK app with a workflow](cdk-dep-action.md) for a workflow that includes the **AWS CDK bootstrap** action.

# Adding the 'AWS CDK bootstrap' action
<a name="cdk-boot-action-add"></a>

 Use the following instructions to add the **AWS CDK bootstrap** action to your workflow. 

**Before you begin**

Before you can use the **AWS CDK bootstrap** action, make sure you have an AWS CDK app ready. The bootstrap action will synthesize the AWS CDK app before bootstrapping. You can write your app in any programming language supported by the AWS CDK.

Make sure your AWS CDK app files are available in:
+ A CodeCatalyst [source repository](source.md), or 
+ A CodeCatalyst [output artifact](workflows-working-artifacts.md) generated by another workflow action

------
#### [ Visual ]

**To add the 'AWS CDK bootstrap' action using the visual editor**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

1. Choose the name of your workflow. You can filter by the source repository or branch name where the workflow is defined, or filter by workflow name or status.

1. Choose **Edit**.

1. Choose **Visual**.

1. At the top-left, choose **\$1 Actions** to open the action catalog.

1. From the drop-down list, choose **Amazon CodeCatalyst**.

1. Search for the **AWS CDK bootstrap** action, and do one of the following:
   + Choose the plus sign (**\$1**) to add the action to the workflow diagram and open its configuration pane.

     Or
   + Choose **AWS CDK bootstrap**. The action details dialog box appears. On this dialog box:
     + (Optional) Choose **View source** to [view the action's source code](workflows-view-source.md#workflows-view-source.title).
     + Choose **Add to workflow** to add the action to the workflow diagram and open its configuration pane.

1. In the **Inputs**, **Configuration**, and **Outputs** tabs, complete the fields according to your needs. For a description of each field, see the ['AWS CDK bootstrap' action YAML](cdk-boot-action-ref.md). This reference provides detailed information about each field (and corresponding YAML property value) as it appears in both the YAML and visual editors.

1. (Optional) Choose **Validate** to validate the workflow's YAML code before committing.

1. Choose **Commit**, enter a commit message, and then choose **Commit** again.
**Note**  
If your **AWS CDK bootstrap** action fails with an `npm install` error, see [How do I fix "npm install" errors?](troubleshooting-workflows.md#troubleshooting-workflows-npm) for information about how to fix the error.

------
#### [ YAML ]

**To add the 'AWS CDK bootstrap' action using the YAML editor**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

1. Choose the name of your workflow. You can filter by the source repository or branch name where the workflow is defined, or filter by workflow name or status.

1. Choose **Edit**.

1. Choose **YAML**.

1. At the top-left, choose **\$1 Actions** to open the action catalog.

1. From the drop-down list, choose **Amazon CodeCatalyst**.

1. Search for the **AWS CDK bootstrap** action, and choose **\$1** to add it to the workflow diagram and open its configuration pane.

1. Modify the properties in the YAML code according to your needs. An explanation of each available property is provided in the ['AWS CDK bootstrap' action YAML](cdk-boot-action-ref.md).

1. (Optional) Choose **Validate** to validate the workflow's YAML code before committing.

1. Choose **Commit**, enter a commit message, and then choose **Commit** again.
**Note**  
If your **AWS CDK bootstrap** action fails with an `npm install` error, see [How do I fix "npm install" errors?](troubleshooting-workflows.md#troubleshooting-workflows-npm) for information about how to fix the error.

------

# 'AWS CDK bootstrap' variables
<a name="cdk-boot-action-variables"></a>

The **AWS CDK bootstrap** action produces and sets the following variables at run time. These are known as *predefined variables*.

For information about referencing these variables in a workflow, see [Using predefined variables](workflows-using-predefined-variables.md).


| Key | Value | 
| --- | --- | 
|  deployment-platform  |  The name of the deployment platform. Hardcoded to `AWS:CloudFormation`.  | 
|  region  |  The region code of the AWS Region that the AWS CDK bootstrap stack was deployed to during the workflow run. Example: `us-west-2`  | 
|  stack-id  |  The Amazon Resource Name (ARN) of the deployed AWS CDK bootstrap stack. Example: `arn:aws:cloudformation:us-west-2:111122223333:stack/codecatalyst-cdk-bootstrap-stack/6aad4380-100a-11ec-a10a-03b8a84d40df`  | 
|  SKIP-DEPLOYMENT  |  A value of `true` indicates that deployment of your AWS CDK bootstrap stack was skipped during the workflow run. A stack deployment will be skipped if there is no change in the stack since the last deployment. This variable is only produced if its value is `true`. Hardcoded to `true`.  | 

# 'AWS CDK bootstrap' action YAML
<a name="cdk-boot-action-ref"></a>

The following is the YAML definition of the **AWS CDK bootstrap** action. To learn how to use this action, see [Bootstrapping an AWS CDK app with a workflow](cdk-boot-action.md).

This action definition exists as a section within a broader workflow definition file. For more information about this file, see [Workflow YAML definition](workflow-reference.md).

**Note**  
Most of the YAML properties that follow have corresponding UI elements in the visual editor. To look up a UI element, use **Ctrl\$1F**. The element will be listed with its associated YAML property.

```
# The workflow definition starts here.
# See Top-level properties for details.
        
Name: MyWorkflow
SchemaVersion: 1.0 
Actions:

# The action definition starts here.    
  CDKBootstrapAction\$1nn: 
    Identifier: aws/cdk-bootstrap@v2
    DependsOn:
      - action-name
    Compute:  
      Type: EC2 | Lambda
      Fleet: fleet-name
    Timeout: timeout-minutes
    Inputs:
      # Specify a source or an artifact, but not both.
      Sources:
        - source-name-1
      Artifacts:
        - artifact-name
    Outputs:
      Artifacts:
        - Name: cdk_bootstrap_artifacts
          Files: 
            - "cdk.out/**/*"
    Environment:
      Name: environment-name
      Connections:
        - Name: account-connection-name
          Role: iam-role-name
    Configuration:
      Region: us-west-2
      CdkCliVersion: version
```

## CDKBootstrapAction
<a name="cdk.boot.name"></a>

(Required)

Specify the name of the action. All action names must be unique within the workflow. Action names are limited to alphanumeric characters (a-z, A-Z, 0-9), hyphens (-), and underscores (\$1). Spaces are not allowed. You cannot use quotation marks to enable special characters and spaces in action names.

Default: `CDKBootstrapAction_nn`.

Corresponding UI: Configuration tab/**Action display name**

## Identifier
<a name="cdk.boot.identifier"></a>

(*CDKBootstrapAction*/**Identifier**)

(Required)

Identifies the action. Do not change this property unless you want to change the version. For more information, see [Specifying the action version to use](workflows-action-versions.md).

**Note**  
Specifying `aws/cdk-bootstrap@v2` causes the action to run on the [March 2024 image](build-images.md#build.default-image) which includes newer tooling such as Node.js 18. Specifying `aws/cdk-bootstrap@v1` causes the action to run on the [November 2022 image](build-images.md#build.previous-image) which includes older tooling such as Node.js 16.

Default: `aws/cdk-bootstrap@v2`.

Corresponding UI: Workflow diagram/CDKBootstrapAction\$1nn/**aws/cdk-bootstrap@v2** label

## DependsOn
<a name="cdk.boot.dependson"></a>

(*CDKBootstrapAction*/**DependsOn**)

(Optional)

Specify an action, action group, or gate that must run successfully in order for this action to run.

For more information about the 'depends on' functionality, see [Sequencing actions](workflows-depends-on.md).

Corresponding UI: Inputs tab/**Depends on - optional**

## Compute
<a name="cdk.boot.computename"></a>

(*CDKBootstrapAction*/**Compute**)

(Optional)

The computing engine used to run your workflow actions. You can specify compute either at the workflow level or at the action level, but not both. When specified at the workflow level, the compute configuration applies to all actions defined in the workflow. At the workflow level, you can also run multiple actions on the same instance. For more information, see [Sharing compute across actions](compute-sharing.md).

Corresponding UI: *none*

## Type
<a name="cdk.boot.computetype"></a>

(*CDKBootstrapAction*/Compute/**Type**)

(Required if [Compute](#cdk.boot.computename) is included)

The type of compute engine. You can use one of the following values:
+ **EC2** (visual editor) or `EC2` (YAML editor)

  Optimized for flexibility during action runs.
+ **Lambda** (visual editor) or `Lambda` (YAML editor)

  Optimized action start-up speeds.

For more information about compute types, see [Compute types](workflows-working-compute.md#compute.types).

Corresponding UI: Configuration tab/Advanced - optional/**Compute type**

## Fleet
<a name="cdk.boot.computefleet"></a>

(*CDKBootstrapAction*/Compute/**Fleet**)

(Optional)

Specify the machine or fleet that will run your workflow or workflow actions. With on-demand fleets, when an action starts, the workflow provisions the resources it needs, and the machines are destroyed when the action finishes. Examples of on-demand fleets: `Linux.x86-64.Large`, `Linux.x86-64.XLarge`. For more information about on-demand fleets, see [On-demand fleet properties](workflows-working-compute.md#compute.on-demand).

With provisioned fleets, you configure a set of dedicated machines to run your workflow actions. These machines remain idle, ready to process actions immediately. For more information about provisioned fleets, see [Provisioned fleet properties](workflows-working-compute.md#compute.provisioned-fleets).

If `Fleet` is omitted, the default is `Linux.x86-64.Large`.

Corresponding UI: Configuration tab/Advanced - optional/**Compute fleet**

## Timeout
<a name="cdk.boot.timeout"></a>

(*CDKBootstrapAction*/**Timeout**)

(Required)

Specify the amount of time in minutes (YAML editor), or hours and minutes (visual editor), that the action can run before CodeCatalyst ends the action. The minimum is 5 minutes and the maximum is described in [Quotas for workflows in CodeCatalyst](workflows-quotas.md). The default timeout is the same as the maximum timeout.

Corresponding UI: Configuration tab/**Timeout - optional **

## Inputs
<a name="cdk.boot.inputs"></a>

(*CDKBootstrapAction*/**Inputs**)

(Optional)

The `Inputs` section defines the data that the **AWS CDK bootstrap** action needs during a workflow run.

Corresponding UI: **Inputs** tab

**Note**  
Only one input (either a source or an artifact) is allowed for each **AWS CDK bootstrap** action.

## Sources
<a name="cdk.boot.inputs.sources"></a>

(*CDKBootstrapAction*/Inputs/**Sources**)

(Required if your AWS CDK app is stored in a source repository)

If your AWS CDK app is stored in a source repository, specify the label of that source repository. The **AWS CDK bootstrap** action synthesizes the app in this repository before starting the bootstrapping process. Currently, the only supported repository label is `WorkflowSource`.

If your AWS CDK app is not contained within a source repository, it must reside in an artifact generated by another action.

For more information about sources, see [Connecting source repositories to workflows](workflows-sources.md).

Corresponding UI: Inputs tab/**Sources - optional**

## Artifacts - input
<a name="cdk.boot.inputs.artifacts"></a>

(*CDKBootstrapAction*/Inputs/**Artifacts**)

(Required if your AWS CDK app is stored in an [output artifact](workflows-working-artifacts-output.md) from a previous action)

If your AWS CDK app is contained in an artifact generated by a previous action, specify that artifact here. The **AWS CDK bootstrap** action synthesizes the app in the specified artifact into a CloudFormation template before starting the bootstrapping process. If your AWS CDK app is not contained within an artifact, it must reside in your source repository.

For more information about artifacts, including examples, see [Sharing artifacts and files between actions](workflows-working-artifacts.md).

Corresponding UI: Inputs tab/**Artifacts - optional**

## Outputs
<a name="cdk.boot.outputs"></a>

(*CDKBootstrapAction*/**Outputs**)

(Optional)

Defines the data that is output by the action during a workflow run.

Corresponding UI: **Outputs** tab

## Artifacts - output
<a name="cdk.boot.outputs.artifacts"></a>

(*CDKBootstrapAction*/Outputs/**Artifacts**)

(Optional)

Specify the artifacts generated by the action. You can reference these artifacts as input in other actions.

For more information about artifacts, including examples, see [Sharing artifacts and files between actions](workflows-working-artifacts.md).

Corresponding UI: Outputs tab/**Artifacts**

## Name
<a name="cdk.boot.outputs.artifacts.name"></a>

(*CDKBootstrapAction*/Outputs/Artifacts/**Name**)

(Required if [Artifacts - output](#cdk.boot.outputs.artifacts) is included)

Specify the name of the artifact that will contain the CloudFormation template that is synthesized by the **AWS CDK bootstrap** action at runtime. The default value is `cdk_bootstrap_artifacts`. If you do not specify an artifact, then the action synthesizes the template, but won't save it in an artifact. Consider saving the synthesized template in an artifact to preserve a record of it for testing or troubleshooting purposes.

Corresponding UI: Outputs tab/Artifacts/Add artifact/**Build artifact name**

## Files
<a name="cdk.boot.outputs.artifacts.files"></a>

(*CDKBootstrapAction*/Outputs/Artifacts/**Files**)

(Required if [Artifacts - output](#cdk.boot.outputs.artifacts) is included)

Specify the files to include in the artifact. You must specify `"cdk.out/**/*"` to include your AWS CDK app's synthesized CloudFormation template.

**Note**  
`cdk.out` is the default directory into which synthesized files are saved. If you specified an output directory other than `cdk.out` in your `cdk.json` file, specify that directory here instead of `cdk.out`.

Corresponding UI: Outputs tab/Artifacts/Add artifact/**Files produced by build**

## Environment
<a name="cdk.boot.environment"></a>

(*CDKBootstrapAction*/**Environment**)

(Required)

Specify the CodeCatalyst environment to use with the action. The action connects to the AWS account and optional Amazon VPC specified in the chosen environment. The action uses the default IAM role specified in the environment to connect to the AWS account, and uses the IAM role specified in the [Amazon VPC connection](https://docs.aws.amazon.com/codecatalyst/latest/adminguide/managing-vpcs.add.html) to connect to the Amazon VPC.

**Note**  
If the default IAM role does not have the permissions required by the action, you can configure the action to use a different role. For more information, see [Changing the IAM role of an action](deploy-environments-switch-role.md).

For more information about environments, see [Deploying into AWS accounts and VPCs](deploy-environments.md) and [Creating an environment](deploy-environments-creating-environment.md).

Corresponding UI: Configuration tab/**Environment**

## Name
<a name="cdk.boot.environment.name"></a>

(*CDKBootstrapAction*/Environment/**Name**)

(Required if [Environment](#cdk.boot.environment) is included)

Specify the name of an existing environment that you want to associate with the action.

Corresponding UI: Configuration tab/**Environment**

## Connections
<a name="cdk.boot.environment.connections"></a>

(*CDKBootstrapAction*/Environment/**Connections**)

(Optional in newer versions of the action; required in older versions)

Specify the account connection to associate with the action. You can specify a maximum of one account connection under `Environment`.

If you do not specify an account connection:
+ The action uses the AWS account connection and default IAM role specified in the environment in the CodeCatalyst console. For information about adding an account connection and default IAM role to environment, see [Creating an environment](deploy-environments-creating-environment.md).
+ The default IAM role must include the policies and permissions required by the action. To determine what those policies and permissions are, see the description of the **Role** property in the action's YAML definition documentation.

For more information about account connections, see [Allowing access to AWS resources with connected AWS accounts](ipa-connect-account.md). For information about adding an account connection to an environment, see [Creating an environment](deploy-environments-creating-environment.md).

Corresponding UI: One of the following depending on the action version:
+ (Newer versions) Configuration tab/Environment/What's in *my-environment*?/three dot menu/**Switch role**
+ (Older versions) Configuration tab/'Environment/account/role'/**AWS account connection**

## Name
<a name="cdk.boot.environment.connections.name"></a>

(*CDKBootstrapAction*/Environment/Connections/**Name**)

(Required if [Connections](#cdk.boot.environment.connections) is included)

Specify the name of the account connection.

Corresponding UI: One of the following depending on the action version:
+ (Newer versions) Configuration tab/Environment/What's in *my-environment*?/three dot menu/**Switch role**
+ (Older versions) Configuration tab/'Environment/account/role'/**AWS account connection**

## Role
<a name="cdk.boot.environment.connections.role"></a>

(*CDKBootstrapAction*/Environment/Connections/**Role**)

(Required if [Connections](#cdk.boot.environment.connections) is included)

Specify the name of the IAM role that the **AWS CDK bootstrap** action uses to access AWS and add the bootstrap stack. Make sure that you have [added the role to your CodeCatalyst space](ipa-connect-account-addroles.md), and that the role includes the following policies.

If you do not specify an IAM role, then the action uses the default IAM role listed in the [environment](deploy-environments.md) in the CodeCatalyst console. If you use the default role in the environment, make sure it has the appropriate policies.

You can use the `CodeCatalystWorkflowDevelopmentRole-spaceName` role with this action, if you'd like. For more information about this role, see [Creating the **CodeCatalystWorkflowDevelopmentRole-*spaceName*** role for your account and space](ipa-iam-roles.md#ipa-iam-roles-service-create). Understand that the `CodeCatalystWorkflowDevelopmentRole-spaceName` role has full access permissions which may pose a security risk. We recommend that you only use this role in tutorials and scenarios where security is less of a concern. 

Corresponding UI: One of the following depending on the action version:
+ (Newer versions) Configuration tab/Environment/What's in *my-environment*?/three dot menu/**Switch role**
+ (Older versions) Configuration tab/'Environment/account/role'/**Role**

## Configuration
<a name="cdk.boot.configuration"></a>

(*CDKBootstrapAction*/**Configuration**)

(Required)

A section where you can define the configuration properties of the action.

Corresponding UI: **Configuration** tab

## Region
<a name="cdk.boot.region"></a>

(*CDKBootstrapAction*/Configuration/**Region**)

(Required)

Specify the AWS Region into which the bootstrap stack will be deployed. This Region should match the one into which your AWS CDK app is deployed. For a list of Region codes, see [Regional endpoints](https://docs.aws.amazon.com/general/latest/gr/rande.html#region-names-codes).

Corresponding UI: Configuration tab/**Region**

## CdkCliVersion
<a name="cdk.boot.cdk.cli.version"></a>

(*CDKBootstrapAction*/Configuration/**CdkCliVersion**)

(Optional)

This property is available with version 1.0.13 or later of the **AWS CDK deploy** action, and version 1.0.8 or later of the **AWS CDK bootstrap** action.

Specify one of the following:
+ The full version of the AWS Cloud Development Kit (AWS CDK) Command Line Interface (CLI) (also called the AWS CDK Toolkit) that you want this action to use. Example: `2.102.1`. Consider specifying a full version to ensure consistency and stability when building and deploying your application.

  Or
+ `latest`. Consider specifying `latest` to take advantage of the latest features and fixes of the CDK CLI.

The action will download the specified version (or the latest version) of the AWS CDK CLI to the CodeCatalyst [build image](build-images.md), and then use this version to run the commands necessary to deploy your CDK application or bootstrap your AWS environment.

For a list of supported CDK CLI versions you can use, see [AWS CDK Versions](https://docs.aws.amazon.com/cdk/api/versions.html).

If you omit this property, the action uses a default AWS CDK CLI version described in one of the following topics:
+ [CDK CLI versions used by the 'AWS CDK deploy' action](cdk-dep-action.md#cdk-dep-action-cdk-version) 
+ [CDK CLI versions used by the "AWS CDK bootstrap" action](cdk-boot-action.md#cdk-boot-action-cdk-version)

Corresponding UI: Configuration tab/**AWS CDK CLI version**

# Publishing files to Amazon S3 with a workflow
<a name="s3-pub-action"></a>

This section describes how to publish files to Amazon S3 using a CodeCatalyst workflow. To accomplish this, you must add the **Amazon S3 publish** action to your workflow. The **Amazon S3 publish** action copies files from a source directory to an Amazon S3 bucket. The source directory can reside in:
+ A [source repository](source.md), or 
+ An [output artifact](workflows-working-artifacts.md) generated by another workflow action

**Topics**
+ [When to use the 'Amazon S3 publish' action](#s3-pub-action-when-to-use)
+ [Runtime image used by the 'Amazon S3 publish' action](#s3-pub-action-runtime)
+ [Example: Publish files to Amazon S3](s3-pub-action-example-workflow.md)
+ [Adding the 'Amazon S3 publish' action](s3-pub-action-add.md)
+ ['Amazon S3 publish' action YAML](s3-pub-action-ref.md)

## When to use the 'Amazon S3 publish' action
<a name="s3-pub-action-when-to-use"></a>

Use this action if:
+ You have a workflow that generates files that you want to store in Amazon S3.

  For example, you might have a workflow that builds a static website that you want to host in Amazon S3. In this case, your workflow would include a [build action](build-add-action.md) to build the site's HTML and supporting files, and an **Amazon S3 publish** action to copy the files to Amazon S3.
+ You have a source repository that contains files that you want to store in Amazon S3.

  For example, you might have a source repository with application source files that you want to archive on a nightly basis to Amazon S3.

## Runtime image used by the 'Amazon S3 publish' action
<a name="s3-pub-action-runtime"></a>

The **Amazon S3 publish** action runs on a [November 2022 image](build-images.md#build.previous-image). For more information, see [Active images](build-images.md#build-curated-images).

# Example: Publish files to Amazon S3
<a name="s3-pub-action-example-workflow"></a>

The following example workflow includes the **Amazon S3 publish** action, along with a build action. The workflow builds a static documentation website and then publishes it to Amazon S3, where it is hosted. The workflow consists of the following building blocks that run sequentially:
+ A **trigger** – This trigger starts the workflow run automatically when you push a change to your source repository. For more information about triggers, see [Starting a workflow run automatically using triggers](workflows-add-trigger.md).
+ A **build** action (`BuildDocs`) – On trigger, the action builds a static documentation website (`mkdocs build`) and adds the associated HTML files and supporting metadata to an artifact called `MyDocsSite`. For more information about the build action, see [Building with workflows](build-workflow-actions.md).
+ An **Amazon S3 publish** action (`PublishToS3`) – On completion of the build action, this action copies the site in the `MyDocsSite` artifact to Amazon S3 for hosting.

**Note**  
The following workflow example is for illustrative purposes, and will not work without additional configuration.

**Note**  
In the YAML code that follows, you can omit the `Connections:` section if you want. If you omit this section, you must ensure that the role specified in the **Default IAM role** field in your environment includes the permissions and trust policies required by the **Amazon S3 publish** action. For more information about setting up an environment with a default IAM role, see [Creating an environment](deploy-environments-creating-environment.md). For more information about the permissions and trust policies required by the **Amazon S3 publish** action, see the description of the [Role](s3-pub-action-ref.md#s3.pub.environment.connections.role) property in the ['Amazon S3 publish' action YAML](s3-pub-action-ref.md).

```
Name: codecatalyst-s3-publish-workflow
SchemaVersion: 1.0

Triggers:
  - Type: PUSH
    Branches:
      - main
Actions:
  BuildDocs:
    Identifier: aws/build@v1
    Inputs:
      Sources:
        - WorkflowSource
    Configuration:
      Steps:
        - Run: echo BuildDocs started on `date`
        - Run: pip install --upgrade pip
        - Run: pip install mkdocs
        - Run: mkdocs build
        - Run: echo BuildDocs completed on `date`
    Outputs:
      Artifacts:
      - Name: MyDocsSite
        Files:
          - "site/**/*"
        
  PublishToS3:
    Identifier: aws/s3-publish@v1
    Environment:
      Name: codecatalyst-s3-publish-environment
      Connections:
        - Name: codecatalyst-account-connection
          Role: codecatalyst-s3-publish-build-role
    Inputs:
      Sources:
        - WorkflowSource
      Artifacts:
        - MyDocsSite
    Configuration:      
      DestinationBucketName: amzn-s3-demo-bucket
      SourcePath: /artifacts/PublishToS3/MyDocSite/site
      TargetPath: my/docs/site
```

# Adding the 'Amazon S3 publish' action
<a name="s3-pub-action-add"></a>

 Use the following instructions to add the **Amazon S3 publish** action to your workflow. 

------
#### [ Visual ]

**To add the 'Amazon S3 publish' action using the visual editor**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

1. Choose the name of your workflow. You can filter by the source repository or branch name where the workflow is defined, or filter by workflow name or status.

1. Choose **Edit**.

1. Choose **Visual**.

1. At the top-left, choose **\$1 Actions** to open the action catalog.

1. From the drop-down list, choose **Amazon CodeCatalyst**.

1. Search for the **Amazon S3 publish** action, and do one of the following:
   + Choose the plus sign (**\$1**) to add the action to the workflow diagram and open its configuration pane.

     Or
   + Choose **Amazon S3 publish**. The action details dialog box appears. On this dialog box:
     + (Optional) Choose **View source** to [view the action's source code](workflows-view-source.md#workflows-view-source.title).
     + Choose **Add to workflow** to add the action to the workflow diagram and open its configuration pane.

1. In the **Inputs**, **Configuration**, and **Outputs** tabs, complete the fields according to your needs. For a description of each field, see the ['Amazon S3 publish' action YAML](s3-pub-action-ref.md). This reference provides detailed information on each field (and corresponding YAML property value) as it appears in both the YAML and visual editors.

1. (Optional) Choose **Validate** to validate the workflow's YAML code before committing.

1. Choose **Commit**, enter a commit message, and then choose **Commit** again.

------
#### [ YAML ]

**To add the 'Amazon S3 publish' action using the YAML editor**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

1. Choose the name of your workflow. You can filter by the source repository or branch name where the workflow is defined, or filter by workflow name or status.

1. Choose **Edit**.

1. Choose **YAML**.

1. At the top-left, choose **\$1 Actions** to open the action catalog.

1. From the drop-down list, choose **Amazon CodeCatalyst**.

1. Search for the **Amazon S3 publish** action, and do one of the following:
   + Choose the plus sign (**\$1**) to add the action to the workflow diagram and open its configuration pane.

     Or
   + Choose **Amazon S3 publish**. The action details dialog box appears. On this dialog box:
     + (Optional) Choose **View source** to [view the action's source code](workflows-view-source.md#workflows-view-source.title).
     + Choose **Add to workflow** to add the action to the workflow diagram and open its configuration pane.

1. Modify the properties in the YAML code according to your needs. An explanation of each available property is provided in the ['Amazon S3 publish' action YAML](s3-pub-action-ref.md).

1. (Optional) Choose **Validate** to validate the workflow's YAML code before committing.

1. Choose **Commit**, enter a commit message, and then choose **Commit** again.

------

# 'Amazon S3 publish' action YAML
<a name="s3-pub-action-ref"></a>

The following is the YAML definition of the **Amazon S3 publish** action. To learn how to use this action, see [Publishing files to Amazon S3 with a workflow](s3-pub-action.md).

This action definition exists as a section within a broader workflow definition file. For more information about this file, see [Workflow YAML definition](workflow-reference.md).

**Note**  
Most of the YAML properties that follow have corresponding UI elements in the visual editor. To look up a UI element, use **Ctrl\$1F**. The element will be listed with its associated YAML property.

```
# The workflow definition starts here.
# See Top-level properties for details.
        
Name: MyWorkflow
SchemaVersion: 1.0 
Actions:

# The action definition starts here.    
  S3Publish\$1nn: 
    Identifier: aws/s3-publish@v1
    DependsOn:
      - build-action
    Compute:  
      Type: EC2 | Lambda
      Fleet: fleet-name
    Timeout: timeout-minutes
    Inputs:
      Sources:
        - source-name-1
      Artifacts:
        - artifact-name
      Variables:
        - Name: variable-name-1
          Value: variable-value-1
        - Name: variable-name-2
          Value: variable-value-2
    Environment:
      Name: environment-name
      Connections:
        - Name: account-connection-name
          Role: iam-role-name
    Configuration:
      SourcePath: my/source
      DestinationBucketName: amzn-s3-demo-bucket
      TargetPath: my/target
```

## S3Publish
<a name="s3.pub.name"></a>

(Required)

Specify the name of the action. All action names must be unique within the workflow. Action names are limited to alphanumeric characters (a-z, A-Z, 0-9), hyphens (-), and underscores (\$1). Spaces are not allowed. You cannot use quotation marks to enable special characters and spaces in action names.

Default: `S3Publish_nn`.

Corresponding UI: Configuration tab/**Action name**

## Identifier
<a name="s3.pub.identifier"></a>

(*S3Publish*/**Identifier**)

(Required)

Identifies the action. Do not change this property unless you want to change the version. For more information, see [Specifying the action version to use](workflows-action-versions.md).

Default: `aws/s3-publish@v1`.

Corresponding UI: Workflow diagram/S3Publish\$1nn/**aws/s3-publish@v1** label

## DependsOn
<a name="s3.pub.dependson"></a>

(*S3Publish*/**DependsOn**)

(Optional)

Specify an action, action group, or gate that must run successfully in order for this action to run.

For more information about the 'depends on' functionality, see [Sequencing actions](workflows-depends-on.md).

Corresponding UI: Inputs tab/**Depends on - optional**

## Compute
<a name="s3.pub.computename"></a>

(*S3Publish*/**Compute**)

(Optional)

The computing engine used to run your workflow actions. You can specify compute either at the workflow level or at the action level, but not both. When specified at the workflow level, the compute configuration applies to all actions defined in the workflow. At the workflow level, you can also run multiple actions on the same instance. For more information, see [Sharing compute across actions](compute-sharing.md).

Corresponding UI: *none*

## Type
<a name="s3.pub.computetype"></a>

(*S3Publish*/Compute/**Type**)

(Required if [Compute](#s3.pub.computename) is included)

The type of compute engine. You can use one of the following values:
+ **EC2** (visual editor) or `EC2` (YAML editor)

  Optimized for flexibility during action runs.
+ **Lambda** (visual editor) or `Lambda` (YAML editor)

  Optimized action start-up speeds.

For more information about compute types, see [Compute types](workflows-working-compute.md#compute.types).

Corresponding UI: Configuration tab/**Compute type**

## Fleet
<a name="s3.pub.computefleet"></a>

(*S3Publish*/Compute/**Fleet**)

(Optional)

Specify the machine or fleet that will run your workflow or workflow actions. With on-demand fleets, when an action starts, the workflow provisions the resources it needs, and the machines are destroyed when the action finishes. Examples of on-demand fleets: `Linux.x86-64.Large`, `Linux.x86-64.XLarge`. For more information about on-demand fleets, see [On-demand fleet properties](workflows-working-compute.md#compute.on-demand).

With provisioned fleets, you configure a set of dedicated machines to run your workflow actions. These machines remain idle, ready to process actions immediately. For more information about provisioned fleets, see [Provisioned fleet properties](workflows-working-compute.md#compute.provisioned-fleets).

If `Fleet` is omitted, the default is `Linux.x86-64.Large`.

Corresponding UI: Configuration tab/**Compute fleet**

## Timeout
<a name="s3.pub.timeout"></a>

(*S3Publish*/**Timeout**)

(Required)

Specify the amount of time in minutes (YAML editor), or hours and minutes (visual editor), that the action can run before CodeCatalyst ends the action. The minimum is 5 minutes and the maximum is described in [Quotas for workflows in CodeCatalyst](workflows-quotas.md). The default timeout is the same as the maximum timeout.

Corresponding UI: Configuration tab/**Timeout - optional **

## Inputs
<a name="s3.pub.inputs"></a>

(*S3Publish*/**Inputs**)

(Optional)

The `Inputs` section defines the data that the `S3Publish` needs during a workflow run.

**Note**  
A maximum of four inputs (one source and three artifacts) are allowed for each **AWS CDK deploy** action. Variables do not count towards this total.

If you need to refer to files residing in different inputs (say a source and an artifact), the source input is the primary input, and the artifact is the secondary input. References to files in secondary inputs take a special prefix to distiguish them from the primary. For details, see [Example: Referencing files in multiple artifacts](workflows-working-artifacts-ex.md#workflows-working-artifacts-ex-ref-file).

Corresponding UI: **Inputs** tab

## Sources
<a name="s3.pub.inputs.sources"></a>

(*S3Publish*/Inputs/**Sources**)

(Required if the files you want to publish to Amazon S3 are stored in a source repository)

If the files that you want to publish to Amazon S3 are stored in a source repository, specify the label of that source repository. Currently, the only supported label is `WorkflowSource`.

If the files that you want to publish to Amazon S3 are not contained within a source repository, they must reside in an artifact generated by another action.

For more information about sources, see [Connecting source repositories to workflows](workflows-sources.md).

Corresponding UI: Inputs tab/**Sources - optional**

## Artifacts - input
<a name="s3.pub.inputs.artifacts"></a>

(*S3Publish*/Inputs/**Artifacts**)

(Required if the files you want to publish to Amazon S3 are stored in an [output artifact](workflows-working-artifacts-output.md) from a previous action)

If the files that you want to publish to Amazon S3 are contained in an artifact generated by a previous action, specify that artifact here. If your files are not contained within an artifact, they must reside in your source repository.

For more information about artifacts, including examples, see [Sharing artifacts and files between actions](workflows-working-artifacts.md).

Corresponding UI: Configuration tab/**Artifacts - optional**

## Variables - input
<a name="s3.pub.inputs.variables"></a>

(*S3Publish*/Inputs/**Variables**)

(Optional)

Specify a sequence of name/value pairs that define the input variables that you want to make available to the action. Variable names are limited to alphanumeric characters (a-z, A-Z, 0-9), hyphens (-), and underscores (\$1). Spaces are not allowed. You cannot use quotation marks to enable special characters and spaces in variable names.

For more information about variables, including examples, see [Using variables in workflows](workflows-working-with-variables.md).

Corresponding UI: Inputs tab/**Variables - optional**

## Environment
<a name="s3.pub.environment"></a>

(*S3Publish*/**Environment**)

(Required)

Specify the CodeCatalyst environment to use with the action. The action connects to the AWS account and optional Amazon VPC specified in the chosen environment. The action uses the default IAM role specified in the environment to connect to the AWS account, and uses the IAM role specified in the [Amazon VPC connection](https://docs.aws.amazon.com/codecatalyst/latest/adminguide/managing-vpcs.add.html) to connect to the Amazon VPC.

**Note**  
If the default IAM role does not have the permissions required by the action, you can configure the action to use a different role. For more information, see [Changing the IAM role of an action](deploy-environments-switch-role.md).

For more information about environments, see [Deploying into AWS accounts and VPCs](deploy-environments.md) and [Creating an environment](deploy-environments-creating-environment.md).

Corresponding UI: Configuration tab/**Environment**

## Name
<a name="s3.pub.environment.name"></a>

(*S3Publish*/Environment/**Name**)

(Required if [Environment](#s3.pub.environment) is included)

Specify the name of an existing environment that you want to associate with the action.

Corresponding UI: Configuration tab/**Environment**

## Connections
<a name="s3.pub.environment.connections"></a>

(*S3Publish*/Environment/**Connections**)

(Optional in newer versions of the action; required in older versions)

Specify the account connection to associate with the action. You can specify a maximum of one account connection under `Environment`.

If you do not specify an account connection:
+ The action uses the AWS account connection and default IAM role specified in the environment in the CodeCatalyst console. For information about adding an account connection and default IAM role to environment, see [Creating an environment](deploy-environments-creating-environment.md).
+ The default IAM role must include the policies and permissions required by the action. To determine what those policies and permissions are, see the description of the **Role** property in the action's YAML definition documentation.

For more information about account connections, see [Allowing access to AWS resources with connected AWS accounts](ipa-connect-account.md). For information about adding an account connection to an environment, see [Creating an environment](deploy-environments-creating-environment.md).

Corresponding UI: One of the following depending on the action version:
+ (Newer versions) Configuration tab/Environment/What's in *my-environment*?/three dot menu/**Switch role**
+ (Older versions) Configuration tab/'Environment/account/role'/**AWS account connection**

## Name
<a name="s3.pub.environment.connections.name"></a>

(*S3Publish*/Environment/Connections/**Name**)

(Required if [Connections](#s3.pub.environment.connections) is included)

Specify the name of the account connection.

Corresponding UI: One of the following depending on the action version:
+ (Newer versions) Configuration tab/Environment/What's in *my-environment*?/three dot menu/**Switch role**
+ (Older versions) Configuration tab/'Environment/account/role'/**AWS account connection**

## Role
<a name="s3.pub.environment.connections.role"></a>

(*S3Publish*/Environment/Connections/**Role**)

(Required if [Connections](#s3.pub.environment.connections) is included)

Specify the name of the IAM role that the **Amazon S3 publish** action uses to access AWS and to copy files to Amazon S3. Make sure that you have [added the role to your CodeCatalyst space](ipa-connect-account-addroles.md), and that the role includes the following policies.

If you do not specify an IAM role, then the action uses the default IAM role listed in the [environment](deploy-environments.md) in the CodeCatalyst console. If you use the default role in the environment, make sure it has the following policies.
+ The following permissions policy:
**Warning**  
Limit the permissions to those shown in the following policy. Using a role with broader permissions might pose a security risk.

------
#### [ JSON ]

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Statement": [
          {
              "Sid": "VisualEditor0",
              "Effect": "Allow",
              "Action": [
                  "s3:PutObject",
                  "s3:ListBucket",
                  "s3:DeleteObject"
              ],
              "Resource": [
                  "arn:aws:s3:::bucket-name",
                  "arn:aws:s3:::bucket-name/*"
              ]
          }
      ]
  }
  ```

------
+ The following custom trust policy:

**Note**  
You can use the `CodeCatalystWorkflowDevelopmentRole-spaceName` role with this action, if you'd like. For more information about this role, see [Creating the **CodeCatalystWorkflowDevelopmentRole-*spaceName*** role for your account and space](ipa-iam-roles.md#ipa-iam-roles-service-create). Understand that the `CodeCatalystWorkflowDevelopmentRole-spaceName` role has full access permissions which may pose a security risk. We recommend that you only use this role in tutorials and scenarios where security is less of a concern. 

Corresponding UI: One of the following depending on the action version:
+ (Newer versions) Configuration tab/Environment/What's in *my-environment*?/three dot menu/**Switch role**
+ (Older versions) Configuration tab/'Environment/account/role'/**Role**

## Configuration
<a name="s3.pub.configuration"></a>

(*S3Publish*/**Configuration**)

(Required)

A section where you can define the configuration properties of the action.

Corresponding UI: **Configuration** tab

## SourcePath
<a name="s3.pub.source.directory"></a>

(*S3Publish*/Configuration/**SourcePath**)

(Required)

Specify the name and path of a directory or file that you want to publish to Amazon S3. The directory or file can reside in a source repository or an artifact from a previous action, and is relative to the source repository or artifact root.

Examples:

Specifying `./myFolder/` copies the contents of `/myFolder` to Amazon S3, and preserves the underlying directory structure.

Specifying `./myFolder/myfile.txt` copies *just *`myfile.txt` to Amazon S3. (The directory structure is removed.)

You cannot use wildcards.

**Note**  
You may need to add a prefix to the directory or file path to indicate which artifact or source to find it in. For more information, see [Referencing source repository files](workflows-sources-reference-files.md) and [Referencing files in an artifact](workflows-working-artifacts-refer-files.md).

Corresponding UI: Configuration tab/**Source path**

## DestinationBucketName
<a name="s3.pub.dest.bucket"></a>

(*S3Publish*/Configuration/**DestinationBucketName**)

(Required)

Specify the name of the Amazon S3 bucket where you want to publish files.

Corresponding UI: Configuration tab/**Destination bucket - optional**

## TargetPath
<a name="s3.pub.dest.directory"></a>

(*S3Publish*/Configuration/**TargetPath**)

(Optional)

Specify the name and path of the directory in Amazon S3 where you want to publish your files. If the directory does not exist, it will be created. The directory path must not include the bucket name.

Examples:

`myS3Folder`

`./myS3Folder/myS3Subfolder`

Corresponding UI: Configuration tab/**Destination directory - optional**

# Deploying into AWS accounts and VPCs
<a name="deploy-environments"></a>

Using [CodeCatalyst workflows](workflow.md), you can deploy applications and other resources to target AWS accounts and Amazon VPCs in the AWS cloud. To enable these deployments, you must set up CodeCatalyst environments.

A CodeCatalyst *environment*, not to be confused with a [Dev Environment](https://docs.aws.amazon.com/codecatalyst/latest/userguide/devenvironment.html), defines the target AWS account and optional Amazon VPC that a CodeCatalyst [workflow](workflow.md) connects to. An environment also defines the [IAM role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) that a workflow needs to access the AWS services and resources within the target account.

You can set up multiple environments and give them names such as development, test, staging, and production. When you deploy into these environments, information about the deployments appears on the CodeCatalyst **Deployment activity** and **Deployment targets** tabs in the environment.

## How do I get started with environments?
<a name="deploy-environments-get-started"></a>

The high-level steps to add and use a CodeCatalyst environment are as follows:

1. In your CodeCatalyst space, **connect one or more AWS accounts**. During this process, add the IAM roles that your workflow requires to access resources in your AWS account. For more information, see [Allowing access to AWS resources with connected AWS accounts](ipa-connect-account.md).

1. In your CodeCatalyst project, **create an environment** that includes one of the AWS accounts and IAM roles from step 1. For more information, see [Creating an environment](deploy-environments-creating-environment.md).

1. In your CodeCatalyst project, in a workflow, **add an [action](workflows-actions.md) that points to the environment** you created in step 2. For more information, see [Adding an action to a workflow](workflows-add-action.md).

   You have now configured an environment. The action can now deploy resources into the AWS account specified in the environment.

**Note**  
You can also add an Amazon VPC to the environment. For more information, see [Adding VPC connections for a space](https://docs.aws.amazon.com/codecatalyst/latest/adminguide/managing-vpcs.add.html) in the *CodeCatalyst Administration Guide* and [Associating a VPC with an environment](deploy-environments-associate-vpc.md).

## Can multiple environments exist within a single workflow?
<a name="deploy-environments-multiple"></a>

Yes. If a workflow includes multiple actions, each of those actions can be assigned an environment. For example, you could have a workflow that includes two deploy actions, where one is assigned a `my-staging-enviroment` environment and another is assigned a `my-production-environment` environment.

## Which workflow actions support environments?
<a name="deploy-environments-supported"></a>

Any workflow action that deploys resources into the AWS cloud, or communicates with AWS services for other reasons (such as monitoring and reporting), supports environments.

## Which actions support having their deployment information displayed in CodeCatalyst?
<a name="deploy-environments-supported-targets"></a>

Of the workflow actions that support environments, only a few support having their deployment information displayed on the **Deployment activity** and **Deployment targets** pages of the CodeCatalyst console.

The following workflow actions support having their deployment information displayed:
+ **Deploy CloudFormation stack** – For more information, see [Deploying an CloudFormation stack](deploy-action-cfn.md)
+ **Deploy to Amazon ECS** – For more information, see [Deploying to Amazon ECS with a workflow](deploy-action-ecs.md)
+ **Deploy to Kubernetes cluster** – For more information, see [Deploying to Amazon EKS with a workflow](deploy-action-eks.md)
+ **AWS CDK deploy** – For more information, see [Deploying an AWS CDK app with a workflow](cdk-dep-action.md)

## Supported Regions
<a name="deploy-environments-supported-regions"></a>

The **Environments** page can display resources in any AWS Region.

## Is an environment mandatory?
<a name="deploy-environments-optional-or-mandatory"></a>

An environment is mandatory if the workflow action to which it is assigned deploys resources into the AWS cloud, or communicates with AWS services for other reasons (such as monitoring and reporting).

For example, if you have a build action that builds an application but doesn't need to communicate with your AWS account or Amazon VPC, then you do not need to assign an environment to the action. If, however, the build action sends logs to the Amazon CloudWatch service in your AWS account, then the action must have an environment assigned. 

**Topics**
+ [How do I get started with environments?](#deploy-environments-get-started)
+ [Can multiple environments exist within a single workflow?](#deploy-environments-multiple)
+ [Which workflow actions support environments?](#deploy-environments-supported)
+ [Which actions support having their deployment information displayed in CodeCatalyst?](#deploy-environments-supported-targets)
+ [Supported Regions](#deploy-environments-supported-regions)
+ [Is an environment mandatory?](#deploy-environments-optional-or-mandatory)
+ [Creating an environment](deploy-environments-creating-environment.md)
+ [Associating an environment with an action](deploy-environments-add-app-to-environment.md)
+ [Associating a VPC with an environment](deploy-environments-associate-vpc.md)
+ [Associating an AWS account with an environment](deploy-environments-associate-account.md)
+ [Changing the IAM role of an action](deploy-environments-switch-role.md)

# Creating an environment
<a name="deploy-environments-creating-environment"></a>

Use the following instructions to create an environment that you can later associate with a workflow action.

**Before you begin**

You need the following:
+ A CodeCatalyst space. For more information, see [Set up and sign in to CodeCatalystSet up and sign in to CodeCatalyst](setting-up-topnode.md).
+ A CodeCatalyst project. For more information, see [Creating a project with a blueprint](projects-create.md#projects-create-console-template).
+ An AWS account connection that includes the IAM roles your workflow action will need to access AWS. For information about creating an account connection, see [Allowing access to AWS resources with connected AWS accounts](ipa-connect-account.md). You can use a maximum of one account connection per environment.
**Note**  
You can create an environment without an account connection; however, you will need to come back and add the connection later.
+ One of the following CodeCatalyst roles:
  + **Space administrator**
  + **Project administrator**
  + **Contributor**
**Note**  
If you have the **Contributor role**, you'll be able to create an environment but you won't be able to associate it with an AWS account connection. You'll need to ask someone with the **Space administrator** or **Project administrator** role to associate the environment with an AWS account connection.

   For more information about permissions and roles, see [Granting users project permissions](projects-members.md).

**To create an environment**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Environments**.

1. In **Environment name**, enter a name, such as **Production** or **Staging**.

1. In **Environment type**, select one of the following:
   + **Non-production** – An environment where you can test your application to make sure it's working as intended before moving it into production.
   + **Production** – A 'live' environment that is publicly-available and hosts your finalized application.

     If you choose **Production**, a **Production** badge appears in the UI next to any actions that the environment is associated with. The badge helps you quickly see which actions are deploying to production. Other than the appearance of the badge, there are no differences between production and non-production environments.

1. (Optional) In **Description**, enter a description such as **Production environment for the hello-world app**.

1. In **AWS account connection - optional**, choose the AWS account connection you want to associate with this environment. Workflow actions that are assigned this environment will be able to connect to the associated AWS account. For more information about creating AWS account connections in CodeCatalyst, see [Allowing access to AWS resources with connected AWS accounts](ipa-connect-account.md).

   If the AWS account connection that you want to use is not listed, it might be because it's not allowed in your project. For more information, see [Configuring project-restricted account connections](https://docs.aws.amazon.com/codecatalyst/latest/adminguide/managing-accounts-restriction.html) in the *Amazon CodeCatalyst Administrator Guide*.

1. In **Default IAM role**, choose the IAM role you want to associate with this environment. Workflow actions that are assigned this environment will inherit this IAM role, and will be able to use it to connect to services and resources in your AWS account.

   If you need to assign the environment to multiple actions, and those actions need IAM roles that are different from the default one specified here, then you can specify the different roles on each action's **Configuration** tab, using the **Switch role** option. For more information, see [Changing the IAM role of an action](deploy-environments-switch-role.md).

   If the IAM role that you want to use as the default is not listed, it might be because you have not added it to your AWS account connection yet. To add an IAM role to an account connection, see [Adding IAM roles to account connections](ipa-connect-account-addroles.md).

1. (Optional) In **VPC connection**, choose a VPC connection that you want to associate with this environment. For more information about creating VPC connections, see [ Managing Amazon Virtual Private Clouds](https://docs.aws.amazon.com/codecatalyst/latest/adminguide/managing-vpcs.html) in the *Amazon CodeCatalyst Administrator Guide*.

   If the VPC connection that you want to use is not listed, it might be because it includes an AWS account connection that's not allowed in your project. For more information, see [Configuring project-restricted account connections](https://docs.aws.amazon.com/codecatalyst/latest/adminguide/managing-accounts-restriction.html) in the *Amazon CodeCatalyst Administrator Guide*.

1. Choose **Create environment**. CodeCatalyst creates an empty environment.

**Next steps**
+ Now that you have created an environment, you are ready to associate it with a workflow action. For more information, see [Associating an environment with an action](deploy-environments-add-app-to-environment.md).

# Associating an environment with an action
<a name="deploy-environments-add-app-to-environment"></a>

When you associate an environment with a [supported workflow action](deploy-environments.md#deploy-environments-supported), the environment's AWS account, default IAM role, and optional Amazon VPC become assigned to the action. The action can then connect and deploy to the AWS account using the IAM role, and also connect to the optional Amazon VPC.

Use the following instructions to associate an environment with an action.

## Step 1: Associate the environment with a workflow action
<a name="deploy-environments-add-app-to-environment-assoc"></a>

Use the following procedure to associate an environment with a workflow action.

------
#### [ Visual ]

**To associate an environment with a workflow action using the visual editor**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

1. Choose the name of your workflow. You can filter by the source repository or branch name where the workflow is defined, or filter by workflow name or status.

1. Choose **Edit**.

1. Choose **Visual**.

1. In the workflow diagram, choose an action that is supported with environments. For more information, see [Which actions support having their deployment information displayed in CodeCatalyst?](deploy-environments.md#deploy-environments-supported-targets).

1. Choose the **Configuration** tab, and specify information in the **Environment** field, as follows.

   **Environment**

   Specify the CodeCatalyst environment to use with the action. The action connects to the AWS account and optional Amazon VPC specified in the chosen environment. The action uses the default IAM role specified in the environment to connect to the AWS account, and uses the IAM role specified in the [Amazon VPC connection](https://docs.aws.amazon.com/codecatalyst/latest/adminguide/managing-vpcs.add.html) to connect to the Amazon VPC.
**Note**  
If the default IAM role does not have the permissions required by the action, you can configure the action to use a different role. For more information, see [Changing the IAM role of an action](deploy-environments-switch-role.md).

   For more information about environments, see [Deploying into AWS accounts and VPCs](deploy-environments.md) and [Creating an environment](deploy-environments-creating-environment.md).

1. (Optional) Change the IAM role associated with the action. You might want to change the role if it contains the wrong set of permissions for the action.

    To change the role:

   1. In the **What's in *my-environment* ?** box, and choose the vertical ellipsis icon (![\[Ellipsis.\]](http://docs.aws.amazon.com/codecatalyst/latest/userguide/images/flows/elipsis.png)).

   1. Choose one of the following:
      +  **Switch role**. Choose this option to change the IAM role used by this action, and only this action. Other actions continue to use the default IAM role specified in their associated environment. For more information, see [Changing the IAM role of an action](deploy-environments-switch-role.md).
      +  **Edit environment**. Choose this option to change the default IAM role listed in your environment. When you choose this option, your action—and any other action associated with the same environment—begins using the new default IAM role.
**Important**  
Use caution when updating the default IAM role. Changing the role might lead to action failures if the permissions in the role are not sufficient for all actions that share the environment.

1. (Optional) Choose **Validate** to validate the workflow's YAML code before committing.

1. Choose **Commit**, enter a commit message, and choose **Commit** again.

------
#### [ YAML ]

**To associate an environment with a workflow action using the YAML editor**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

1. Choose the name of your workflow. You can filter by the source repository or branch name where the workflow is defined, or filter by workflow name or status.

1. Choose **Edit**.

1. Choose **YAML**.

1. In the workflow action that you want to associate with an environment, add code similar to the following:

   ```
   action-name:
     Environment:
       Name: environment-name
   ```

   For more information, see the [Action types](workflows-actions.md#workflows-actions-types) topic. This topic has links into the documentation for each action, including its YAML reference.

1. (Optional) If you want the action to use a different role from the default IAM role that's listed in the environment, add a `Connections:` section that includes the role you want to use. For more information, see [Changing the IAM role of an action](deploy-environments-switch-role.md).

1. (Optional) Choose **Validate** to validate the workflow's YAML code before committing.

1. Choose **Commit**, enter a commit message, and choose **Commit** again.

------

## Step 2: Populate the deployment activity page
<a name="deploy-environments-add-app-to-environment-run"></a>

After associating an environment with a workflow action, you can populate the **Deployment activity** and **Deployment target** pages in the **Environments** section of the CodeCatalyst console with deployment information. Use the following instructions to populate these pages.

**Note**  
Only a few actions support having their deployment information displayed in the CodeCatalyst console. For more information, see [Which actions support having their deployment information displayed in CodeCatalyst?](deploy-environments.md#deploy-environments-supported-targets).

**To add deployment information to CodeCatalyst**

1. If a workflow run did not start automatically when you committed your changes in [Step 1: Associate the environment with a workflow action](#deploy-environments-add-app-to-environment-assoc), manually start a run as follows:

   1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

   1. Choose the name of your workflow. You can filter by the source repository or branch name where the workflow is defined, or filter by workflow name or status.

   1. Choose **Run**.

   The workflow run starts a new deployment, which causes CodeCatalyst to add deployment information to CodeCatalyst.

1. Verify that deployment activity was added to the CodeCatalyst console:

   1. In the navigation pane, choose **CI/CD**, and then choose **Environments**.

   1. Choose your environment (for example, `Production`).

   1. Choose the **Deployment activity** tab, and verify that a deployment appears with a **Status** of **SUCCEEDED**. This indicates that a workflow run successfully deployed your application resources.

   1. Choose the **Deployment targets** tab, and verify that your application resources appear.

# Associating a VPC with an environment
<a name="deploy-environments-associate-vpc"></a>

When an action is configured with an environment that has a VPC connection, the action will run connected to the VPC, adhering to the network rules and access resources specified by the associated VPC. The same VPC connection can be used by one or more environments.

Use the following instructions to associate a VPC connection with an environment.

**To associate a VPC connection with an environment**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Environments**.

1. Choose your environment (for example, `Production`).

1. Choose the **Environment properties** tab.

1. Choose **Manage VPC connection**, choose your desired VPC connection, and choose **Confirm**. This associates your selected VPC connection with this environment.
**Note**  
If the VPC connection that you want to use is not listed, it might be because it includes an AWS account connection that's not allowed in your project. For more information, see [Configuring project-restricted account connections](https://docs.aws.amazon.com/codecatalyst/latest/adminguide/managing-accounts-restriction.html) in the *Amazon CodeCatalyst Administrator Guide*.

For more information, see [ Managing Amazon Virtual Private Clouds](https://docs.aws.amazon.com/codecatalyst/latest/adminguide/managing-vpcs.html) in the *CodeCatalyst Administrator Guide*.

# Associating an AWS account with an environment
<a name="deploy-environments-associate-account"></a>

Use the following instructions to associate an AWS account with an environment. When you associate an AWS account with an environment, workflow actions that are assigned the environment will be able to connect to the AWS account.

For more information about account connections, see [Allowing access to AWS resources with connected AWS accounts](ipa-connect-account.md).

**Before you begin**

You need the following:
+ An AWS account connection that includes the IAM roles your workflow action will need to access AWS. For information about creating an account connection, see [Allowing access to AWS resources with connected AWS accounts](ipa-connect-account.md). You can use a maximum of one account connection per environment.
+ One of the following CodeCatalyst roles: **Space administrator** or **Project administrator**. For more information, see [Granting users project permissions](projects-members.md).

**To associate an AWS account with an environment**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Environments**.

1. Choose your environment (for example, `Production`).

1. Choose **Edit environment**.

1. Under **Environment properties**, in the **AWS account connection - optional** drop-down list, choose your desired AWS account.

   If the AWS account connection that you want to use is not listed, it might be because it's not allowed in your project. For more information, see [Configuring project-restricted account connections](https://docs.aws.amazon.com/codecatalyst/latest/adminguide/managing-accounts-restriction.html) in the *Amazon CodeCatalyst Administrator Guide*.

1. In **Default IAM role**, choose the IAM role you want to associate with this environment. Workflow actions that are assigned this environment will inherit this IAM role, and will be able to use it to connect to services and resources in your AWS account.

   If the IAM role that you want to use as the default is not listed, it might be because you have not added it to your AWS account connection yet. To add an IAM role to an account connection, see [Adding IAM roles to account connections](ipa-connect-account-addroles.md).

# Changing the IAM role of an action
<a name="deploy-environments-switch-role"></a>

By default, when you associate an [environment](deploy-environments.md) with a workflow [action](workflows-actions.md), the action inherits the default IAM role specified in the environment. You can change this behavior so that the action uses a different role. You might want an action to use a different role if the default IAM role is missing the permissions that the action needs to operate in the AWS cloud.

To assign a different IAM role to an action, you can use the **Switch role** option in the visual editor or the `Connections:` property in the YAML editor. The new role overrides the default IAM role specified in the environment, allowing you to keep the default IAM role as-is. You might want to keep the default IAM role as-is if there are other actions that use it.

Use the following instructions to configure an action to use a different IAM role from the one specified in its environment.

------
#### [ Visual ]

**To assign a different IAM role to an action (visual editor)**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

1. Choose the name of your workflow. You can filter by the source repository or branch name where the workflow is defined, or filter by workflow name or status.

1. Choose **Edit**.

1. Choose the box that represents the action whose IAM role you want to update.

1. Choose the **Configuration** tab.

1. In the **What's in *my-environment* ?** box, choose the vertical ellipsis icon (![\[Ellipsis.\]](http://docs.aws.amazon.com/codecatalyst/latest/userguide/images/flows/elipsis.png)).

1. Choose **Switch role**.

1. In the **Switch role** dialog box, in the **IAM role** drop-down list, choose the IAM role that you want the action to use. This role will override the default IAM role in the environment. If the role you want to use is not in the list, make sure you've added it to your space. For more information, see [Adding IAM roles to account connections](ipa-connect-account-addroles.md).

   The chosen role now appears in the **What's in *my-environment*?** box along with a **Defined in workflow** badge. The role also appears in the workflow definition file, in the `Connections:` section.

1. (Optional) Choose **Validate** to validate the workflow's YAML code before committing.

1. Choose **Commit**, enter a commit message, and choose **Commit** again.

------
#### [ YAML ]

**To assign a different IAM role to an action (YAML editor)**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

1. Choose the name of your workflow. You can filter by the source repository or branch name where the workflow is defined, or filter by workflow name or status.

1. Choose **Edit**.

1. Choose **YAML**.

1. In the workflow action where you want to use a different IAM role, add a `Connections:` section, similar to the following:

   ```
   action-name:
     Environment:
       Name: environment-name
       Connections: 
         - Name: account-connection-name
           Role: iam-role-name
   ```

   In the preceding code, replace *account-connection-name* with the name of the [account connection](ipa-connect-account.md) that contains the IAM role, and replace *iam-role-name* with the name of the IAM role that you want the action to use. This role will override the default IAM role in the environment. Make sure you've added the role to your space. For more information, see [Adding IAM roles to account connections](ipa-connect-account-addroles.md).

   For more information, see the [Action types](workflows-actions.md#workflows-actions-types) topic. This topic has links into the documentation for each action, including its YAML reference.

------

# Displaying the app URL in the workflow diagram
<a name="deploy-app-url"></a>

If your workflow deploys an application, you can configure Amazon CodeCatalyst to display the application's URL as a clickable link. This link appears in the CodeCatalyst console, inside the action that deployed it. The following workflow diagram shows the **View App** URL appearing at the bottom of an action.

![\[View app URL\]](http://docs.aws.amazon.com/codecatalyst/latest/userguide/images/deploy/view-app-url.png)


By making this URL clickable in the CodeCatalyst console, you can quickly verify your application deployment.

**Note**  
The app URL is not supported with the **Deploy to Amazon ECS** action.

To enable this feature, add an output variable to your action with a name that contains `appurl`, or `endpointurl`. You can use a name with or without a joining dash (`-`), underscore (`_`), or space (` `). The string is case-insensitive. Set the variable's value to the `http` or `https` URL of your deployed application.

**Note**  
If you're updating an existing output variable to include the `app url`, or `endpoint url` string, update all references to this variable to use the new variable name.

For detailed steps, see one of the following procedures:
+ [To display the app URL in the "AWS CDK deploy" action](#deploy-app-url-cdk)
+ [To display the app URL in the "Deploy CloudFormation stack" action](#deploy-app-url-cfn)
+ [To display the app URL in all other actions](#deploy-app-url-other)

When you've finished configuring the URL, verify that it appears as expected by following these instructions:
+ [To verify that the application URL was added](#deploy-app-url-verify)<a name="deploy-app-url-cdk"></a>

**To display the app URL in the "AWS CDK deploy" action**

1. If you're using the **AWS CDK deploy** action, add a `CfnOutput` construct (which is a key-value pair) in your AWS CDK application code:
   + The key name must contain `appurl`, or `endpointurl`, with or without a joining dash (`-`), underscore (`_`), or space (` `). The string is case-insensitive.
   + The value must be the `http` or `https` URL of your deployed application.

   For example, your AWS CDK code might look like this:

   ```
   import { Duration, Stack, StackProps, CfnOutput, RemovalPolicy} from 'aws-cdk-lib';
   import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
   import * as s3 from 'aws-cdk-lib/aws-s3';
   import { Construct } from 'constructs';
   import * as cdk from 'aws-cdk-lib';
   export class HelloCdkStack extends Stack {
     constructor(scope: Construct, id: string, props?: StackProps) {
       super(scope, id, props);
       const bucket = new s3.Bucket(this, 'amzn-s3-demo-bucket', {
         removalPolicy: RemovalPolicy.DESTROY,
       });
       new CfnOutput(this, 'APP-URL', {
         value: https://mycompany.myapp.com,
         description: 'The URL of the deployed application',
         exportName: 'myApp',
       });
       ...
     }
   }
   ```

   For more information about the `CfnOutput` construct, see [interface CfnOutputProps](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.CfnOutputProps.html) in the *AWS Cloud Development Kit (AWS CDK) API Reference*.

1. Save and commit your code.

1. Proceed to [To verify that the application URL was added](#deploy-app-url-verify).<a name="deploy-app-url-cfn"></a>

**To display the app URL in the "Deploy CloudFormation stack" action**

1. If you're using the **Deploy CloudFormation stack** action, add an output to the `Outputs` section in your CloudFormation template or AWS SAM template with these characteristics:
   + The key (also called the logical ID) must contain `appurl`, or `endpointurl`, with or without a joining dash (`-`), underscore (`_`), or space (` `). The string is case-insensitive.
   + The value must be the `http` or `https` URL of your deployed application.

   For example, your CloudFormation template might look like this:

   ```
   "Outputs" : {
     "APP-URL" : {
       "Description" : "The URL of the deployed app",
       "Value" : "https://mycompany.myapp.com",
       "Export" : {
         "Name" : "My App"
       }
     }
   }
   ```

   For more information about CloudFormation outputs, see [Outputs](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/outputs-section-structure.html) in the *AWS CloudFormation User Guide*.

1. Save and commit your code.

1. Proceed to [To verify that the application URL was added](#deploy-app-url-verify).<a name="deploy-app-url-other"></a>

**To display the app URL in all other actions**

If you're using another action to deploy your application, such as the build action or **GitHub Actions**, do the following to have the app URL displayed.

1. Define an environment variable in the `Inputs` or `Steps` section of the action in the workflow definition file. The variable must have these characteristics:
   + The `name` must contain `appurl`, or `endpointurl`, with or without a joining dash (`-`), underscore (`_`), or space (` `). The string is case-insensitive.
   + The value must be the `http` or `https` URL of your deployed application.

   For example, a build action might look like this:

   ```
   Build-action:
     Identifier: aws/build@v1
     Inputs:
       Variables:
         - Name: APP-URL
           Value: https://mycompany.myapp.com
   ```

   ...or this:

   ```
   Actions:
     Build:
       Identifier: aws/build@v1
       Configuration:    
         Steps:
           - Run: APP-URL=https://mycompany.myapp.com
   ```

   For more information about defining environment variables, see [Defining a variable](workflows-working-with-variables-define-input.md).

1. Export the variable.

   For example, your build action might look like this:

   ```
   Build-action:
     ...
     Outputs:
       Variables:
         - APP-URL
   ```

   For information about exporting variables, see [Exporting a variable so that other actions can use it](workflows-working-with-variables-export-input.md).

1. (Optional) Choose **Validate** to validate the workflow's YAML code before committing.

1. Choose **Commit**, enter a commit message, and choose **Commit** again.

1. Proceed to [To verify that the application URL was added](#deploy-app-url-verify).<a name="deploy-app-url-verify"></a>

**To verify that the application URL was added**
+ Start a workflow run, if it hasn't started automatically. The new run should have the app URL displayed as a clickable link in its workflow diagram. For more information about starting runs, see [Starting a workflow run manually](workflows-manually-start.md). 

# Removing a deployment target
<a name="deploy-remove-target"></a>

You can remove a deployment target such as an Amazon ECS cluster or CloudFormation stack from the **Deployment targets** page in the CodeCatalyst console.

**Important**  
When you remove a deployment target, it is removed from the CodeCatalyst console, but remains available in the AWS service that hosts it (if it still exists).

Consider removing a deployment target if the target has become stale in CodeCatalyst. Targets might become stale if:
+ You deleted the workflow that deployed to the target.
+ You changed the stack or cluster that you're deploying to. 
+ You deleted the stack or cluster from the CloudFormation or Amazon ECS service in the AWS console.

**To remove a deployment target**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Environments**.

1. Choose the name of the environment that contains the deployment target you want to remove. For information about environments, see [Deploying into AWS accounts and VPCs](deploy-environments.md).

1. Choose the **Deployment targets** tab.

1. Choose the radio button next to the deployment target you want to remove.

1. Choose **Remove**.

   The target is removed from the page.

# Tracking deployment status by commit
<a name="track-changes"></a>

At any time in the development lifecycle, it's important to know the deployment status of specific commits, such as bug fixes, new features, or other impactful changes. Consider the following scenarios in which deployment status tracking capability is helpful to development teams:
+ As a developer, you've made a fix to address a bug and you want to report the status of its deployment across your team's deployment environments.
+ As a release manager, you want to view a list of deployed commits to track and report their deployment status.

CodeCatalyst provides a view you can use to determine at a glance where individual commits or changes have been deployed, and to which environment. This view includes: 
+ A list of commits.
+ The status of deployments that include the commits.
+ The environments in which the commits are successfully deployed.
+ The status of any tests run against the commits in your CI/CD workflow.

The following procedure details how to navigate to and use this view to track changes in your project.

**Note**  
Tracking deployment status by commit is only supported with [CodeCatalyst repositories](source.md). You cannot use this feature with a [GitHub repository, Bitbucket repository, or GitLab project repository](extensions.md).

**To track deployment status by commit**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Change tracking**.

1. In the two dropdown lists at the top of the main pane, choose the source repository and branch that contain the commits whose release status you want to view.

1. Choose **View changes**.

   A list of commits appears.

   For each commit, you can view the following:
   + Commit information such as ID, author, message, and when it was committed. For more information, see [Store and collaborate on code with source repositories in CodeCatalystStore and collaborate on code with source repositories](source.md).
   + The status of deployments to each environment. For more information, see [Deploying into AWS accounts and VPCs](deploy-environments.md).
   + Test and code coverage results. For more information, see [Testing with workflowsTesting with workflows](test-workflow-actions.md).
**Note**  
Software Composition Analysis (SCA) results are not displayed.

1. (Optional) To view more information about the changes related to a specific commit, including the latest deployment and detailed code coverage and unit test information, choose **View details** for that commit.

# Viewing the deployment logs
<a name="deploy-deployment-logs"></a>

You can view logs related to specific deploy actions to troubleshoot problems in Amazon CodeCatalyst.

You can view logs starting from a [workflow](workflow.md), or an [environment](deploy-environments.md).

**To view the logs of a deploy action starting from a workflow**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

1. Choose the name of your workflow. You can filter by the source repository or branch name where the workflow is defined, or filter by workflow name or status.

1. Choose **Runs**.

1. Choose the workflow run that deployed your application.

1. In the workflow diagram, choose the action whose logs you want to view.

1. Choose the **Logs** tab and expand the sections to reveal the log messages.

1. To view more logs, choose the **Summary** tab, and then choose **View in CloudFormation** (if it's available) to view more logs there. You may need to sign in to AWS.

**To view the logs of a deploy action starting from an environment**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Environments**.

1. Choose the environment into which your application was deployed.

1. In **Deployment activity**, find the **Workflow Run ID** column, and choose the workflow run that deployed your stack.

1. In the workflow diagram, choose the action whose logs you want to view.

1. Choose the **Logs** tab and expand the sections to reveal the log messages.

1. To view more logs, choose the **Summary** tab, and then choose **View in CloudFormation** (if it's available) to view more logs there. You may need to sign in to AWS.

# Viewing deployment information
<a name="deploy-view-deployment-info"></a>

You can view the following information about a deployment in Amazon CodeCatalyst:
+ Deployment activity, including the deployment status, start time, end time, history, and duration of events.
+ Stack name, AWS Region, last update time, and associated workflows.
+ Commits and pull requests.
+ Action-specific information, for example, CloudFormation events and outputs.

You can view deployment information starting from a [workflow](workflow.md), an [environment](deploy-environments.md), or a workflow [action](workflows-concepts.md#workflows-concepts-actions).

**To view deployment information starting from a workflow**
+ Go to the workflow run that deployed your application. For instructions, see [Viewing workflow run status and details](workflows-view-run.md). 

**To view deployment information starting from an environment**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Environments**.

1. Choose the environment where your stack was deployed, for example, `Production`.

1. Choose **Deployment activity** to view the deployment history of your stacks, the status of the deployments (for example, **SUCCEEDED** or **FAILED**), and other deployment-related information.

1. Choose **Deployment target** to view information about the stacks, clusters, or other targets deployed into the environment. You can view information such as the stack name, Region, provider, and identifier.

**To view deployment information starting from an action**

1. Open the CodeCatalyst console at [https://codecatalyst.aws/](https://codecatalyst.aws/).

1. Choose your project.

1. In the navigation pane, choose **CI/CD**, and then choose **Workflows**.

1. Choose the name of your workflow. You can filter by the source repository or branch name where the workflow is defined, or filter by workflow name or status.

1. In the workflow diagram, choose the workflow action that deployed your application. For example, you might choose **DeployCloudFormationStack**.

1. Review the contents in the right pane for action-specific deployment information. 