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.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{
	"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.
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
{
  "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 - 2019

Powered by Hugo & Kiss.