pipeline { agent any // Define parameters parameters { string(name: 'host_ip', description: 'Target System Address') } environment { ANSIBLE_FORCE_COLOR = '1' cosmos_password = credentials('cosmos_password') cosmos_root_password = credentials('cosmos_root_password') matt_private_key = credentials('matt_private_key') matt_public_key = credentials('matt_public_key') } options { ansiColor('xterm') } stages { stage('Generate Inventory File') { steps { // Generate the dynamic inventory file sh """ jenkins_group=\$(echo ${env.BUILD_USER_GROUPS} | sed 's/,/\\n/g' | grep -v \$SERVER_SUBNET_GROUP | grep Jenkins | head -n 1) jenkins_subnet_group=\$(echo ${env.BUILD_USER_GROUPS} | sed 's/,/\\n/g' | grep -e authenticated -e \$SERVER_SUBNET_GROUP | sort -rf | head -n 1) jenkins_user=\$(echo ${env.BUILD_USER}) cd /var/jenkins_home/ansible chmod +x /var/jenkins_home/ansible/inventory/inventory.sh /var/jenkins_home/ansible/inventory/inventory.sh -s -a \$jenkins_subnet_group -g \$jenkins_group -u \$jenkins_user -i ${params.host_ip} echo 'echo Hello World' > /var/jenkins_home/ansible/.inv/vpn_check.sh chmod +x /var/jenkins_home/ansible/.inv/vpn_check.sh """ } } stage('Ansible Playbook') { steps { //Run the cosmos-base ansible playbook // /workspace/ansible/playbooks/cosmos-base.yaml sh """ echo ${params.host_ip} hash=\$(echo -n ${params.host_ip} | md5sum | cut -c 1-8) inventory_file="/var/jenkins_home/ansible/.inv/inventory-\$hash.yml" cd /var/jenkins_home/ansible ansible-playbook -i \$inventory_file /var/jenkins_home/ansible/playbooks/jenkins_vpn.yaml \ --ssh-common-args='-o StrictHostKeyChecking=no' \ --extra-vars "new_hostname=${params.new_hostname}.home.cosmos vpn_endpoint='${params.vpn_endpoint}' \ cosmos_password='${env.cosmos_password}' cosmos_root_password='${env.cosmos_root_password}' \ matt_public_key='${env.matt_public_key}' matt_private_key='${env.matt_private_key}' " """ } } stage('Ping new VPN host') { steps { // Generate the dynamic inventory file sh """ /var/jenkins_home/ansible/.inv/vpn_check.sh """ } } } post { always { // Remove dynamic Inventory file and ping file sh """ hash=\$(echo -n "${params.host_ip}" | md5sum | cut -c 1-8) inventory_file="/var/jenkins_home/ansible/.inv/inventory-\$hash.yml" rm \$inventory_file rm /var/jenkins_home/ansible/.inv/vpn_check.sh """ } } }