Tuesday, 23 May 2017

AWS ECS run task on a specific EC2 container instance

What:

Amazon Web Services - EC2, ECS

Problem:

You want to run task on a specific ECS (docker host) instance.

Solution:

Amazon supports Placement Constraints, which means you have more control on how to distribute tasks (docker containers) to EC2 container service instances. My goal is to place a task always on the same instance.

To achieve this I will use "custom attribute" which can be set on ECS instances.
Navigate to EC2 Container Service, click your cluster name, then ECS Instances tab.
Select one of the instances and click on Actions button
Select View/Edit Attributes
Click on Add attribute and select
Name:  constraint
Value: master

Now you need to add new service to be able to specify placement constraints.
In your cluster click on Services tab > Create
Set your settings and under Task Placement > Placement Templates select Custom
Under Constraint add
Type: MemberOf
Expression: attribute:constraint == master
Save

Now when you know how to do it in AWS Console you can add it to your CloudFormation template.
To set "custom attribute" when instance is created you can use userdata script, simply add below code to it:
#!/bin/bash
cat <<'EOF' >> /etc/ecs/ecs.config
ECS_CLUSTER=MyCluster
ECS_INSTANCE_ATTRIBUTES={"constraint": "master"}
EOF

No comments:

Post a Comment