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.
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.
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.
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
.
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.
version
.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 the version
variable 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.