Understanding Jenkinsfile, Ansible, and GitHub Actions Simplified.

#JENKINSFILE
pipeline {
agent any
environment {
// Using SSH key stored in Jenkins credentials
EC2_SSH_KEY = credentials('EC2_SSH')
ANSIBLE_HOST_KEY_CHECKING = 'False'
}
stages {
stage('Checkout') {
steps {
// Checkout the code from the GitHub repository
checkout scm
}
}
stage('Run Ansible Playbook') {
steps {
script {
// Running Ansible Playbook to configure the server
sh '''
ansible-playbook -i ./ansible/inventory.aws_ec2.yml -e 'host_group=tag_git_gitaction' ./ansible/playbooks/nginx-setup.yml -u ubuntu --private-key $EC2_SSH_KEY
'''
}
}
}
}
}
Explanation of the above jenkinsfile:
EC2_SSH_KEY = credentials('EC2_SSH') - This will bring the EC2_SSH credential from the jenkins credential to SSH on server which ansible is use.
steps {
checkout scm
} - This will clone the repo in the jenkins job workspace and search for jenkinsfile.sh ''' ansible-playbook -i ./ansible/inventory.aws_ec2.yml -e 'host_group=tag_git_gitaction' ./ansible/playbooks/nginx-setup.yml -u ubuntu --private-key $EC2_SSH_KEY ''' - This will trigger the ansible to perform task by using inventory.aws_ec2.yml as inventory, nginx-setup.yml as playbook, host_group=tag_git_gitaction as a variable which will be used inside playbook.
ANSIBLE Inventory
#inventory.aws_ec2.yml-
plugin: aws_ec2
regions:
- us-east-1
filters:
"tag:git": "gitaction"
strict: true
keyed_groups:
- prefix: tag
key: tags
Work of ansible inventory is to search for the IPs of the basis of the filter you define in the inventory and provide them to the ansible playbook to perform tasks.
Explanation of the above ansible inventory:
1. regions: - us-east-1 - region is defined where to search.
2. filters: "tag:git": "gitaction" - tags defined in the EC2 tags.
ANSIBLE Playbook
#nginx-setup.yml -
---
- name: Install and Configure Nginx
hosts: "{{ host_group }}"
become: yes
tasks:
- name: Install Nginx
apt:
name: nginx
state: present
- name: Start Nginx service
systemd:
name: nginx
state: started
enabled: yes
- name: Remove default index.html
file:
path: /var/www/html/index.html
state: absent
- name: Clone custom HTML page from GitHub
git:
repo: 'https://github.com/<user-name>/<repo-name>'
dest: /var/www/html
clone: yes
update: yes
force: yes
- name: Restart Nginx service
systemd:
name: nginx
state: restarted
Explanation of the above ansible playbook:
hosts: "{{ host_group }}" - IP will be passed here by inventory.
Tasks of ansible-
- name: Install Nginx- name: Start Nginx service
- name: Remove default index.html
- name: Clone custom HTML page from GitHub
- name: Restart Nginx service
Subscribe to my newsletter
Read articles from Prem Choudhary directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Prem Choudhary
Prem Choudhary
DEVOPS ENGINEER | AWS | Java | Linux | Python | Git | Github | Docker | Spring Boot | Ansible | Jenkins | Algorithmic Trader | Pine Editior