Skip to content

Instantly share code, notes, and snippets.

@hungtrinh
Forked from jlis/.gitlab-ci.yml
Created May 12, 2020 10:39
Show Gist options
  • Save hungtrinh/079e8915fc5d89eba576d87990c3aaf7 to your computer and use it in GitHub Desktop.
Save hungtrinh/079e8915fc5d89eba576d87990c3aaf7 to your computer and use it in GitHub Desktop.
AWS ECS and ECR deployment via Docker and Gitlab CI
image: docker:latest
variables:
REPOSITORY_URL: <AWS ACCOUNT ID>.dkr.ecr.eu-central-1.amazonaws.com/<ECS REPOSITORY NAME>
REGION: eu-central-1
TASK_DEFINTION_NAME: <TASK DEFINITION NAME>
CLUSTER_NAME: <CLUSTER NAME>
SERVICE_NAME: <SERVICE NAME>
services:
- docker:dind
before_script:
- apk add --no-cache curl jq python py-pip
- pip install awscli
- $(aws ecr get-login --no-include-email --region "${REGION}")
- IMAGE_TAG="$(echo $CI_COMMIT_SHA | head -c 8)"
stages:
- build
- deploy
build:
stage: build
script:
- echo "Building image..."
- docker build -t $REPOSITORY_URL:latest .
- echo "Tagging image..."
- docker tag $REPOSITORY_URL:latest $REPOSITORY_URL:$IMAGE_TAG
- echo "Pushing image..."
- docker push $REPOSITORY_URL:latest
- docker push $REPOSITORY_URL:$IMAGE_TAG
only:
- master
deploy:
stage: deploy
script:
- echo $REPOSITORY_URL:$IMAGE_TAG
- TASK_DEFINITION=$(aws ecs describe-task-definition --task-definition "$TASK_DEFINTION_NAME" --region "${REGION}")
- NEW_CONTAINER_DEFINTIION=$(echo $TASK_DEFINITION | python $CI_PROJECT_DIR/update_task_definition_image.py $REPOSITORY_URL:$IMAGE_TAG)
- echo "Registering new container definition..."
- aws ecs register-task-definition --region "${REGION}" --family "${TASK_DEFINTION_NAME}" --container-definitions "${NEW_CONTAINER_DEFINTIION}"
- echo "Updating the service..."
- aws ecs update-service --region "${REGION}" --cluster "${CLUSTER_NAME}" --service "${SERVICE_NAME}" --task-definition "${TASK_DEFINTION_NAME}"
only:
- master
import sys, json, argparse
parser = argparse.ArgumentParser('Replaces image in the task definition')
parser.add_argument('image_uri', metavar='I', type=str, nargs='+',
help='The new image URI')
args = parser.parse_args()
definition = json.load(sys.stdin)['taskDefinition']['containerDefinitions']
definition[0]['image'] = args.image_uri[0]
print json.dumps(definition)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment