May 5, 2016

Automated Blue/Green deployment using Lambda and CloudFormation

Blue/Green deployment is a well-known method to deploy an application without any downtime. Performing DNS switch is one of the very common techniques to achieve this. Using DNS switch has a minor issue with DNS caching which might take some time for DNS change to be propagated.

Apart from DNS switch, AWS gives us two different options to switch the stacks. One is to have single ELB and swap it across auto-scaling group and another is switching the launch configuration of the auto-scaling group. Check the following presentation on various methods to achieve blue/green deployment in AWS.

I preferred swapping the ELB between auto-scaling groups. This method is fairly simple and also gives the advantage of no changes to DNS entry. Using Lambda it becomes quite easy to perform this task as a part of CFN, by just selecting the stack that needs to be live.

Following Lambda function gets the 3 parameters from the CFN (Live ASG, Non-Live ASG & ELB Name), attaches the ELB to Live ASG & detaches it from the Non-Live ASG.

Lambda function which performs the switch.

import boto3
from botocore.exceptions import ClientError
import json
import requests


def lambda_handler(event, context):
    print event
    print 'Request type is %s' % event['RequestType']
    if event['RequestType'] == 'Delete':
        sendResponse(event, context, 'SUCCESS', {})
        return 0

    live_asg = event['ResourceProperties']['LiveASG']
    non_live_asg = event['ResourceProperties']['NonLiveASG']
    elb_name = event['ResourceProperties']['ELBName']

    try:
        asg = boto3.client('autoscaling')
        asg.attach_load_balancers(
            AutoScalingGroupName=live_asg,
            LoadBalancerNames=[elb_name]
        )
        print 'Successfully attached ELB %s to the ASG %s.' % (elb_name, live_asg)
        if event['RequestType'] == 'Update':
            asg.detach_load_balancers(
                AutoScalingGroupName=non_live_asg,
                LoadBalancerNames=[elb_name]
            )
            print 'Successfully detached ELB %s from the ASG %s.' % (elb_name, non_live_asg)
        responseData = {'Success': 'Completed ELB attach / detach.'}
        sendResponse(event, context, 'SUCCESS', responseData)
    except ClientError as e:
        print 'Received client error: %s' % e
        responseData = {'Failed': 'Received client error: %s' % e}
        sendResponse(event, context, 'FAILED', responseData)


def sendResponse(event, context, responseStatus, responseData):
    responseBody = {'Status': responseStatus,
                    'Reason': 'See the details in CloudWatch Log Stream: ' + context.log_stream_name,
                    'PhysicalResourceId': context.log_stream_name,
                    'StackId': event['StackId'],
                    'RequestId': event['RequestId'],
                    'LogicalResourceId': event['LogicalResourceId'],
                    'Data': responseData}
    print 'RESPONSE BODY:n' + json.dumps(responseBody)
    try:
        req = requests.put(event['ResponseURL'], data=json.dumps(responseBody))
        if req.status_code != 200:
            print req.text
            raise Exception('Recieved non 200 response while sending response to CFN.')
        return
    except requests.exceptions.RequestException as e:
        print e
        raise

if __name__ == '__main__':
    lambda_handler('event', 'handler')

IAM permissions required for the Lambda function

{
	"Version": "2012-10-17",
	"Statement": [
	  {
		"Sid": "CloudWatchLogsAccess",
                             "Effect": "Allow",
		"Action": [
			"logs:*"
		],
		"Resource": "arn:aws:logs:*:*:*"
	  },
	  {
		"Sid": "ManageELBinASG",
		"Effect": "Allow",
		"Action": [
			"autoscaling:AttachLoadBalancers",
			"autoscaling:DetachLoadBalancers"
		],
		"Resource": [
			"*"
		]
	  }
	]
}

Following CFN stack enables you to select the stack that should be live and the capacity for each stack. Once the stack is switched: let’s say make green as new live-stack, validate whether everything looks good, just update the CFN stack and change the values of ASG capacities for blue (old) stack to 0 and it automatically terminate the instances and save costs.

Expand for CloudFormation template

