Using Jenkins pipelines to deploy AWS ECS services

Nitin Yadav
SquareOps
Published in
1 min readMay 20, 2019

Single Branch Pipeline

Dockerfile

FROM openjdk:10
COPY target/server.jar
COPY entrypoint.sh entrypoint.sh
COPY getContainerIp.py getContainerIp.py
RUN chmod +x entrypoint.sh ; chmod +x getContainerIp.py
EXPOSE 9100
ENTRYPOINT ./entrypoint.sh $SPRING_PROFILES_ACTIVE

entrypoint.sh

#!/bin/bash
SPRING_PROFILES_ACTIVE=$1
export ECS_INSTANCE_IP_ADDRESS=$(/usr/bin/python /getContainerIp.py)
java -jar server.jar --spring.profiles.active=${SPRING_PROFILES_ACTIVE}

getContainerIP.py

#!/usr/bin/python
import urllib, json

metadataEndpoint = "http://169.254.170.2/v2/metadata"
metadata = urllib.urlopen(metadataEndpoint)
metadataJson = json.loads(metadata.read())
print (metadataJson['Containers'][0]['Networks'][0]['IPv4Addresses'][0])

Jenkinsfile

pipeline {
agent any
parameters {
string(
name: 'BRANCH',
defaultValue: 'master',
description: ''
)
}
environment {
EC_REGISTRY = "xxxxxxxxxxxx.dkr.ecr.ap-southeast-1.amazonaws.com/${JOB_BASE_NAME}"
ECS_CLUSTER = "TEST-ECS-CLUSTER"
}
options {
buildDiscarder(logRotator(numToKeepStr: '50'))
}
stages {
stage ('Checkout') {
steps {
//script {
// currentBuild.displayName = "${COMPONENT}"
//}
checkout([
$class: 'GitSCM',
branches: [[name: '${BRANCH}']],
doGenerateSubmoduleConfigurations: false,
extensions: [
[
$class: 'CloneOption',
noTags: false,
reference: '',
shallow: true
],
[$class: 'CleanCheckout']
],
submoduleCfg: [],
userRemoteConfigs: [[
credentialsId: 'dev_ops',
url: 'https://gitlab.com/xxxx_admin/sample_ecs_springboot.git'
]]
])
}
}
stage ('Package') {
steps {
sh '''
docker build \
-t ${EC_REGISTRY}:${BUILD_NUMBER} \
-t ${EC_REGISTRY}:latest \
.
'''
}
}
stage ('Upload') {
steps {
//ecrLogin()
withDockerRegistry([ credentialsId: "",url: "https://${EC_REGISTRY}" ]){
sh '''
set +x
eval $(aws ecr get-login --no-include-email --region ap-southeast-1) > /dev/null
docker push ${EC_REGISTRY}:${BUILD_NUMBER}
docker push ${EC_REGISTRY}:latest
'''
}
}
}
stage ('Deploy') {
steps {
sh '''aws ecs update-service \
--cluster ${ECS_CLUSTER} \
--service ${JOB_BASE_NAME} \
--force-new-deployment \
--region ap-southeast-1
'''
}
}
}
}

→ can be placed in root of any repository , give branch name and default path in jenkins pipeline job and it will automatically construct pipeline

--

--

Nitin Yadav
SquareOps

DevOps with 10+ yrs experience. I love to accept the challenges of modernizing the legacy infrastructures and taking existing deployments to handle 100X scale