# 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".

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1672499268808/b3c0734d-2051-439c-a7ea-74ab1aff1f37.png align="center")

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

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1672499278209/216f70a4-374e-409e-a2ba-be7a940819b1.png align="center")

Copy the SSH private key to the credential.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1672499308487/b088fa44-8305-4861-bda9-b9299569d82b.png align="center")

# Configure and Run Jenkins Job

In Jenkinsfile, we add the following step.

```bash
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.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1672499363197/e2466acf-a648-48db-b234-f9c4e7d5aa7c.png align="center")

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

```bash
[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.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1672499432288/a6119dbf-2917-45d0-bc68-03d92ca2cf31.png align="center")

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

```bash
[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
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1672499456222/72ece1b1-0614-4a8c-9228-c9ca1a7acd64.png align="center")

# 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](%5Bhttps://www.techworld-with-nana.com/devops-bootcamp%5D(https://www.techworld-with-nana.com/devops-bootcamp))
