How to move all existing containers on another instance before auto scale in? - amazon-web-services

I am using AWS ECS in combination with EC2 instances.
Right now I am setting up Auto Scaling. How can I make sure that when, an EC2 instance gets terminated, all ECS tasks get migrated before the machine gets terminated?

Right now it is not automatically possible to achieve this. The best approach would be to have atleast 2 tasks running of each service, spread on different instances via a placement constraint.
Manually (or scripted) it is possible:
If you want to replace an instance attached to an ECS cluster, you can simply drain the instance. This will do the following
Start a new task of each running service on another instance in the cluster
Wait until the recently started task is 'steady'
shutdown the old task
To drain an instance using the AWS CLI, do the following:
Open the Amazon ECS console at https://console.aws.amazon.com/ecs/.
In the navigation pane, choose Clusters and select the cluster.
Choose ECS Instances and select the check box for the container
instances.
Choose Actions, Drain instances.
After the instances are processed, choose Done.
This can also be done via the command line.
To do it automatically, you will need to add a lifecycle hook on termination.
Call the AWS CLI from the termination lifecycle hook to drain the instance, wait a fixed amount of time and then continue terminating the instance.

Related

AWS EC2 LifeCyle Hook vs User Data in Launch configuration

In AWS EC2, both lifecycle hook and user data of launch configuration permits to execute some customised actions while launching instances.
Could you tell me is Lifecyle hook related actions are executed before or User data defined in launch configuration executed before ?
When do you chose which one ? What are their differences ?
User Data and Cloud-Init
When launching an Amazon EC2 instance, you can provide a User Data field. The information entered in this field is available to the instance via http://169.254.169.254/latest/user-data/.
This is an excellent way to pass information to the instance that is accessible to software running on the instance.
Then Canonical, maker of Ubuntu, conceived Cloud-Init as a way of running scripts during the startup of virtual machines. Cloud-Init takes a script passed via EC2 User Data and runs it as root during the first boot of an instance. It is a great way to install software and configure the machine when it is first used.
Amazon EC2 Auto-Scaling Lifecycle Hooks
Amazon EC2 Auto-Scaling is a method of automatically scaling a fleet of EC2 instances based on workload. Instances are launched or terminated based on a target capacity metric. Instances launched through Auto-Scaling are normal EC2 instances, so User Data can be used to configure these instances.
Sometimes, however, a more complex operation is required when launching/terminating instances. For example, when launching instances it might be necessary to contact an external configuration service, and when terminating instances it might be necessary to copy data off an instance. These tasks can be accomplished via Lifecycle Hooks.
From Amazon EC2 Auto Scaling Lifecycle Hooks - Amazon EC2 Auto Scaling:
Lifecycle hooks enable you to perform custom actions by pausing instances as an Auto Scaling group launches or terminates them. When an instance is paused, it remains in a wait state until either you complete the lifecycle action using the complete-lifecycle-action CLI command or CompleteLifecycleAction API action, or the timeout period ends (one hour by default).
Compared to User Data, Lifecycle Hooks are rarely used. They are typically required when a longer-running or external process is required before instances are ready to process requests. For example, there might be a long startup process required for new instances that exceeds the time normally allowed for health checks. Or, an external process (outside the instance) might need to be triggered before the instance can start processing traffic.
Lifecycle Hooks are more complicated because they involve a signalling mechanism. When an Auto Scaling instance is launched or terminated, Auto Scaling will send a message via Amazon SQS or Amazon SNS. You are then responsible for running a process that responds to this signal. When the process is complete, it must send a signal back to Auto Scaling so that the instance can be fully added to, or removed from, the Auto Scaling group. This will typically require something running external to the EC2 instance to process the Lifecycle Hook.
Bottom line: You want to use User Data. It is rare that you would use a Lifecycle Hook.
Thanks for your answers.
Actually, the LifeCycle hook is somehow useful. For example, in my situation, I have to deactivate Tableau Server licenses before the instance is terminated. This is a good situation to use it.
While, during starting up, user data is executed but the instance will be put into "In Service" states once the OS itself is up, even the user data is still not yet finished to be executed.
So to choose between the two approches, it all depends on what you want to do in the scripts.

ECS stop instance

