適当なECSデプロイスクリプト

JSONYAMLプリプロセス出来ると、なおうれし。

{
  "containerDefinitions": [
    {
      "volumesFrom": [],
      "memory": 300,
      "portMappings": [
        {
          "hostPort": 0,
          "containerPort": 80,
          "protocol": "tcp"
        }
      ],
      "essential": true,
      "mountPoints": [
        {
          "containerPath": "/usr/local/apache2/htdocs",
          "sourceVolume": "vol"
        },
        {
          "containerPath": "/var/log/httpd",
          "sourceVolume": "log"
        }
      ],
      "name": "httpd",
      "environment": [],
      "image": "httpd:2.4",
      "cpu": 10
    },
    {
      "volumesFrom": [
        {
          "sourceContainer": "httpd"
        }
      ],
      "memory": 200,
      "portMappings": [],
      "essential": true,
      "entryPoint": [
        "sh",
        "-c"
      ],
      "mountPoints": [],
      "name": "testapp",
      "environment": [],
      "image": "busybox",
      "command": [
        "/bin/sh -c 'while true; do echo xxx >> /usr/local/apache2/htdocs/index.html; sleep 3; done'"
      ],
      "cpu": 10
    }
  ],
  "volumes": [
    {
      "name": "vol"
    },
    {
      "host": {
        "sourcePath": "/var/log/httpd"
      },
      "name": "log"
    }
  ],
  "family": "test"
}
  • ec-deploy.sh
#!/bin/bash
set -e

if [ -z "$1" -o -z "$2" ]; then
  echo "usage: $0 SERVICE TASK_JSON"
  exit
fi

SERVICE=$1
TASK_JSON=$2
TASK_NAME=$(jq -r .family $TASK_JSON)
TASK_ROLE=arn:aws:iam::...:role/...

function get_last_event() {
  EVENT=$(aws ecs describe-services --services $1 | jq -r '.services[0].events[0] | [.id, .message] | @tsv')
  EVENT_ID=$(awk -F '\t' '{print $1}' <<< "$EVENT")
  EVENT_MSG=$(awk -F '\t' '{print $2}' <<< "$EVENT")
}

get_last_event $SERVICE
LAST_EVENT_ID="$EVENT_ID"
LAST_EVENT_MSG="$EVENT_MSG"

aws ecs register-task-definition \
  --task-role-arn=$TASK_ROLE \
  --cli-input-json file://$TASK_JSON > /dev/null

aws ecs update-service --service $SERVICE --task-definition $TASK_NAME > /dev/null

while true; do
  get_last_event $SERVICE

  if [ "$EVENT_ID" != "$LAST_EVENT_ID" ]; then
    echo $EVENT_MSG

    if [[ "$EVENT_MSG" =~ has\ reached\ a\ steady\ state ]]; then
      break
    fi

    LAST_EVENT_ID="$EVENT_ID"
    LAST_EVENT_MSG="$EVENT_MSG"
  fi
done

デプロイ例

$  ecs-deploy.sh hello task.json
(service hello) has started 1 tasks: (task 2b3ab535-05f7-40be-a2a7-b661e56e9527).
(service hello) registered 1 targets in (target-group arn:aws:elasticloadbalancing:ap-northeast-1:...:targetgroup/default/afb88bc90fe30b1a)
(service hello) has begun draining connections on 1 tasks.
(service hello) has stopped 1 running tasks: (task 9cc4b054-0fa5-4083-a23d-e3a497400bd5).
(service hello) has reached a steady state.