Matthew Housser
Matthew Housser

Reputation: 1012

From local script, terminate (then recreate) all EC2 instances in Auto Scaling Group

The setup:

I have an AWS Load Balancer with an Auto Scaling Group attached to it. It launches instances of an AMI that I have configured to act as a base setup for our application server.

I used the User Data setting to do the following:

#!/bin/bash

cd /home/server
GIT_SSH_COMMAND='ssh -i /home/ec2-user/app-server.key' git pull
composer install

That is to say: when the Auto Scaling Group spins up a new instance, it pulls the latest code from GitHub, updates the composer dependencies (it's a Lumen-based PHP RESTful application service), and is ready to go.

This all works.

When I manually detatch all of the EC2 instances from my Auto Scaling Group, new instances are immediately created and successfully grab the latest code. Lovely!

What I'm trying to do

After I commit my server code to GitHub, I want to run a local command - say, deploy staging, which automatically does the following:

  1. Terminates current instances in the Auto Scaling Group
  2. This causes new instances to be created, which then update to the latest code.

What I'm doing now

It's still very manual. I commit to GitHub, and then I have to go to the AWS web console and 'detatch' all my EC2 instances so that new ones will take their place - and then I have to go terminate those detatched instances.

The question

So - given what I'm trying to accomplish, how can I get this done?

From my Windows PC I want to type in a single word which will do all of the above.

Perhaps my ordering of things is incorrect - for example, new instances should be spun up before terminating the old ones, etc - and in this case, please advise me as to the best way to accomplish things.

I'm also looking for exact recommendations re: how to implement this. Do I need to download that AWS CLI tool for Windows? How do I execute AWS commands from my home PC? Etc..

Thanks!

EDIT

Alternatively (perhaps this is a cleaner way?), I could also just tell the current instances in my Auto Scaling Group/Load Balancer to 'do a GitHub update'.. but I have no idea how to do this. The instances only do this once upon first being created.

Upvotes: 0

Views: 482

Answers (1)

Mircea
Mircea

Reputation: 10566

This whole setup is sort of brittle. You could take a look at CodeDeploy: https://aws.amazon.com/codedeploy/

For your specific setup, if you're not allowed to touch it/alter it too much, what I would do is:
In the running instances I would periodically pull from github and compare with what is running. If there is a new version I would stop the service. The instance would become unhealthy and get recycled and get the new version.
You probably want to setup up a somewhat random schedule between different machines to ensure they don't all get recycled at the same time.

Upvotes: 2

Related Questions