I've an ECS cluster with running one task for my backend instance. I would like to be able to stop/start the EC2 instance whenever I want. Is it possible?? I was trying to stop instance directly but it terminates after few second when stopped and after that new instance is created automatically. I tried to change the Auto Scale Group to match desired=min=0 capacity but when I do that the instance gets auto terminated. I just want to turn off the Ec2 instance when its not needed to be used but at the same time I want data to persist betweet turning on and off. I am fighting with this for a few days now and wasn't able to achieve my goals.
Also how to link EBS volume with VOLUME /root/.local/share/XYZ from docker file image to persist the data from the XYZ folder
I would suggest you to do modifications in autoscaling group, when you want to turn off instance put 0 in auto scaling and when you want to turn on change value in autoscaling,
... you can do that with aws cli , and you can shcdule the period also by putting aws cli command in cron job
I would suggest using EFS. Here is an article from AWS on how to persist data from ECS containers using EFS.
Using Amazon EFS to Persist Data from Amazon ECS Containers
Start/Stop instances and auto-scale don't really fit together.
Auto-scale is specifically designed to solve scalein/scaleout.
One way to address this could be using customized termination policy (but I never tried this in ECS setup).
One note though, if your customized termination policy never terminates the instances and you continue adding instances to keep always, you might get good amount EC2 bill.

Replace ECS container instances in terraform setup

We have a terraform deployment that creates an auto-scaling group for EC2 instances that we use as docker hosts in an ECS cluster. On the cluster there are tasks running. Replacing the tasks (e.g. with a newer version) works fine (by creating a new task definition revision and updating the service -- AWS will perform a rolling update). However, how can I easily replace the EC2 host instances with newer ones without any downtime?
I'd like to do this to e.g. have a change to the ASG launch configuration take effect, for example switching to a different EC2 instance type.
I've tried a few things, here's what I think gets closest to what I want:
Drain one instance. The tasks will be distributed to the remaining instances.
Once no tasks are running in that instance anymore, terminate it.
Wait for the ASG to spin up a new instance.
Repeat steps 1 to 3 until all instances are new.
This works almost. The problem is that:
It's manual and therefore error prone.
After this process one of the instances (the last one that was spun up) is running 0 (zero) tasks.
Is there a better, automated way of doing this? Also, is there a way to re-distribute the tasks in an ECS cluster (without creating a new task revision)?
Prior to making changes make sure you have the ASG spanned across multiple availability zones and so are the containers. This ensures High Availability when instances are down in one Zone.
You can configure an update policy of Autoscaling group with AutoScalingRollingUpgrade where you can set MinInstanceInService and MinSuccessfulInstancesPercent to a higher value to maintain slow and safe rolling upgrade.
You may go through this documentation to find further tweaks. To automate this process, you can use terraform to update the ASG launch configuration, this will update the ASG with a new version of launch configuration and trigger a rolling upgrade.

AWS Scaling In Termination Protection for EC2 Container Service

