The goal of this project is to automate the installation and configuration of Jenkins using Ansible. The setup will include:
sudo apt update -y
sudo apt upgrade -y
sudo apt install -y openjdk-11-jdk git curl ansible
Use a Terraform script to create the EC2 instance and Security Group rules.
Create an Ansible Playbook (jenkins-install.yml)
---
- name: Install and Configure Jenkins
hosts: jenkins
become: yes
tasks:
- name: Install Java
apt:
name: openjdk-11-jdk
state: present
- name: Add Jenkins Repository Key
apt_key:
url: https://pkg.jenkins.io/debian/jenkins.io.key
state: present
- name: Add Jenkins Repository
apt_repository:
repo: "deb http://pkg.jenkins.io/debian-stable binary/"
state: present
- name: Install Jenkins
apt:
name: jenkins
state: present
update_cache: yes
- name: Start and Enable Jenkins
systemd:
name: jenkins
enabled: yes
state: started
ansible-playbook -i inventory jenkins-install.yml
Create an Ansible task file (jenkins-plugins.yml):
---
- name: Install Jenkins Plugins
hosts: jenkins
become: yes
tasks:
- name: Install required Jenkins plugins
jenkins_plugin:
name: "{{ item }}"
state: present
with_items:
- git
- job-dsl
- pipeline
- ansicolor
- docker-plugin
- ansible
Run the Playbook:
ansible-playbook -i inventory jenkins-plugins.yml
Use Jenkins Job DSL Plugin to automate job creation.
Create a Job DSL File (seed-job.groovy):
pipelineJob('Sample-Pipeline') {
definition {
cps {
script("""
pipeline {
agent any
stages {
stage('Clone Repo') {
steps {
git 'https://github.com/user/repo.git'
}
}
stage('Build') {
steps {
sh 'mvn clean install'
}
}
}
}
""".stripIndent())
}
}
}
Create an Ansible Playbook for Job Configuration (jenkins-job.yml):
---
- name: Create Jenkins Job
hosts: jenkins
tasks:
- name: Create a new job
uri:
url: "http://localhost:8080/createItem?name=Sample-Pipeline"
method: POST
user: "admin"
password: "admin"
body: "{{ lookup('file', 'seed-job.groovy') }}"
force_basic_auth: yes
status_code: 200,201
ansible-playbook -i inventory jenkins-job.yml
Once the setup is complete:
This Task provides a fully automated Jenkins CI/CD pipeline using Ansible, enabling fast, reliable, and repeatable deployments! 🚀