AWS and Jenkins

AWS and Jenkins

In the previous post, we show how to run a sample web application on AWS EC2. In practice, this task called CD (continuous deployment) is automatically done by Jenkins. In this blog, I am going to show how to do it in Jenkins.

Install Jenkins Plugin and Create SSH Credential

Since we are going to connect to EC2 with SSH in Jenkins, we need to install a plugin called "SSH Agent".

We use a multi-branch pipeline that has its credential scope.

Copy the SSH private key to the credential.

Configure and Run Jenkins Job

In Jenkinsfile, we add the following step.

stage('deploy'){  
   steps{  
      script{  
         def dockerCmd = 'docker run -p 3080:3080 -d stevenchen521/react-nodejs-example:1.0'  
         sshagent(['ec2-server-key']){  
            sh "ssh -o StrictHostKeyChecking=no ec2-user@23.20.218.114 ${dockerCmd}"  
         }  

      }  
   }  
}ggjen

We also need to open port 3080 on EC2. Here considering it is the test purpose we do not restrict the IP address.

Before we run the Jenkins job, we log on to EC2 and check there is no running container. Here is the result.

[ec2-user@ip-10-1-1-108 ~]$ docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[ec2-user@ip-10-1-1-108 ~]$ docker images
REPOSITORY   TAG       IMAGE ID   CREATED   SIZE
[ec2-user@ip-10-1-1-108 ~]$

Run the job successfully.

Then we check the EC2 and the app container is running as expected.

[ec2-user@ip-10-1-1-108 ~]$ docker ps
CONTAINER ID   IMAGE                                    COMMAND                  CREATED              STATUS              PORTS                                       NAMES
ee7c67d7df8f   stevenchen521/react-nodejs-example:1.0   "docker-entrypoint.s…"   About a minute ago   Up About a minute   0.0.0.0:3080->3080/tcp, :::3080->3080/tcp   zealous_sinoussi

Summary

In this post, we show how to log on to the EC2 server in the Jenkins job and run a docker container.

Reference

Module 9 of DevOps Bootcamp