Using Ansible in Jenkins – Ansible Plugin

Jenkins + Ansible Options

I have been doing a lot of Jenkins, Ansible, Terraform, and similar automations lately and I have seen multiple ways of running Ansible in Jenkins.  These include:

  1. Install Ansible on your Jenkins node and call it with “sh” in a pipeline.
  2. Install Ansible on your Jenkins node and call it with the ansible plugin for Jenkins (not a default plugin).
  3. Run a docker image with Jenkins and configure ansible there.

I think the 3rd option is the most powerful as you can separately configure and version Ansible for your various Jenkins jobs.  But the second option is pretty sleek as well and is what we’ll talk about here.

Jenkins Ansible Plugin

If you go to the Jenkins plugins management page, you can install the ansible plugin pretty easily.  There are some good documents on it right here too.  After installing that plugin, I also suggest you install the AnsiColor plugin.

With both of those in place, you can get ansible running your playbooks with its private key credentials and it will print beautiful colored output to your logs.

Here is an example of how to call it from a pipeline.  Note that this lets you specify your target hosts in a CSV, assuming your playbook uses the “target_hosts” group.  It also disables host key checking (which took me a while to work out as the docs are wrong).  For some reason my ssh wouldn’t work without that setting with this plugin even though it is not ideal.

pipeline {
    agent any

    parameters {
        string(name: 'GIT_BRANCH', defaultValue: 'master', description: 'git branch to work from.')
        string(name: 'TARGET_HOSTS_CSV', defaultValue: 'none', description: 'target deployment hosts.')
    }

    stages {
        stage('Deploy application.') {
            steps {
                sh 'echo [target_hosts] > /tmp/inventory.ini'
                sh 'echo "${TARGET_HOSTS_CSV}" | tr "," "\n" >> /tmp/inventory.ini'

                ansiColor('xterm') {
                    ansiblePlaybook(
                        playbook: './ansible/playbook.yml',
                        inventory: '/tmp/inventory.ini',
                        credentialsId: 'your-jenkins-pk-credential',
                        disableHostKeyChecking: true,
                        colorized: true)
                }
            }

        }
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s