How to Deploy to Amazon ECS With Jenkins
Register a new task definition revision with the fresh image, then update the ECS service to roll it out.
Render a task definition with the new image tag, aws ecs register-task-definition, then aws ecs update-service --force-new-deployment to start the rollout.
Steps
- Register a task definition revision pointing at the new image.
- Update the service to the new revision.
- Wait on
aws ecs wait services-stableto confirm the rollout settled.
Pipeline
Jenkinsfile
pipeline {
agent any
environment { AWS_REGION = 'us-east-1' }
stages {
stage('Deploy') {
steps {
withCredentials([usernamePassword(credentialsId: 'aws-deploy',
usernameVariable: 'AWS_ACCESS_KEY_ID',
passwordVariable: 'AWS_SECRET_ACCESS_KEY')]) {
sh '''
sed "s|IMAGE_TAG|$BUILD_NUMBER|" taskdef.json > taskdef.out.json
ARN=$(aws ecs register-task-definition \
--cli-input-json file://taskdef.out.json \
--query 'taskDefinition.taskDefinitionArn' --output text)
aws ecs update-service --cluster prod --service api \
--task-definition "$ARN" --force-new-deployment
aws ecs wait services-stable --cluster prod --services api
'''
}
}
}
}
}Gotchas
services-stablecan take minutes; raise the stage timeout for slow draining.- The execution role in the task definition must allow pulling from your registry.
Related guides
How to Build and Push a Docker Image in JenkinsBuild a Docker image in a Jenkins Declarative Pipeline and push it to a registry with docker.withRegistry, ta…
How to Deploy to AWS With an Assumed Role in JenkinsDeploy to AWS from a Jenkins Declarative Pipeline by assuming an IAM role with sts assume-role, exporting tem…