Basic DevOps CI/CD Pipeline #3
- #devops
- #ci/cd
- #jenkins
- #ansible
- #docker
Before reading this blog, check out the first part and the second part of the series.
I assume you have already installed Ansible and are familiar with the basics. If not, feel free to check out the What is Ansible blog.
Docker also needs to be installed on the target server. You can follow the installation steps in the first part.
In this part, we’ll prepare an Ansible playbook to deploy the Docker image we built in the second part onto another server.
Ansible Playbook for Deployment
We’ll use the docker_image module to manage Docker images and the docker_container module to manage Docker containers. For more information, refer to the official documentation.
Pulling the Docker Image
First, we’ll pull the image from DockerHub:
---
- hosts: appserver1
tasks:
- name: Pull application Docker image
docker_image:
name: "yourdockerhubuser/javaapp:{{ version }}"
source: pull
In the Docker image name, we’ve used a parameter ({{ version }}) that will be provided in the Jenkinsfile.
Running the Docker Containers
After pulling the image, we’ll run it in containers:
- name: Create application containers
docker_container:
name: "application-{{ item }}"
image: "yourdockerhubuser/javaapp:{{ version }}"
state: started
with_sequence: count=2
Here, item is a variable, and with_sequence is a loop that creates multiple containers. We’re specifying a count of 2, so Ansible will create two containers named application-1 and application-2.
Integrating with Jenkins
We’ll pass the version variable in the Jenkinsfile. The version should correspond to the build number used in the Docker build and push pipeline.
Adding a Parameter to the Jenkins Pipeline
- Enable “This project is parameterized” in your Jenkins job configuration.
- Add a String Parameter named
version.
Jenkins Pipeline Script
Here’s how to integrate the Ansible playbook into the Jenkins pipeline:
pipeline {
agent any
stages {
stage('Deploy') {
steps {
ansiblePlaybook([
inventory : 'hosts',
playbook : 'deploy.yml',
installation: 'ansible',
colorized : true,
extraVars : [
version : "$version"
]
])
}
}
}
}
In this script:
inventory: Specifies the Ansible inventory file.playbook: Specifies the Ansible playbook file.installation: Refers to the Ansible installation configured in Jenkins.extraVars: Passes theversionvariable to the playbook.
By following these steps, you can automate the deployment of your Docker images using Ansible and integrate the process into your Jenkins pipeline.