Skip to main content

How to Deploy Application Code From S3 Using AWS CodeDeploy

In a previous post, we discussed the top 5 deployment tools for AWS. Out of them, AWS CodeDeploy is a tool which is especially designed for AWS. It is a new service by Amazon Web Services which was launched during the Re:Invent 2014 conference held in Las Vegas last November. The primary focus of AWS CodeDeploy is to automate the deployment process, minimize downtime, easy adoption, and centralized control.

In this post, we will see how you can leverage AWS CodeDeploy to deploy your latest application code to your EC2 instances. AWS CodeDeploy deploys applications from Amazon S3 or GitHub. We will focus on deploying the application using Amazon S3 here.

Before starting, please go through the terminology used across this post which is specific to AWS CodeDeploy:

  • Application: Unique name provided to your application.
  • Revision: A combination of archive files with Application Specification File (AppSec). The archive file comprises source code, deployment scripts, web pages, executables, etc. Revisions are stored in S3 or GitHub repositories.
  • Deployment Configuration: a set of deployment rules and deployment success and failure conditions that AWSCodeDeploy uses during a deployment.
  • Deployment Group: a set of deployment targets, i.e.: individual instances or autoscaled instances. Deployment on individual instances works based on tags.

Deploying code from S3 to CodeDeploy: application prerequisites

Operating System: Amazon Linux 2014.09.1
Application Type: Simple HTML, CSS, JS application
Region: N. Virginia (us-east-1)

Pre-requisites

We need to have two IAM roles: a Service Role and an Instance Profile Role.

Service Role: Service Role access will be granted to AWS CodeDeploy to read through your EC2 instance tags. For auto-scaled instances, it looks for your autoscaling name tags. Service Role Policy is as follows:

{
"Version": "2012-10-17",
"Statement": [
   {
     "Action": [
       "autoscaling:PutLifecycleHook",
       "autoscaling:DeleteLifecycleHook",
       "autoscaling:RecordLifecycleActionHeartbeat",
       "autoscaling:CompleteLifecycleAction",
       "autoscaling:DescribeAutoscalingGroups",
       "autoscaling:PutInstanceInStandby",
       "autoscaling:PutInstanceInService",
       "ec2:Describe*"
     ],
     "Effect": "Allow",
     "Resource": "*"
   }
]
}

Once the IAM role is created, you need to establish a trusted relationship for this role with AWSCodeDeploy. Modify trust relationship policy for this particular role and set it to below mentioned policy :

{
"Version": "2012-10-17",
"Statement": [
    {
    "Sid": "",
    "Effect": "Allow",
    "Principal": {
    "Service": [
        "codedeploy.us-east-1.amazonaws.com",
        "codedeploy.us-west-2.amazonaws.com"
    ]
    },
    "Action": "sts:AssumeRole"
    }
]
}

Instance Profile Role: EC2 instances needs to be launched with proper permissions to access files from S3 buckets.

{
    "Version": "2012-10-17",
    "Statement": [
    {
        "Action": [
            "s3:Get*",
            "s3:List*"
        ],
        "Effect": "Allow",
        "Resource": "*"
    }
    ]
}

Building Deployment Revision

To build a deployment revision for S3, you need to create a compressed archive file with your application code and an application specification file (AppSpec). AppSpec is the heart of CodeDeploy and is written in YAML. AppSpec defines how the application code will be deployed on deployment targets and which deployment lifecycle event hooks to run in response to various deployment lifecycle events. It should be in the root of an application source code’s directory structure.

High-Level Structure of AppSpec File:

version: 0.0
os: operating-system-name
files: source-destination-files-mappings
permissions: permissions-specifications
hooks: deployment-lifecycle-event-mappings

In the structure above, you can find the following fields:
Version:  the version of your application
OS: Operating system of your deployment targets, i.e.: Linux or Windows
Files: name of the files copied to the deployment target
Permissions: how permissions are applied to files copied to the deployment target
Hooks: scripts to run at specific deployment lifecycle events during the deployment. The available event hooks are:

  • ApplicationStop: events to be performed when the application is stopped
  • DownloadBundle: occurs when CodeDeploy agent downloads bundle from S3 bucket
  • BeforeInstall: occurs before AWSCodeDeploy starts deployment of application code to the deployment target
  • Install: AWSCodeDeploy copies files to deployment targets
  • AfterInstall: occurs once files are copied and installed to deployment targets
  • ApplicationStart: occurs just before your application revision is started on the deployment target
  • ValidateService: occurs after the service has been validated

The sample AppSpec File used for this example deployment is as below:

version: 0.0
os: linux
files:
   - source: /
     destination: /var/www/html
permissions:
   - object: /var/www/html
     pattern: "**"
     owner: apache
     group: apache
     mode: 755
     type:
       - file
