Lesson 2 of 5 AWS CodeDeploy

Deploying to Amazon EC2 and On-Premises Servers

Deployments to EC2 and on-premises servers are the most configurable CodeDeploy deployments. This lesson explains in-place and blue/green deployment types, the order of lifecycle events and what each is for, deployment configurations and minimum healthy hosts, and the interaction with load balancers and Auto Scaling groups.

Learning outcomes

After completing this lesson, you will be able to:

  • Distinguish between in-place and blue/green deployments for EC2 and explain the trade-offs.
  • Describe the order and purpose of the EC2 lifecycle events, including load balancer events.
  • Explain how deployment configurations and minimum healthy hosts control the pace and success of a deployment.
  • Explain how CodeDeploy handles Auto Scaling scale-out events and zonal deployments.

In-Place Deployments

In an in-place deployment, the application on each existing instance is stopped, the new revision is installed and the application is restarted. Instances are updated in batches according to the deployment configuration. If the deployment group has a load balancer, each instance is deregistered before it is updated and registered again afterwards, so users are not sent to an instance that is restarting. In-place deployments need no extra capacity and suit on-premises servers, which cannot be cloned automatically. Their weaknesses are reduced capacity during the deployment and a slower rollback, because rolling back means deploying the previous revision to every instance again.

Blue/Green Deployments

In a blue/green deployment, the existing instances (blue) keep serving traffic while CodeDeploy installs the revision on a replacement set (green). Green instances are provided in one of two ways: CodeDeploy automatically copies the Auto Scaling group, creating a new group with the same launch template and size, or the team provisions instances itself and identifies them by tags. After the revision is installed and the green instances pass health checks, CodeDeploy reroutes the load balancer to them, either immediately or after a manual approval within a wait period, and then terminates or keeps the original instances after a configurable wait.

Blue/green deployments require a load balancer, and they are available only for EC2, not on-premises servers. They provide full capacity throughout the deployment and a fast rollback: while the blue instances still exist, rollback reroutes traffic back to them without reinstalling anything.

In-place
TargetsExisting EC2 or on-premises instances
Capacity during deploymentReduced by the batch being updated
RollbackRedeploy the previous revision to each instance
Load balancerOptional
Extra costNone
Choose when On-premises servers or limited capacity budgets.
Blue/green
TargetsNew EC2 instances (copied Auto Scaling group or tagged instances)
Capacity during deploymentFull; old and new run side by side
RollbackReroute traffic to the original instances if not yet terminated
Load balancerRequired
Extra costTwo fleets for the duration
Choose when Minimal impact and the fastest rollback on EC2.

The following diagram shows the two fleets and the order of events.

An EC2 blue/green deployment. The blue instances keep serving traffic while CodeDeploy installs the revision on green instances, created by copying the Auto Scaling group or identified by tags. After green passes health checks, CodeDeploy reroutes the load balancer, immediately or after a manual approval, then keeps or terminates blue after a wait. Capacity stays full throughout, and while blue exists, rollback only reroutes traffic back.
Blue keeps serving until green is proven, and stays available for rollback.

Lifecycle Events

An EC2/On-premises deployment runs a fixed sequence of lifecycle events on each instance. Some are performed by the agent and cannot be scripted; others run the scripts mapped in the AppSpec hooks section. The order for an in-place deployment with a load balancer is shown below; the events in bold accept scripts.

  1. BeforeBlockTraffic, then BlockTraffic (deregistration from the load balancer), then AfterBlockTraffic.
  2. ApplicationStop: stops the running application. This script comes from the previously deployed revision, because the new revision has not been downloaded yet.
  3. DownloadBundle: the agent copies the revision to a temporary location on the instance.
  4. BeforeInstall: pre-installation tasks, such as backing up files or decrypting configuration.
  5. Install: the agent copies files to their destinations as defined in the files section.
  6. AfterInstall: configuration tasks, such as setting permissions or changing configuration files.
  7. ApplicationStart: starts the services stopped in ApplicationStop.
  8. ValidateService: verifies that the deployment succeeded, for example by calling a health endpoint.
  9. BeforeAllowTraffic, then AllowTraffic (registration with the load balancer), then AfterAllowTraffic.

In a blue/green deployment, the install events run on the green instances, and the traffic events run in two places: BeforeAllowTraffic, AllowTraffic and AfterAllowTraffic on the green instances, and BeforeBlockTraffic, BlockTraffic and AfterBlockTraffic on the blue instances when they are removed from the load balancer.

version: 0.0
os: linux
files:
  - source: /build
    destination: /opt/orders
file_exists_behavior: OVERWRITE
permissions:
  - object: /opt/orders
    owner: orders
    group: orders
    mode: "750"
hooks:
  ApplicationStop:
    - location: scripts/stop.sh
      timeout: 60
  AfterInstall:
    - location: scripts/configure.sh
      timeout: 120
      runas: root
  ApplicationStart:
    - location: scripts/start.sh
      timeout: 60
  ValidateService:
    - location: scripts/validate.sh   # exits non-zero if /health does not return 200
      timeout: 300

