Jenkins Tutorial pt.2 - Setup Docker build pipeline w/ECR

Welcome to the second part of the tutorial!

We are going to build a docker image and push it to AWS’s ECR docker registry.

Prerequisites

First, of course, you need to have Jenkins setup already. If you haven’t, see my previous post.

Second, you need to install some plugins on Jenkins. We are using:

  • Git Plugin
  • Pipeline AWS Plugin
    Please install them in Jenkins > Manage Jenkins > Manage Plugins.

Third, set up the corresponding credentials.
Go to Jenkins > Credentials > System > Global > Add Credentials, and add a username and password for your github (or other scm) account.
We also need aws credentials, if you don’t have AWS account or an ECR docker registry yet, be sure to create one now.
You can either use the AWS Credentials type, or normal username with password, where Username: AccessKeyId, Password: SecretAccessKey.

Creating Pipeline

Now create a new pipeline, scroll down to script part. We will be mostly using declarative pipeline instead of sripted.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
pipeline {
agent any
environment {
registry = 'copy-your-ecr-repo-here/testproject:latest'
}
stages {
stage("Checkout") {
steps {
git branch: 'master',
credentialsId: 'github',
url: 'your-github-repo.git'
}
}
stage("Docker Build") {
steps {
sh "docker build -t testproject:latest ."
}
}
stage("ECR Login") {
steps {
withAWS(credentials:'aws-credential') {
script {
def login = ecrLogin()
sh "${login}"
}
}
}
}
stage("Docker Push") {
steps {
sh "docker push ${registry}"
}
}
}
post {
success {
echo 'ending'
build job: 'TestJob-CD'
}
}
}

Don’t worry, I will go through the whole process.

Stage 1: Checkout source code

We covered this part in the previos tutorial. Basically just checking our your source code in Jenkins.

Stage 2: Docker Build

Pretty straight forward, running a docker build command. Make sure to have a Dockerfile in your repo.

Stage 3: ECR Login

Here we are using the AWS Pipeline plugin to generate the login commands for ECR. Note that the quotation marks of ${login} are double quotes, since we want the actual variable value, not plain text ${login}.

Stage 4: Docker Push

Now that we have a docker image file, we can push to the docker registry, for future use.

Post Stage: Trigger Another Job

Now the CI stage has successfully passed, we might want to trigger another job for deployment. So we can create another build job called TestJob-CD.
The success post stage only executes when this job is finished successfully. If there is error during execution, it won’t trigger the CD job.
You can find other types of post triggers here.

We’ve come to the end of this tutorial! In the next post, I will talk about the CD part of Jenkins.