I am unable to figure out how to protect my ECS task instances when using Auto Scaling in Amazon AWS. I have a long running task that can scale out as required but I want to mark task instances that are running as "not destroyable". I have found several resources that talk about instance protection such as:
https://aws.amazon.com/blogs/aws/new-instance-protection-for-auto-scaling/
and (because I am using python) the API documentation is here:
http://boto3.readthedocs.io/en/latest/reference/services/autoscaling.html#AutoScaling.Client.set_instance_protection
This method requires an InstanceId and so I attempt to get the instance id of the current container by using a command like:
curl http://169.254.169.254/latest/meta-data/instance-id
However, this method just returns the instance id of the EC2 machine the task is running on. So my question is: Is there a way to get the instance id of a docker task instance (if that even exists)? If not is there another way I can prevent Auto Scaling from terminating a task that is still running? Do I have to write my own task manager that manages Scaling In?
To solve the same issue, we developed a simple application which is started when a job is done on one of the Auto Scaling Group (ASG) instances. This application checks the queue and if there is no job in the queue (for let's say 10 minutes or 10 times) it terminates its instance and decrements the Desired value of the ASG. This provides us with a reliable mechanism for scaling in. Scaling out on the other hand, is done by the ASG itself based on the number of jobs in the queue.

Is there a way to STOP not TERMINATE instances using auto-scaling in AWS?

I am looking at using AWS auto-scaling to scale my infrastructure up and down based on various performance metrics (CPU, etc.). I understand how to set this up; however, I don't like that instances are terminated rather than stopped when it is scaled down. This means that when I scale back up, I have to start from scratch with a new instance and re-install my software, etc. I'd rather just start/stop my instances as needed rather than create/terminate. Is there a way to do this?
No, it is not possible to Stop an instance under Auto Scaling. When a Scaling Policy triggers the removal of an instance, Auto Scaling will always Terminate the instance.
However, here's some ideas to cope with the concept of Termination...
Option 1: Use pre-configured AMIs
You can configure an Amazon EC2 instance with your desired software, data and settings. Then, select the EC2 instance in the Management Console and choose the Create Image action. This will create a new Amazon Machine Image (AMI). You can then configure Auto Scaling to use this AMI when launching a new instance. Each new instance will contain exactly the same disk contents.
It's worth mentioning that EBS starts up very quickly from an AMI. Instead of copying the whole AMI to the boot disk, it copies it across on "first access". This means the new instance can start-up immediately rather than waiting for the whole disk to be copied.
Option 2: Use a startup (User Data) script
Each Amazon EC2 instance has a User Data field, which is accessible from the instance. A script can be passed through the User Data field, which is then executed when the instance starts. The script could be used to install software, download data and configure the instance.
The script could do something very simple, like download a configuration script from a source code repository, then execute the script. This means that machine configuration can be centrally managed and version-controlled. Want to update your app? Just launch a new instance with the updated script and throw away the old instance (which is much easier than "updating" an app).
Option 3: Add/Remove instances to an Auto Scaling group
Rather than using Scaling Policies to Launch/Terminate instances for an Auto Scaling group, it is possible to attach/detach specific instances. Thus, you could 'simulate' auto scaling:
When you want to scale-down, detach an instance from the Auto Scaling group, then stop it.
When you want to add an instance, start the instance then attach it to the Auto Scaling group.
This would require your own code, but it is very simple (basically two API calls). You would be responsible for keeping track of which instance to attach/detach.
You can suspend scaling processes, see documentation here:
https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-suspend-resume-processes.html#as-suspend-resume
Add that instance to Scale in protection and then stop the instance then it will not delete your instance as it's having the scale in protection.
Actually you have three official AWS options to reboot or even stop an instance which belongs to an Auto Scaling Group:
Put the instance into the Standby state
Detach the instance from the group
Suspend the health check process
Ref.: https://aws.amazon.com/premiumsupport/knowledge-center/reboot-autoscaling-group-instance/
As of April 2021:
Option 4: Use Warm Pools and an Instance Reuse Policy
By default, Amazon EC2 Auto Scaling terminates your instances when your Auto Scaling group scales in. Then, it launches new instances into the warm pool to replace the instances that were terminated.
If you want to return instances to the warm pool instead, you can specify an instance reuse policy. This lets you reuse instances that are already configured to serve application traffic.
This mostly automates option 3 from John's answer.
Release announcement: https://aws.amazon.com/blogs/compute/scaling-your-applications-faster-with-ec2-auto-scaling-warm-pools/
Documentation: https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-warm-pools.html
This is to expand a little on #mwalling's answer, because that is the right direction, but needs a little extra work to prevent instance termination.
There is now a way to stop or hibernate scaled in instances!
By default AWS Autoscaling scale in policy is to terminate an instance. Even if you have a warm pool configured. Autoscaling will create a fresh instance to put into the warm pool. Presumably to make sure you start with a fresh machine every time. However, with a instance reuse policy you can make AWS Autoscaling either stop or hibernate a running instance and store that instance in the warm pool.
Advantages include:
Local caches stay populated (use hibernate for in memory cache).
Burstable EC2 instances (those types with T*) keep built up burst credits instead of the newly created instance that have limited or no credits.
Practical example:
We use a burstable EC2 instance for CI/CD work that we scale to 0 instances outside working hours. With a reuse policy our local image repository stays populated with the most important Docker images. Also we keep the built up credit from the previous day and that speeds up automatic jobs we run first thing every morning.
How to implement:
There's currently no way of doing this completely via the management console. So you will need to use AWS CLI or SDK.
First create a warm pool as described in the AWS Documentation
Then execute this command to add a reuse policy:
aws autoscaling put-warm-pool --auto-scaling-group-name <Name-of-autoscaling-group> --instance-reuse-policy ReuseOnScaleIn=true
Reference docs for the command: AWS CLI Autoscaling put-warm-pool documentation
Flow diagram of possible life cycles of EC2 instances:
Image from AWS Documentation: Lifecycle state transitions for instances in a warm pool