In this tutorial, I will integrate Ansible into the Jenkins CI/CD pipeline. Now, let’s go to DevOps CI/CD pipeline tutorial part 4.
Table of Contents
The content is
- Install Ansible on Amazon EC2
- How to integrate Ansible with Jenkins
- Create an Ansible playbook
- Jenkins job to deploy on Docker container through DockerHub
- Jenkin’s job to deploy a war file on Docker container using Ansible.
Install Ansible on Amazon EC2
Prerequisites
- Amazon Linux EC2 Instance
Installation steps
Install python and python-pip
[root@Ansible_host ~]# yum install python
[root@Ansible_host ~]# yum install python-pipUsing pip command install Ansible
[root@Ansible_host ~]# pip install ansible
[root@Ansible_host ~]# ansible --versionCreate a user called for Ansible
[root@Ansible_host ~]# useradd ansibleadmin
[root@Ansible_host ~]# passwd ansibleadmingrant sudo access to ansibleadmin user.
[root@Ansible_host ~]# echo "ansibleadmin ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoersLogin ansibleadmin user and generate key
ssh-keygenCopy keys to the target server.
ssh-copy-id ansibleadmin@<target-server>
Ansible server used to create images and store them on the docker registry.
yum install docker
service docker status
service docker start
usermod -aG docker ansibleadminCreate a folder /opt/ansible and hosts file for inventory file add control node and manged hosts IP address to it.
Validating test Ansible
Run ansible command as ansibleadmin user.
ansible all -m pingHow to integrate Ansible with Jenkins
You need to Install “publish Over SSH” as below
Manage Jenkins > Manage Plugins > Available > Publish over SSH
Enable connection between Ansible-control-node and Jenkins as below.
Manage Jenkins > Configure System > Publish Over SSH > SSH Servers 
Example,
- SSH Servers:
- Name: ansible-server
- Hostname:<ServerIP>
- username: ansibleadmin
- Click Advanced> chose- Use password authentication, or use a different key.
Create an Ansible playbook
I will create a simple Ansible playbook as below
---
- hosts: 172.13.13.4
  become: true
  tasks:
  - name: Stop old docker container
    command: docker stop devops-container
    ignore_errors: yes
  - name: Remove stopped docker container
    command: docker rm devops-container
    ignore_errors: yes
  - name: Remove current docker image
    command: docker rmi devops-image
    ignore_errors: yes
  - name: Building docker image
    command: docker build -t devops-image .
    args:
      chdir: /opt/docker
  - name: creating docker image
    command: docker run -d --name devops-container -p 8080:8080 devops-image
Run Ansible playbook
ansible-playbook -i hosts simple-devops.yml
