Created
June 2, 2020 04:34
-
-
Save imnnquy/1b51cedf84411f30eafd08846266f375 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# This is the user data to be added into launch configuration for auto scaling group | |
env="stg" #TODO: change environment | |
AWS_ECS_CLUSTER_NAME="cluster-name-$env" | |
echo ECS_CLUSTER=$AWS_ECS_CLUSTER_NAME >> /etc/ecs/ecs.config | |
echo ECS_BACKEND_HOST= >> /etc/ecs/ecs.config | |
echo "ECS_ENABLE_TASK_CPU_MEM_LIMIT=false" >> /etc/ecs/ecs.config | |
START_TASK_SCRIPT_FILE="/etc/ecs/ecs-start-task.sh" | |
cat <<- 'EOF' > ${START_TASK_SCRIPT_FILE} | |
# Set environment variables and store logs to file | |
exec 2>>/var/log/ecs/ecs-start-task.log | |
set -x | |
env="stg" #TODO: change environment | |
AWS_ECS_CLUSTER_NAME="cluster-name-$env" | |
# Install aws cli v2 and jq | |
yum install -y jq unzip | |
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" | |
unzip awscliv2.zip | |
./aws/install | |
PATH=$PATH:/usr/local/bin | |
# Wait for the ECS service to be responsive | |
until curl -s http://localhost:51678/v1/metadata | |
do | |
sleep 1 | |
done | |
# Configure AWS environment | |
az=$(curl -s http://instance-data/latest/meta-data/placement/availability-zone) | |
region=${az:0:${#az} - 1} | |
aws configure set default.region $region | |
INSTANCES_COUNT=$(aws ecs list-container-instances --cluster $AWS_ECS_CLUSTER_NAME | jq '.containerInstanceArns | length') | |
# Scale all ECS services | |
for AWS_ECS_CONTAINER_NAME in service1_$env service2_$env service3_$env service4_$env nginx_$env ; do | |
aws ecs update-service --cluster $AWS_ECS_CLUSTER_NAME --service $AWS_ECS_CONTAINER_NAME --desired-count $INSTANCES_COUNT --placement-constraints type="distinctInstance" --placement-strategy type="spread",field="instanceId" >> /dev/null | |
done | |
EOF | |
# Write systemd unit file | |
UNIT="ecs-start-task.service" | |
cat <<- EOF > /etc/systemd/system/${UNIT} | |
[Unit] | |
Description=ECS Start Task | |
Requires=ecs.service | |
After=ecs.service | |
[Service] | |
ExecStart=/usr/bin/bash ${START_TASK_SCRIPT_FILE} | |
[Install] | |
WantedBy=default.target | |
EOF | |
# Enable our ecs.service dependent service with `--no-block` to prevent systemd deadlock | |
# See https://github.com/aws/amazon-ecs-agent/issues/1707 | |
systemctl enable --now --no-block "${UNIT}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment