Integrate Ansible with Jenkins

Please visit my website and subscribe to my youtube channel for more articles

https://devops4solutions.com/

In this blog, we will Integrate Ansible with Jenkins

Prerequistie

  1. Jenkins Server
  2. Ansible Server installed on Jenkins Server
  3. Ansible Plugin
  4. ./ssh/config created for Jenkins user

Steps:

  1. Go to Jenkins -> Manage Plugins -> Ansible

Configure -

Go to Manage Jenkins -> Global Tool configuration ->Search for Ansible

Image for post

Create a pipeline job in Jenkins

pipeline {
agent any

stages {
stage('checkout') {
steps {

git branch: 'develop', url: 'yoururl'

}
}



stage('Ansible Init') {
steps {
script {

def tfHome = tool name: 'Ansible'
env.PATH = "${tfHome}:${env.PATH}"
sh 'ansible --version'

}
}
}



stage('Ansible Deploy') {

steps {

dir('dev/ansible')
{

sh 'ansible all -m ping -i hosts'

}
}
}

Commit hosts file and ansible.cfg file with your configuration in your source control.

For ssh config file, you can also put in your source control and it will take all configuration from there. But for the host “test” which is getting invoked through proxy will not work directly. You have to add this same ssh config under the jenkins user as “config” name

Image for post
Host dev
Hostname 2.3.34.4
User ubuntu
StrictHostKeyChecking no
IdentityFile ~/terraform-deploy
Host test
Hostname 2.3.4.3
User ubuntu
StrictHostKeyChecking no
IdentityFile ~/terraform-deploy
ProxyCommand ssh -W %h:%p dev

After this, when you trigger Jenkins job it will ping all the host successfully. If you have not added the config file under Jenkins user then it will fail while ping to the test server with the error

"changed": false, 
"msg": "Failed to connect to the host via ssh: ssh: Could not resolve hostname dev: Name or service not known\r\nssh_exchange_identification: Connection closed by remote host\r\n",
"unreachable": true
}

If all configuration is ok, you will get the below output

Running in /var/lib/jenkins/workspace/TerraformScripts/Ansible_Test/dev/ansible
[Pipeline] {
[Pipeline] sh
[ansible] Running shell script
+ ansible all -m ping -i hosts
dev | SUCCESS => {
"changed": false,
"ping": "pong"
}
test | SUCCESS => {
"changed": false,
"ping": "pong"
}

Written by

Devops Automation Enginneer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store