The following diagram shows the events in order and which accept scripts.

The lifecycle events of an in-place EC2 deployment with a load balancer, in order. The instance is deregistered (BeforeBlockTraffic, BlockTraffic, AfterBlockTraffic), the application is stopped (ApplicationStop, using the previous revision's script), the agent downloads and installs the bundle around the BeforeInstall and AfterInstall hooks, ApplicationStart and ValidateService run, and the instance is registered again (BeforeAllowTraffic, AllowTraffic, AfterAllowTraffic). BlockTraffic, DownloadBundle, Install and AllowTraffic are performed by the agent and accept no scripts.
In a blue/green deployment the install events run on green, and the traffic events on both fleets.

A broken ApplicationStop script

Because ApplicationStop runs the script from the previous revision, a broken stop script keeps failing every new deployment, even one that fixes the script. The remedy is to deploy with the option to ignore ApplicationStop failures (--ignore-application-stop-failures), after which the new, fixed script becomes the one used next time.

Put in order

EC2 lifecycle events

Exam skills 1.4.2 · 1.4.3

Put the lifecycle events of an in-place EC2 deployment in order.

Log in to try this activity Interactive activities are free with an account.

Deployment Configurations and Minimum Healthy Hosts

For EC2, a deployment configuration specifies the minimum healthy hosts, as a number or a percentage of the instances in the deployment group. CodeDeploy updates as many instances at a time as it can while keeping at least that many healthy. An instance is healthy if its last deployment succeeded or has not yet been attempted. If the number of healthy instances would fall below the minimum, the deployment fails. The predefined configurations are summarised below.

ConfigurationBehaviourMinimum healthy hosts
CodeDeployDefault.AllAtOnceUpdates every instance at once; succeeds if at least one instance succeeds0
CodeDeployDefault.HalfAtATimeUpdates up to half of the instances at a time50%
CodeDeployDefault.OneAtATimeUpdates one instance at a time; fails if any instance fails, except possibly the lastAll but one

A custom configuration can set any value, such as 75%. For blue/green deployments, the configuration applies to the green instances. A zonal configuration deploys to one Availability Zone at a time with an optional monitoring duration after each zone, and a first-zone monitor duration, which limits a faulty deployment to a single zone while alarms are watched. This mirrors the way AWS deploys its own services.

Fill in the value

Minimum healthy hosts

Exam skills 1.4.4

Work out how many instances CodeDeploy updates at once.

Log in to try this activity Interactive activities are free with an account.

Auto Scaling Group Integration

When a deployment group includes an Auto Scaling group, CodeDeploy adds a launch lifecycle hook to it. A newly launched instance waits in the Pending:Wait state while CodeDeploy deploys the last successful revision to it, and enters service only when that deployment succeeds. This keeps new instances consistent with the rest of the fleet.

A scale-out event during a deployment can create inconsistency: the new instance receives the previous successful revision while the deployment is installing the new one. CodeDeploy detects this and starts a follow-on deployment to bring such instances up to date. Teams also suspend scaling processes during deployments or use blue/green deployments to avoid the problem. If the lifecycle hook is removed manually or the CodeDeploy service role lacks Auto Scaling permissions, new instances enter service without the application, which appears as healthy-looking instances that fail load balancer health checks.

Worked example

Choosing a Strategy for a Fleet

A web application runs on 12 EC2 instances in an Auto Scaling group behind an Application Load Balancer. The business requires that capacity never drops below 100% during a release and that a faulty release can be reversed within minutes.

An in-place deployment would reduce capacity by the batch being updated, and its rollback would reinstall the previous revision on each instance, which takes as long as a deployment. A blue/green deployment that copies the Auto Scaling group meets both requirements: the 12 blue instances serve traffic while 12 green instances are prepared, traffic moves only after green passes ValidateService and load balancer health checks, and the blue instances are kept for one hour before termination. If the error-rate alarm fires during that hour, automatic rollback reroutes traffic to the blue instances.

Check yourself

A deployment to 10 instances with CodeDeployDefault.HalfAtATime fails on six instances. What is the result?

Show answer

The deployment fails, because fewer than the minimum healthy hosts (50%, five instances) remain healthy. CodeDeploy stops the deployment and, if configured, rolls back.

Exam Tips

Remember for the exam

  • Blue/green for EC2 needs a load balancer, keeps full capacity and rolls back by rerouting traffic; in-place works on-premises and needs no extra instances.
  • ApplicationStop runs the previous revision's script; use --ignore-application-stop-failures when that script is broken.
  • Lifecycle order: ApplicationStop, DownloadBundle, BeforeInstall, Install, AfterInstall, ApplicationStart, ValidateService, with Block/AllowTraffic events around them when a load balancer is used.
  • Minimum healthy hosts decides how many instances update at once and when the deployment fails; zonal configurations deploy one Availability Zone at a time.
  • CodeDeploy's Auto Scaling lifecycle hook deploys the last successful revision to new instances before they enter service.