hooks:
   BeforeInstall:
   - location: Scripts/installapache.sh
     runas: root
   - location: Scripts/startapache.sh
     runas: root
   AfterInstall:
   - location: Scripts/restartapache.sh
     runas: root

The Sample AWSCodeDeploy application used for this blog post is available over here.

Creating the CodeDeploy Application and Performing Deployment

1. Launch an EC2 instance with the Instance Profile role created before, a tag that you like (e.g. Environment = Production or Name = CodeDeployDemo) and with the following user data :

sudo yum update
sudo yum install aws-cli
cd /home/ec2-user
aws s3 cp s3://aws-codedeploy-us-east-1/latest/install . --region us-east-1
chmod +x ./install
sudo ./install auto

2. Go back to the AWS Management Console and select the “CodeDeploy” service.
AWSCodeDeploy Getting Started

Click on Get Started Now to create your first application and deployment group. It provides you two options:

  • Sample Deployment allows you to deploy a sample WordPress application on EC2 instances.
  • Custom Deployment allows you to deploy your application on existing EC2 instances.

AWSCodeDeploy Welcome Screen
We will pick with the Custom Deployment model.
3. Create your application
A CodeDeploy application helps you to create deployment groups and to identify deployment targets (EC2 instances) on which a particular revision is applied.
To create an application, you need to provide:

  • Application Name: suitable name for your CodeDeploy application
  • Deployment Group Name: name provided to your deployment group on which you will be deploying your application
  • Amazon EC2 tags: specified key-value pair basis on which deployment targets are identified. For auto-scaling, you need to provide an auto-scaling group name.
  • Deployment Configuration: Desired deployment configuration. This determines how the application will be deployed on EC2 instances. There are three possible options i.e., CodeDeployDefault.AllAtOnce, CodeDeployDefault.HalfAtOnce, CodeDeployDefault.OnceAtOnce.
  • Service Role: This is the service role created by you during pre-requisites step 1.
AWS CodeDeploy Application Creation

AWS CodeDeploy Application Search by Amazon EC2 TagsOnce all the necessary details are filled up, click on “Create Application” and move towards creating new deployments and publishing new revisions.
4. Create new deployment
Once the application is created, it is time to create a new deployment which will deploy a revision to deployment targets.
To create a deployment, go to that application and select deploy new revision.
AWSCodeDeploy How to Deploy your Application Screen

For a new deployment, we need to pass:

  • Application Name: name of the application you created in a previous step.
  • Deployment Group: select the deployment group you created in a previous step.
  • Revision Type: whether deployment code is available at S3 or GitHub
  • Revision Location: S3/GitHub path of the deployment code
  • Deployment Description: Description of this deployment
  • Deployment Config: Desired deployment configuration. This determines how the application will be deployed on EC2 instances. There are three possible options: CodeDeployDefault.AllAtOnce, CodeDeployDefault.HalfAtOnce, CodeDeployDefault.OnceAtOnce.
AWSCodeDeploy Create New Deployment Screen

AWSCodeDeploy Deployment Creation File Type Drop Down
That’s it. Deployment process has started and you can monitor the deployment process on the next screen.
AWSCodeDeploy Deployments Creation Progress
The deployment process goes from Created to In Progress to Succeeded.
AWSCodeDeploy Successful Completion
Once the deployment process is completed, you can go back and view your application.
If you used the above application, you will see something like this:
Sample AWSCodeDeploy Application

Re-Deploying Application with the latest revision

Deploying your latest revision is very easy. All you need to do is to build a compressed archive file (sample new build archive file) and put it into S3 bucket. Once done, go back to your application and create new deployment where you need to pass the latest S3 archive file path as revision location.

A new revision of sample application used for this post is available over here.
New AWSCodeDeploy Deployment Creation
Now, initiate the deployment procedure and new application code will be deployed to your instances.
AWSCodeDeploy Successful Deployment
Once done, go back to your browser and browse the application using the public IP address of your instance.
Updated AWSCodeDeploy Application

Limitations of AWS CodeDeploy

  • Only available for N.Virginia and Oregon region.
  • Existing running instances without IAM roles cannot use AWS CodeDeploy. You need to re-launch them using Instance Profile IAM role created above under Pre-requisites section.

Avatar

Written by

Sanket Dangi

Head of Managed Services at REAN Cloud. Before joining REAN Cloud, I was CEO and Founder of StraightArc Solutions which was later acquired by REAN Cloud.I started my career working on cloud computing. Loves to talk about DevOps, System Administration, Scalability, High Availability, Disaster Recovery and Cloud Security. Apart from work, I love to meet people, travel and watch sports.

Related Posts

Sam Ghardashem
Sam Ghardashem
— May 15, 2019

