Basic DevOps CI/CD Pipeline #3

Before reading this blog, check out the first part & the second part of the series;

I assume you already installed the Ansible and, knew about the basics. If not feel free to check out the What is Ansible blog.

Docker also need to be installed on the target server. You can follow the installation steps on first part.

We’ll prepare an ansible-playbook to deploy our image that we built within the second part on another server;

We are going to use docker_image module to manage docker image & docker_container module to manage docker containers. For more info check out the official documentation.

We will firstly pull the image from DockerHub with;

---
- hosts: appserver1
  tasks:
    - name: Pull application Docker image
      docker_image:
        name: "yourdockerhubuser/javaapp:{{ version }}"
        source: pull

As you can see at the name of the Docker image, we used  a parameter that will be given on Jenkinsfile.
On the Jenkins side, we need to install another plugin to trigger Ansible playbook; Ansible plugin.

Then, after pulling we need to run this image on containers;

    - name: Create application containers
      docker_container:
        name: "application-{{ item }}"
        image:"yourdockerhubuser/javaapp:{{ version }}"
        state: started
      with_sequence: count=2

But what is item variable and with_sequence thing?

There are several ways to use item variable on Ansible playbook and with_sequence is one of them. We basically gave a container count to ansible and also use it in naming; We are expecting 2 containers named application-1 & application-2.

Okay, another question: How do we pass version variable on Jenkinsfile & What should it be?

We used build number as the version on Docker build & push Jenkins pipeline, so we should use the same on here. And, here is the how;

Firstly, we need to add a parameter on our Deployment pipeline, to do it you need to enable “This project is parameterized“, then add a String Parameter for version.

pipeline {
    agent any
    stages {
        stage('Deploy') {
            steps{
                ansiblePlaybook([
                    inventory   : 'hosts',
                    playbook    : 'deploy.yml',
                    installation: 'ansible',
                    colorized   : true,
                    extraVars   : [
                        version : "$version"
                    ]
                ])
            }
        }
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *