Ansible and Jenkins Remote Triggers
Ansible Tower has an awesome feature that I’ve talked about before called provisioning callbacks. It’s hard to beat their simplicity, one click of a button and you have an API endpoint and a key to use. However you can replicate this in Jenkins with just about the same amount of work. Coming from using both Tower and Jenkins, I currently prefer to use Jenkins. I find it a little more flexible.
To pull this off it will be easier if you have the Ansible Plugin for Jenkins. This works with either a pipeline or freestyle job, but pipelines are the preferred way.
Make sure to set up a user token before beginning.
In your job check the
Trigger builds remotely option. This will open a text box for you to add a token and also gives you the endpoint for your API call.
Now that you have this information you’re 50% of the way there. The only other bit you need is some way to trigger the job. In this case we’ll just use a Bash script that calls a cURL command. You will need your username and token if you have authentication enabled to get the crumb.
#!/bin/bash JENKINS_CRUMB=$(curl --user username:user_token https://JENKINS_URL/crumbIssuer/api/xml?xpath=concat\(//crumbRequestField,%22:%22,//crumb\)) curl -H $JENKINS_CRUMB -X POST --user username:user_token \ https://JENKINS_URL/job/Ansible%20Jobs/job/Hardening%20Playbook/buildWithParameters?token=YOUR_TYPED_TOKEN&PARAMETER=value
This script has 2 parts. The first is the request to get the crumb from the Jenkins server. The second is cURL request. This includes the user and user token which has permissions to run the job in Jenkins and the API endpoint given to you in Jenkins including any parameters.
If you don’t have parameters the endpoint ends with this:
Now all you need to do is set this script up in some type of automation, as a cronjob, or a systemd service with a timer and you can do whatever you could do with provisioning callbacks.