Aviatrix Integration of a NextGen Firewall in AWS Transit Gateway

Learn how Aviatrix’s intelligent orchestration and control eliminates unwanted tradeoffs encountered when deploying Palo Alto Networks VM-Series Firewalls with AWS Transit Gateway.Deploying any next generation firewall in a public cloud environment is challenging, not because of the f...

Read more
  • AWS
Joe Nemer
Joe Nemer
— May 3, 2019

AWS Config Best Practices for Compliance

Use AWS Config the Right Way for Successful ComplianceIt’s well-known that AWS Config is a powerful service for monitoring all changes across your resources. As AWS Config has constantly evolved and improved over the years, it has transformed into a true powerhouse for monitoring your...

Read more
  • AWS
  • Compliance
Avatar
Francesca Vigliani
— April 30, 2019

Cloud Academy is Coming to the AWS Summits in Atlanta, London, and Chicago

Cloud Academy is a proud sponsor of the 2019 AWS Summits in Atlanta, London, and Chicago. We hope you plan to attend these free events that bring the cloud computing community together to connect, collaborate, and learn about AWS. These events are all about learning. You can learn how t...

Read more
  • AWS
  • AWS Summits
Paul Hortop
Paul Hortop
— April 2, 2019

How to Monitor Your AWS Infrastructure

The AWS cloud platform has made it easier than ever to be flexible, efficient, and cost-effective. However, monitoring your AWS infrastructure is the key to getting all of these benefits. Realizing these benefits requires that you follow AWS best practices which constantly change as AWS...

Read more
  • AWS
  • Monitoring
Joe Nemer
Joe Nemer
— April 1, 2019

AWS EC2 Instance Types Explained

Amazon Web Services’ resource offerings are constantly changing, and staying on top of their evolution can be a challenge. Elastic Cloud Compute (EC2) instances are one of their core resource offerings, and they form the backbone of most cloud deployments. EC2 instances provide you with...

Read more
  • AWS
  • EC2
Avatar
Nitheesh Poojary
— March 26, 2019

How DNS Works – the Domain Name System (Part One)

Before migrating domains to Amazon's Route53, we should first make sure we properly understand how DNS worksWhile we'll get to AWS's Route53 Domain Name System (DNS) service in the second part of this series, I thought it would be helpful to first make sure that we properly understand...

Read more
  • AWS
Avatar
Stuart Scott
— March 14, 2019

Multiple AWS Account Management using AWS Organizations

As businesses expand their footprint on AWS and utilize more services to build and deploy their applications, it becomes apparent that multiple AWS accounts are required to manage the environment and infrastructure.  A multi-account strategy is beneficial for a number of reasons as ...

Read more
  • AWS
  • Identity Access Management
Avatar
Sanket Dangi
— February 11, 2019

WaitCondition Controls the Pace of AWS CloudFormation Templates

AWS's WaitCondition can be used with CloudFormation templates to ensure required resources are running.As you may already be aware, AWS CloudFormation is used for infrastructure automation by allowing you to write JSON templates to automatically install, configure, and bootstrap your ...

Read more
  • AWS
  • CloudFormation
Badrinath Venkatachari
Badrinath Venkatachari
— February 1, 2019

10 Common AWS Mistakes & How to Avoid Them

Massive migration to the public cloud is changing architecture patterns, operating principles, and governance models. That means new approaches are vital to get a handle on soaring cloud spend. Because the cloud’s short-term billing cycles call for financial discipline, you must empower...

Read more
  • AWS
  • Operations
Avatar
Andrew Larkin
— January 24, 2019

The 9 AWS Certifications: Which is Right for You and Your Team?

As companies increasingly shift workloads to the public cloud, cloud computing has moved from a nice-to-have to a core competency in the enterprise. This shift requires a new set of skills to design, deploy, and manage applications in cloud computing.As the market leader and most ma...

Read more
  • AWS
  • AWS Certifications
Avatar
Andrew Larkin
— January 15, 2019

2018 Was a Big Year for Content at Cloud Academy

As Head of Content at Cloud Academy I work closely with our customers and my domain leads to prioritize quarterly content plans that will achieve the best outcomes for our customers.We started 2018 with two content objectives: To show customer teams how to use Cloud Services to solv...

Read more
  • AWS
  • Azure
  • Cloud Computing
  • Google Cloud Platform
Avatar
Jeremy Cook
— November 29, 2018

Amazon Elastic Inference – GPU Acceleration for Faster Inferencing

“Add GPU acceleration to any Amazon EC2 instance for faster inference at much lower cost (up to 75% savings)”So you’ve just kicked off the training phase of your multilayered deep neural network. The training phase is leveraging Amazon EC2 P3 instances to keep the training time to a...

Read more
  • AWS
  • Elastic Inference
  • re:Invent 2018