{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Description": "AWS SA Assignment Instance for AMI creation.",
  "Parameters": {
    "LiveStack": {
      "Description": "Select which stack should be live.",
      "Type": "String",
      "AllowedValues": [
        "Blue",
        "Green"
      ],
      "ConstraintDescription": "must be a valid EC2 instance type."
    },
    "BlueKeyName": {
      "Description": "Keypair to be used with Blue stack.",
      "Type": "AWS::EC2::KeyPair::KeyName",
      "ConstraintDescription": "Must be a valid EC2 Keypair name."
    },
    "GreenKeyName": {
      "Description": "Keypair to be used with Green stack.",
      "Type": "AWS::EC2::KeyPair::KeyName",
      "ConstraintDescription": "Must be a valid EC2 Keypair name."
    },
    "BlueInstanceType": {
      "Description": "Application Server EC2 instance type for blue stack.",
      "Type": "String",
      "Default": "t2.micro",
      "AllowedValues": [
        "",
        "t2.micro",
        "t2.small",
        "t2.medium",
        "t2.large",
        "m4.large",
        "m4.xlarge",
        "c4.large",
        "c4.xlarge"
      ],
      "ConstraintDescription": "must be a valid EC2 instance type."
    },
    "GreenInstanceType": {
      "Description": "Application Server EC2 instance type for green stak.",
      "Type": "String",
      "Default": "t2.micro",
      "AllowedValues": [
        "",
        "t2.micro",
        "t2.small",
        "t2.medium",
        "t2.large",
        "m4.large",
        "m4.xlarge",
        "c4.large",
        "c4.xlarge"
      ],
      "ConstraintDescription": "must be a valid EC2 instance type."
    },
    "BlueMinCapacity": {
      "Description": "Auto Scaling minimum capacity.",
      "Type": "Number",
      "MinValue": "0",
      "ConstraintDescription": "Must be a number greater than or equal to 0."
    },
    "BlueMaxCapacity": {
      "Description": "Auto Scaling maximum capacity.",
      "Type": "Number",
      "MinValue": "0",
      "ConstraintDescription": "Must be a number greater than or equal to 0."
    },
    "BlueDesiredCapacity": {
      "Description": "Auto Scaling desired capacity.",
      "Type": "Number",
      "MinValue": "0",
      "ConstraintDescription": "Must be a number greater than or equal to 0."
    },
    "GreenMinCapacity": {
      "Description": "Auto Scaling minimum capacity.",
      "Type": "Number",
      "MinValue": "0",
      "ConstraintDescription": "Must be a number greater than or equal to 0."
    },
    "GreenMaxCapacity": {
      "Description": "Auto Scaling maximum capacity.",
      "Type": "Number",
      "MinValue": "0",
      "ConstraintDescription": "Must be a number greater than or equal to 0."
    },
    "GreenDesiredCapacity": {
      "Description": "Auto Scaling desired capacity.",
      "Type": "Number",
      "MinValue": "0",
      "ConstraintDescription": "Must be a number greater than or equal to 0."
    }
  },
  "Mappings": {
    "AWSRegionArch2AMI": {
      "us-east-1"      : { "ami" : "ami-08111162" },
      "us-west-2"      : { "ami" : "ami-c229c0a2" },
      "us-west-1"      : { "ami" : "ami-1b0f7d7b" },
      "eu-west-1"      : { "ami" : "ami-31328842" },
      "eu-central-1"   : { "ami" : "ami-e2df388d" },
      "ap-northeast-1" : { "ami" : "ami-f80e0596" },
      "ap-northeast-2" : { "ami" : "ami-6598510b" },
      "ap-southeast-1" : { "ami" : "ami-e90dc68a" },
      "ap-southeast-2" : { "ami" : "ami-f2210191" },
      "sa-east-1"      : { "ami" : "ami-1e159872" }
    },
    "Settings": {
      "Vpc": {
        "Id": "vpc-25aaa040"
      },
      "eu-west-1a": {
        "private": "subnet-6cc78109",
        "public": "subnet-6ee7810a"
      },
      "eu-west-1b": {
        "private": "subnet-c1aa22b6",
        "public": "subnet-c2aa22b5"
      }
    }
  },
  "Metadata" : {
    "AWS::CloudFormation::Interface" : {
      "ParameterGroups" : [
        {
          "Label" : { "default" : "General Configuration" },
          "Parameters" : [
            "LiveStack"
          ]
        },
        {
          "Label" : { "default" : "Blue Stack Configuration" },
          "Parameters" : [
            "BlueKeyName",
            "BlueInstanceType",
            "BlueMinCapacity",
            "BlueMaxCapacity",
            "BlueDesiredCapacity"
          ]
        },
        {
          "Label" : { "default" : "Green Stack Configuration" },
          "Parameters" : [
            "GreenKeyName",
            "GreenInstanceType",
            "GreenMinCapacity",
            "GreenMaxCapacity",
            "GreenDesiredCapacity"
          ]
        }
      ],
      "ParameterLabels" : {
        "LiveStack": { "default" : "Select which stack should be Live.*" },
        "DeleteStack": { "default" : "Select the stack (NON-LIVE STACK) to be deleted. If none, select blank.*" },
        "BlueKeyName" : { "default" : "Select the key to be used in blue stack." },
        "BlueInstanceType" : { "default" : "Select the instance type to be used in blue stack." },
        "BlueMinCapacity" : { "default" : "Enter the auto scaling minimum capacity for blue stack.*" },
        "BlueMaxCapacity" : { "default" : "Enter the auto scaling maximum capacity for blue stack.*" },
        "BlueDesiredCapacity" : { "default" : "Enter the auto scaling desired capacity for blue stack.*" },
        "GreenKeyName" : { "default" : "Select the key to be used in green stack." },
        "GreenInstanceType" : { "default" : "Select the instance type to be used in green stack." },
        "GreenMinCapacity" : { "default" : "Enter the auto scaling minimum capacity for green stack.*" },
        "GreenMaxCapacity" : { "default" : "Enter the auto scaling maximum capacity for green stack.*" },
        "GreenDesiredCapacity" : { "default" : "Enter the auto scaling desired capacity for green stack.*" }
      }
    }
  },
  "Conditions": {
    "BlueisLive": {"Fn::Equals": [{ "Ref": "LiveStack" }, "Blue"]},
    "GreenisLive": {"Fn::Equals": [{ "Ref": "LiveStack" }, "Green"]}
  },
  "Resources": {
    "WebServerRole": {
      "Type": "AWS::IAM::Role",
      "Properties": {
        "AssumeRolePolicyDocument": {
          "Version" : "2012-10-17",
          "Statement": [ {
            "Effect": "Allow",
            "Principal": {
              "Service": [ "ec2.amazonaws.com" ]
            },
            "Action": [ "sts:AssumeRole" ]
          } ]
        },
        "Path": "/"
      }
    },
    "WebServerInstanceProfile":{
      "Type": "AWS::IAM::InstanceProfile",
      "Properties": {
         "Path": "/",
         "Roles": [ { "Ref" : "WebServerRole" } ]
      }
    },
    "WebELBSecurityGroup": {
      "Type": "AWS::EC2::SecurityGroup",
      "Properties": {
        "GroupDescription": "ELB seecurity group.",
        "SecurityGroupIngress": [
          {
            "IpProtocol": "tcp",
            "FromPort": "80",
            "ToPort": "80",
            "CidrIp" : "0.0.0.0/0"
          }
        ],
        "VpcId": { "Fn::FindInMap": [ "Settings", "Vpc", "Id" ] },
        "Tags": [
          {
            "Key": "Name",
            "Value": "WebELBSecurityGroup"
          }
        ]
      }
    },
    "ServerSecurityGroup": {
      "Type": "AWS::EC2::SecurityGroup",
      "Properties": {
        "GroupDescription": "Server seecurity group.",
        "SecurityGroupIngress": [
          {
            "IpProtocol": "tcp",
            "FromPort": "80",
            "ToPort": "80",
            "SourceSecurityGroupId": { "Ref" : "WebELBSecurityGroup" }
          }
        ],
        "VpcId": { "Fn::FindInMap": [ "Settings", "Vpc", "Id" ] },
        "Tags": [
          {
            "Key": "Name",
            "Value": "ServerSecurityGroup"
          }
        ]
      }
    },
    "WebElasticLoadBalancer": {
      "Type": "AWS::ElasticLoadBalancing::LoadBalancer",
      "Properties": {
        "Listeners": [
          {
              "LoadBalancerPort": "80",
              "InstancePort": "80",
              "Protocol": "HTTP",
              "InstanceProtocol": "HTTP"
          }
        ],
        "HealthCheck": {
            "Target": "TCP:80",
            "HealthyThreshold": "3",
            "UnhealthyThreshold": "5",
            "Interval": "20",
            "Timeout": "10"
        },
        "ConnectionDrainingPolicy": {
            "Enabled": "true",
            "Timeout": "30"
        },
        "CrossZone": true,
        "SecurityGroups": [
          { "Ref": "WebELBSecurityGroup" }
        ],
        "Subnets": [
          {"Fn::FindInMap": ["Settings", "eu-west-1a", "public"]},
          {"Fn::FindInMap": ["Settings", "eu-west-1b", "public"]}
        ]
      }
    },
    "BlueLaunchConfig": {
      "Type": "AWS::AutoScaling::LaunchConfiguration",
      "Properties": {
        "InstanceType": { "Ref": "BlueInstanceType" },
        "ImageId": { "Fn::FindInMap": [ "AWSRegionArch2AMI", { "Ref": "AWS::Region" }, "ami" ]},
        "SecurityGroups": [ { "Ref": "ServerSecurityGroup" } ],
        "KeyName": { "Ref": "BlueKeyName" },
        "IamInstanceProfile": { "Ref": "WebServerInstanceProfile" },
        "UserData": {
          "Fn::Base64": {
            "Fn::Join": [
              "n",
              [
                "#!/bin/bash -ex",
                "",
                "PATH=$PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "yum upgrade -y",
                "yum install nginx -y",
                "echo \"Blue Deployment!!!\" > /usr/share/nginx/html/index.html",
                "chkconfig --level 2345 nginx on",
                "service nginx start"
              ]
            ]
          }
        }
      }
    },
    "BlueServerGroup": {
      "Type": "AWS::AutoScaling::AutoScalingGroup",
      "Properties": {
        "VPCZoneIdentifier": [
          {"Fn::FindInMap": ["Settings", "eu-west-1a", "private"]},
          {"Fn::FindInMap": ["Settings", "eu-west-1b", "private"]}
        ],
        "LaunchConfigurationName": { "Ref": "BlueLaunchConfig" },
        "TerminationPolicies": [ "OldestInstance" ],
        "MinSize": { "Ref": "BlueMinCapacity" },
        "MaxSize": { "Ref": "BlueMaxCapacity" },
        "DesiredCapacity": { "Ref": "BlueDesiredCapacity" },
        "HealthCheckGracePeriod": "2400",
        "HealthCheckType": "EC2",
        "Tags": [
          {
            "Key": "Name",
            "Value": "Blue Web Server",
            "PropagateAtLaunch": "true"
          },
          {
            "Key": "Owner",
            "Value": "Prakash",
            "PropagateAtLaunch": "true"
          }
        ]
      }
    },
    "GreenLaunchConfig": {
      "Type": "AWS::AutoScaling::LaunchConfiguration",
      "Properties": {
        "InstanceType": { "Ref": "GreenInstanceType" },
        "ImageId": { "Fn::FindInMap": [ "AWSRegionArch2AMI", { "Ref": "AWS::Region" }, "ami" ]},
        "SecurityGroups": [ { "Ref": "ServerSecurityGroup" } ],
        "KeyName": { "Ref": "GreenKeyName" },
        "IamInstanceProfile": { "Ref": "WebServerInstanceProfile" },
        "UserData": {
          "Fn::Base64": {
            "Fn::Join": [
              "n",
              [
                "#!/bin/bash -ex",
                "",
                "PATH=$PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "yum upgrade -y",
                "yum install nginx -y",
                "echo \"Green Deployment!!!\" > /usr/share/nginx/html/index.html",
                "chkconfig --level 2345 nginx on",
                "service nginx start"
              ]
            ]
          }
        }
      }
    },
    "GreenServerGroup": {
      "Type": "AWS::AutoScaling::AutoScalingGroup",
      "Properties": {
        "VPCZoneIdentifier": [
          {"Fn::FindInMap": ["Settings", "eu-west-1a", "private"]},
          {"Fn::FindInMap": ["Settings", "eu-west-1b", "private"]}
        ],
        "LaunchConfigurationName": { "Ref": "GreenLaunchConfig" },
        "TerminationPolicies": [ "OldestInstance" ],
        "MinSize": { "Ref": "GreenMinCapacity" },
        "MaxSize": { "Ref": "GreenMaxCapacity" },
        "DesiredCapacity": { "Ref": "GreenDesiredCapacity" },
        "HealthCheckGracePeriod": "2400",
        "HealthCheckType": "EC2",
        "Tags": [
          {
            "Key": "Name",
            "Value": "Green Web Server",
            "PropagateAtLaunch": "true"
          },
          {
            "Key": "Owner",
            "Value": "Prakash",
            "PropagateAtLaunch": "true"
          }
        ]
      }
    },
    "AssignLiveStack": {
      "Type": "Custom::AssignLiveStack",
      "DependsOn": [ "WebElasticLoadBalancer", "BlueServerGroup", "GreenServerGroup" ],
      "Properties": {
        "ServiceToken": "arn:aws:lambda:eu-west-1:176207018055:function:bluegreenswitch",
        "LiveASG": {
          "Fn::If" : [
            "BlueisLive",
            { "Ref" : "BlueServerGroup"},
            {"Ref" : "GreenServerGroup"}
          ]
        },
        "NonLiveASG": {
          "Fn::If" : [
            "BlueisLive",
            { "Ref" : "GreenServerGroup"},
            {"Ref" : "BlueServerGroup"}
          ]
        },
        "ELBName": { "Ref" : "WebElasticLoadBalancer" }
      }
    }
  },
  "Outputs": {
    "WebServerURL" : {
      "Description" : "Web Server URL",
      "Value" : {
        "Fn::Join": [
          "",
          [
            "http://",
            { "Fn::GetAtt" : [ "WebElasticLoadBalancer" , "DNSName" ] }
          ]
        ]
      }
    }
  }
}

© Prakash P 2015 - 2023

Powered by Hugo & Kiss.