In this module, you'll use AWS CodePipeline, AWS CodeBuild, and Amazon S3 to build a Continuous Delivery pipeline to automate a code deployment workflow for the Unicorn API.
CodePipeline orchestrates the steps to build, test, and deploy your code changes. Below is a screenshot of the CodePipeline you will build when have completed this module.
CodeBuild compiles source code, runs tests, and produces software packages that are ready to deploy to environments.
The Unicorn API buildspec.yml defines the commands used to build the project and the output artifacts.
version: 0.1
phases:
install:
commands:
- echo "nothing to do in install"
pre_build:
commands:
- echo "Installing dependencies - `pwd`"
build:
commands:
- echo "Starting build `date` in `pwd`"
- aws cloudformation package --template-file app-sam.yaml --s3-bucket $BUILD_OUTPUT_BUCKET --output-template-file app-sam-output.yaml
post_build:
commands:
- echo "build completed on `date`"
artifacts:
files:
- app-sam-output.yaml
discard-paths: yesFor the Unicorn API, the build command is the same CloudFormation package command used from the Serverless Application Model: Step 2, except that the S3 bucket has been externalized to an environment variable that you will define in the CodeBuild project.
As a reminder, the CloudFormation package command packages the local source code, uploads it to S3, and returns a new CloudFormation template that has been modified to use the S3 references as the CodeUri.
For the Unicorn API, the output artifact is a zip archive that includes only the app-sam-output.yaml file.
Each of the following sections provide an implementation overview and detailed, step-by-step instructions. The overview should provide enough context for you to complete the implementation if you're already familiar with the AWS Management Console or you want to explore the services yourself without following a walkthrough.
If you're using the latest version of the Chrome, Firefox, or Safari web browsers the step-by-step instructions won't be visible until you expand the section.
You will reuse the S3 Bucket that you created in Module 1: Serverless Application Model from the DevOps Workshop. If you have not completed this Module, please refer to the module instructions to create the S3 Bucket.
If you are unsure of your S3 Bucket's name, please follow the instructions below.
Step-by-step instructions (expand for details)
-
In the AWS Management Console choose Services then select S3 under Storage.
-
Browse the list of Buckets or use the search box to identify the S3 Bucket.
wildrydes-devops-yournamewas recommended as the Bucket name, however you may have chosen a different globaly unique name.
The CodePipeline that you will create in the next step will be triggered by updates to a deployment package in S3.
-
Change directory to
aws-serverless-workshops-master/DevOps/2_ContinuousDeliveryPipeline/unicorn-api. -
To create a deployment for this project, zip the contents of the
unicorn-apidirectory into a file namedunicorn-api.zip, which is your deployment package. If you are unsure how to zip the files in theunicorn-apidirectory, follow the instructions for Microsoft workstations here, and macOS workstations here.
Important
Zip the directory content, not the directory. The contents of the Zip file are available as the current working directory of the Lambda function. For example: /app-sam.yaml
-
In the AWS Management Console, choose Services then select S3 under Storage.
-
Browse the list of Buckets or use the search box to find the S3 bucket that you identified previously.
-
Choose Upload
-
Choose Add files, select the local copy of
unicorn-api.zipand then choose Upload in the bottom left corner of the dialog.
Use the IAM console to create a new role. Name it WildRydesUnicornApiCodeBuild and select AWS CodeBuild for the role type. You'll need to attach policies that grant your CodeBuild project permissions to write CloudWatchLogs, get and put objects from the CodePipeline S3 bucket, and put objects to the S3 bucket that you identified previously.
-
From the AWS Management Console, click on Services and then select IAM in the Security, Identity & Compliance section.
-
Select Roles in the left navigation bar and then choose Create New Role.
-
Select AWS CodeBuild for the role type.
Note: Selecting a role type automatically creates a trust policy for your role that allows AWS services to assume this role on your behalf. If you were creating this role using the CLI, AWS CloudFormation or another mechanism, you would specify a trust policy directly.
-
Choose Next Step.
-
Enter
WildRydesUnicornApiCodeBuildfor the Role name. -
Choose Create Role.
-
Type
WildRydesUnicornApiCodeBuildinto the filter box on the Roles page and choose the role you just created. -
On the Permissions tab, expand the Inline Policies section and choose the click here link to create a new inline policy.
-
Ensure Custom Policy is selected and choose Select.
-
Enter
WildRydesUnicornApiCodeBuildfor the Policy Name. -
Enter the following for the Policy Document. Make sure you replace
YOUR_BUCKET_NAMEwith the name you identified previously andYOUR_REGIONwith the name of the AWS Region that you chose in Module 1, for exampleus-east-1.{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:CreateLogGroup", "logs:CreateLogStream" ], "Resource": [ "arn:aws:logs:YOUR_REGION:::log-group:/aws/codebuild/wildrydes-unicorn-api" ] }, { "Effect": "Allow", "Action": [ "logs:PutLogEvents" ], "Resource": [ "arn:aws:logs:YOUR_REGION:::log-group:/aws/codebuild/wildrydes-unicorn-api/*" ] }, { "Effect": "Allow", "Action": [ "s3:GetObject", "s3:GetObjectVersion", "s3:PutObject" ], "Resource": [ "arn:aws:s3:::codepipeline-*/*" ] }, { "Effect": "Allow", "Action": [ "s3:PutObject" ], "Resource": [ "arn:aws:s3:::YOUR_BUCKET_NAME/*" ] } ] } -
Choose Apply Policy
You have now prepared the dependencies required to create a pipeline. Next, you'll create a CodePipeline with two stages, source and build.
-
From the AWS Management Console, click on Services and then select CodePipeline in the Developer Tools section.
-
Choose Create Pipeline.
-
Enter
wildrydes-unicorn-apifor the Pipeline name
The source stage is triggered automatically when a new version of the Unicorn API zip artifact is uploaded to S3. The source stage copies the archive from the S3 object, unzips the contents, rearchives the contents, and puts the archive to an encrypted CodePipeline S3 bucket.
-
Select
Amazon S3for the Source provider -
Enter
s3://YOUR_BUCKET_NAME/unicorn-api.zipfor the Amazon S3 location. Make sure you replaceYOUR_BUCKET_NAMEwith the name you identified previously. -
Choose Next step
The build stage is triggered automatically when a new version of the source stage is available. You will configure the build stage to use CodeBuild transform the source code into an artifact that is ready to be deployed.
-
Select
AWS CodeBuildfor the Build provider. -
Select
Create a new build projectunder Configure your project. -
Enter
wildrydes-unicorn-apifor the Project name. -
Select
Use an image maintained by AWS CodeBuildfor the Environment image. -
Select
Ubuntufor the Operating System. -
Select
Node.jsfor the Runtime. -
Select
aws/codebuild/nodejs:6.3.1for the Version. -
Select
Use the buildspec.yml in the source code root directoryfor the Build specification. -
Select
Choose an existing service role from your accountand enterWildRydesUnicornApiCodeBuildas the Role name. -
Expand the Advanced configuration section.
-
In the Environment variables section, enter
S3_BUCKETfor the variable Name and enter the name of the S3 bucket that you identified previously for the Value. -
Choose Save build project
-
Choose Next step
-
Select
No Deploymentas the Deployment provider -
Choose Next step
-
Choose Create role
-
A new browser window will open. Choose Create a new IAM Role for IAM Role, and enter
WildRydesUnicornApiCodePipelinefor the Role name. -
Choose Allow
-
The browser window will close, returning you to the CodePipeline UI with
WildRydesUnicornApiCodePipelinepopulated for the Role name. -
Choose Next Step
-
Review the details of the CodePipeline and choose Create pipeline
After you have created the wildrydes-unicorn-api CodePipeline, you will see a pipeline with two stages, Source and Build. When the pipeline completes successfully, each stage will be green, similar to the screenshot below.
The CodePipeline that you have created so far pulls source code updates from S3 and builds a deployable artifact using CodeBuild. Next, you will add a stage to deploy the app-sam-output.yaml CloudFormation Template to update a CloudFormation Stack using the same technique used from the command line in Module 1.
Use the IAM console to create a new role. Name it WildRydesUnicornApiCloudFormation and select AWS CloudFormation for the role type. You'll need to attach policies that grant your CloudFormation project permissions to access Lambda, DynamoDB and API Gateway.
-
From the AWS Management Console, click on Services and then select IAM in the Security, Identity & Compliance section.
-
Select Roles in the left navigation bar and then choose Create New Role.
-
Select AWS CloudFormation Role for the role type.
Note: Selecting a role type automatically creates a trust policy for your role that allows AWS services to assume this role on your behalf. If you were creating this role using the CLI, AWS CloudFormation or another mechanism, you would specify a trust policy directly.
-
Choose Next Step.
-
Enter
WildRydesUnicornApiCloudFormationfor the Role name. -
Choose Create Role.
-
Type
WildRydesUnicornApiCloudFormationinto the filter box on the Roles page and choose the role you just created. -
On the Permissions tab, choose the Attach Policy button to add a Managed Policy.
-
Enter
AWSLambdaFullAccessinto the filter box, select the checkbox to the left of the role, and clear the filter box -
Enter
AmazonDynamoDBFullAccessinto the filter box, select the checkbox to the left of the role, and clear the filter box -
Enter
AmazonAPIGatewayAdministratorinto the filter box, select the checkbox to the left of the role, and clear the filter box -
Choose Attach Policy.
-
On the Permissions tab, expand the Inline Policies section and choose the click here link to create a new inline policy.
-
Ensure Custom Policy is selected and choose Select.
-
Enter
WildRydesUnicornApiCloudFormationfor the Policy Name. -
Enter the following for the Policy Document.
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "cloudformation:CreateChangeSet", "cloudformation:ExecuteChangeSet", "iam:AttachRolePolicy", "iam:CreateRole", "iam:DeleteRole", "iam:DeleteRolePolicy", "iam:DetachRolePolicy", "iam:PutRolePolicy", "iam:GetRole" ], "Resource": [ "*" ] } ] } -
Choose Apply Policy
-
From the AWS Management Console, click on Services and then select CodePipeline in the Developer Tools section.
-
Choose
wildrydes-unicorn-apifrom the list of pipelines. -
Choose
Edit.
-
Choose
+Stageat the bottom of the pipeline. -
Enter
Prodfor the Stage Name. -
Choose
+ActionbelowProd.
-
In the Add action dialog, select
Deployfor the Action category. -
Enter
CreateChangeSetfor the Action name. -
Select
AWS CloudFormationfor the Deployment provider. -
Select
Create or replace a change setfor Action mode -
Enter
wildrydes-unicorn-apifor Stack name -
Enter
wildrydes-unicorn-api-changesetfor Change set name -
Enter
MyAppBuild::app-sam-output.yamlfor Template -
Select
CAPABILITY_IAMfor Capabilities -
Enter
WildRydesUnicornApiCloudFormationfor Role name -
Enter
MyAppBuildfor Input artifacts #1 -
Choose Add Action
-
Choose
+ActionbelowCreateChangeSet. -
In the Add action dialog, select
Deployfor the Action category. -
Enter
ExecuteChangeSetfor the Action name. -
Select
AWS CloudFormationfor the Deployment provider. -
Select
Execute a change setfor Action mode -
Enter
wildrydes-unicorn-apifor Stack name -
Enter
wildrydes-unicorn-api-changesetfor Change set name -
Choose Add Action
The pipeline should look like the following screenshot after adding the new Prod stage.
-
Scroll to the top of the pipeline and choose
Save pipeline changes -
Choose
Save and Continuewhen prompted by the Save Pipeline Changes dialog.
The addition of the deploy stage is complete. You will now validate that the Prod stage is working by updating the Unicorn API with a new method to remove a Unicorn from the Wild Ryde stables, and deploying the change using CodePipeline.
Using a text editor, open the app-sam.yaml file and append a new AWS::Serverless::Function Resource labeled DeleteFunction that has the following definition.
Note: whitespace is important in YAML files. Please verify that the configuration below is added with the same space indentation as the CloudFormation Resources in the app-sam.yaml file.
-
CodeUri is
app -
Runtime is
nodejs6.10 -
Handler is
delete.lambda_handler -
Event type is
Apiassociated to the/unicorns/{name}Path anddeleteMethod -
Environment variable named
TABLE_NAMEthat references theDynamodbTableResources for its value. -
Policies should mirror other Functions, however the Action to allow is
dynamodb:DeleteItem
If you are unsure of the syntax to add to app-sam.yaml please refer to the code snippet below.
app-sam.yaml additions to support Delete function (expand for details)
DeleteFunction:
Type: 'AWS::Serverless::Function'
Properties:
Runtime: nodejs6.10
CodeUri: app
Handler: delete.lambda_handler
Description: Remove Unicorn
Events:
UpdateApi:
Type: Api
Properties:
Path: /unicorns/{name}
Method: delete
Environment:
Variables:
TABLE_NAME: !Ref DynamodbTable
Policies:
- Version: '2012-10-17'
Statement:
- Effect: Allow
Resource: !Sub 'arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${DynamodbTable}'
Action:
- 'dynamodb:DeleteItem'-
Change directory to
aws-serverless-workshops-master/DevOps/2_ContinuousDeliveryPipeline/unicorn-api. -
To create a deployment for this project, zip the contents of the
unicorn-apidirectory into a file namedunicorn-api.zip, which is your deployment package. If you are unsure how to zip the files in theunicorn-apidirectory, follow the instructions for Microsoft workstations here, and macOS workstations here.
Important
Zip the directory content, not the directory. The contents of the Zip file are available as the current working directory of the Lambda function. For example: /app-sam.yaml
-
In the AWS Management Console, choose Services then select S3 under Storage.
-
Browse the list of Buckets or use the search box to find the S3 bucket that you identified previously.
-
Choose Upload
-
Choose Add files, select the local copy of
unicorn-api.zipand then choose Upload in the bottom left corner of the dialog.
-
From the AWS Management Console, click on Services and then select CodePipeline in the Developer Tools section.
-
Choose
wildrydes-unicorn-apifrom the list of pipelines. -
Observe that each stage's color will turn blue during execution and green on completion. Following the successful execution of all stages, the pipeline should look like the following screenshot.
-
In the AWS Management Console, click Services then select API Gateway under Application Services.
-
In the left nav, click on
wildrydes-unicorn-api. -
From the list of API resources, click on the
DELETElink under the/{name}resource. -
On the resource details panel, click the
TESTlink in the client box on the left side of the panel. -
On the test page, enter
Shadowfoxin the Path field. -
Click on the Test button.
-
Scroll to the top of the test page, and verify that on the right side of the panel that the Status code of the HTTP response is 200.
-
In the left nav, under the
wildrydes-unicorn-apiAPI click on Stages, expand the Prod stage, and choose theGETmethod under the/unicornsresource. -
At the top of the Prod Stage Editor panel, open the Invoke URL to a new browser window to display a list of Unicorns in the browser.
Shadowfoxshould not be in the list of Unicorns.
Congratulations! You have successfully created a Continuous Delivery Pipeline using CodePipeline to automate the deployment of the Unicorn API. In the next X-Ray Module, you will integrate AWS X-Ray to demonstrate how to troubleshoot the Unicorn API.

















