How to Set Up a Jenkins Pipeline Triggered by GitHub Webhook to Run Ansible Playbooks


Prerequisites
Jenkins installed and running
Jenkins server accessible from GitHub (publicly or via tunneling)
GitHub repository with your Ansible playbooks
Jenkins plugins installed: Git, Pipeline, GitHub Integration
SSH key (
.pem
file) configured with correct permissions for your target servers.
Step 1: Create a Jenkins Pipeline Job
Open Jenkins dashboard.
Click New Item.
Enter a name for your pipeline, e.g.,
ansible-deployment-pipeline
.Select Pipeline and click OK.
Step 2: Configure Pipeline Parameters and Environment Variables
Add parameters like
Pipeline_name
andAnsible_playbook
(select from available playbooks).Set environment variables for your GitHub repo URL and Ansible playbook directory.
Example snippet in your Jenkinsfile:
environment {
GIT_REPO_URL = 'https://github.com/yourusername/your-ansible-repo.git'
ANSIBLE_DIR = "/var/lib/jenkins/workspace/${params.Pipeline_name}/ansible/"
}
parameters {
string(name: "Pipeline_name", defaultValue: "", description: "Enter pipeline name")
choice(name: 'Ansible_playbook', choices: ['nginx-install.yml', 'nginx-uninstall.yml', 'reboot.yml', 'update-kernel.yml'], description: 'Select Ansible playbook')
}
Step 3: Set Up Git Checkout Stage
Add a stage in your Jenkinsfile to checkout code from GitHub:
stage('Checkout SCM') {
steps {
checkout([$class: 'GitSCM', branches: [[name: '*/main']], userRemoteConfigs: [[url: env.GIT_REPO_URL]]])
}
}
Make sure to replace main
with your branch name.
Step 4: Set File Permissions (Optional)
If your Ansible playbook needs access to an SSH key, modify its permissions:
stage('Modify pem file permission') {
steps {
dir("${env.ANSIBLE_DIR}") {
sh "sudo chmod 400 yourkey.pem"
}
}
}
Step 5: Execute Ansible Playbook
Run the selected playbook using the Jenkins pipeline:
stage('Execute the pipeline') {
steps {
dir("${env.ANSIBLE_DIR}") {
sh "sudo ansible-playbook -i hosts ${params.Ansible_playbook} -b"
}
}
}
Step 6: Configure GitHub Webhook
In your GitHub repo, go to Settings > Webhooks.
Click Add webhook.
Enter your Jenkins server webhook URL:
http://<jenkins-server-url>/github-webhook/
Set Content type to
application/json
.Select Just the push event.
Click Add webhook.
Step 7: Configure Jenkins to Listen to Webhook Events
In your Jenkins pipeline job, go to Configure > Build Triggers.
Check GitHub hook trigger for GITScm polling.
Save the configuration.
Step 8: Test the Pipeline
Push a commit to the GitHub repository branch.
The webhook will trigger Jenkins.
Jenkins will run the pipeline and execute the Ansible playbook.
Subscribe to my newsletter
Read articles from Durkesh blogs directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
