Showing posts with label Playbook. Show all posts
Showing posts with label Playbook. Show all posts

Tuesday, 16 July 2024

How to Use Jenkinsfile to connect into Ansible Tower and execute a server reboot running a ansible playbook ?

Let’s create a Jenkinsfile that integrates with Ansible Tower and executes a playbook to reboot a server. We’ll also include parameters for environment, target hostname group, and boolean options.


First, make sure you have the following prerequisites:

  1. Jenkins: Set up Jenkins on your system.
  2. Ansible Tower: Ensure you have Ansible Tower installed and configured.
  3. SSH Key Pair: Set up an SSH key pair for authentication between Jenkins and Ansible Tower.

Now, let’s create the Jenkinsfile:

pipeline {
    agent any

    parameters {
        string(name: 'ENV', description: 'Environment (e.g., dev, staging, prod)')
        string(name: 'TARGET_HOSTNAME_GROUP', description: 'Ansible inventory group for target hosts')
        booleanParam(name: 'REBOOT_ENABLED', defaultValue: true, description: 'Enable server reboot')
    }

    stages {
        stage('Checkout') {
            steps {
                checkout scm
            }
        }

        stage('Run Ansible Playbook') {
            steps {
                script {
                    def ansiblePlaybookCmd = """
                        ansible-playbook -i ${TARGET_HOSTNAME_GROUP} playbook.yml
                        --extra-vars 'reboot_enabled=${REBOOT_ENABLED}'
                    """
                    sh ansiblePlaybookCmd
                }
            }
        }
    }
}

Explanation:

  • The Jenkinsfile defines a pipeline with two stages: “Checkout” and “Run Ansible Playbook.”
  • We use parameters to allow users to input the environment, target hostname group, and whether to enable server reboot.
  • In the “Run Ansible Playbook” stage, we execute the Ansible playbook using the provided parameters.
  • The ansible-playbook command includes the inventory group and an extra variable (reboot_enabled) to control the reboot behavior.


Make sure to adjust the playbook.yml path and customize the playbook according to your specific requirements. Additionally, ensure that Jenkins has the necessary permissions to execute Ansible playbooks on the target hosts.

Remember to replace placeholders (such as ${TARGET_HOSTNAME_GROUP}) with actual values in your environment. If you encounter any issues, feel free to ask for further assistance! 🚀


- For more information on integrating Ansible with Jenkins, you can explore the official Ansible Tower plugin for Jenkins1

- Additionally, check out the Red Hat blog post on integrating Ansible with Jenkins in a CI/CD process2..

####################################################################


Let’s enhance the Jenkinsfile by adding the three boolean parameters: rebootstop_application, and start_application. These parameters will allow you to control additional actions during your pipeline execution. Here’s the updated Jenkinsfile:


pipeline {
    agent any

    parameters {
        string(name: 'ENV', description: 'Environment (e.g., dev, staging, prod)')
        string(name: 'TARGET_HOSTNAME_GROUP', description: 'Ansible inventory group for target hosts')
        booleanParam(name: 'REBOOT_ENABLED', defaultValue: true, description: 'Enable server reboot')
        booleanParam(name: 'STOP_APP_ENABLED', defaultValue: false, description: 'Stop application before reboot')
        booleanParam(name: 'START_APP_ENABLED', defaultValue: false, description: 'Start application after reboot')
    }

    stages {
        stage('Checkout') {
            steps {
                checkout scm
            }
        }

        stage('Run Ansible Playbook') {
            steps {
                script {
                    def ansiblePlaybookCmd = """
                        ansible-playbook -i ${TARGET_HOSTNAME_GROUP} playbook.yml
                        --extra-vars 'reboot_enabled=${REBOOT_ENABLED}'
                        --extra-vars 'stop_app_enabled=${STOP_APP_ENABLED}'
                        --extra-vars 'start_app_enabled=${START_APP_ENABLED}'
                    """
                    sh ansiblePlaybookCmd
                }
            }
        }
    }
}

Explanation:

  • I’ve added three new boolean parameters: STOP_APP_ENABLED and START_APP_ENABLED.
  • If STOP_APP_ENABLED is set to true, the pipeline will stop the application before rebooting the server.
  • If START_APP_ENABLED is set to true, the pipeline will start the application after the server reboot.

Remember to adjust the playbook (playbook.yml) to handle these additional actions based on the provided parameters. Feel free to customize the playbook according to your specific requirements.

Thursday, 25 April 2024

How to Create a Ansible Lab on your Local Machine using Vagrant in 5 min using ChatGPT


This is an exciting experiment of mine as DevOps. As I am experimenting with the Tools available ... So, the quest is to "Vagrantfile which creates 3 instances of Centos 8 servers, each server shall be able to connect on the same network for easy communication"

Here is what we want to achieve:

- Build 3 servers to use Ansible

Jumped into via ChatGPT via Bing Copilot and created the following prompt.


"Hi Copilot, can you write a Vagrantfile which creates 3 instances of Centos 8 servers, each server shall be able to connect on the same network for easy communication, these instance serves are to be used as Ansible Lab environments comprised of one Ansible Tower and two deployments environments, please"


The output:

# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|
  # Define the base box
  config.vm.box = "centos/8"

  # Ansible Tower Server
  config.vm.define "ansible_tower" do |ansible_tower|
    ansible_tower.vm.hostname = "ansible-tower"
    ansible_tower.vm.network "private_network", ip: "192.168.56.10"
  end

  # Deployment Environment 1
  config.vm.define "deploy_env1" do |deploy_env1|
    deploy_env1.vm.hostname = "deploy-env1"
    deploy_env1.vm.network "private_network", ip: "192.168.56.11"
  end

  # Deployment Environment 2
  config.vm.define "deploy_env2" do |deploy_env2|
    deploy_env2.vm.hostname = "deploy-env2"
    deploy_env2.vm.network "private_network", ip: "192.168.56.12"
  end

  # Provisioning with Ansible (Optional)
  # config.vm.provision "ansible" do |ansible|
  #   ansible.playbook = "playbook.yml"
  # end
end

Source code on Git Hub repository.

To use this Vagrantfile:

  1. Install VirtualBox and Vagrant on your system.
  2. Save the above code into a file named Vagrantfile.
  3. Open a terminal and navigate to the directory containing the Vagrantfile.
  4. Run vagrant up to create the VMs.

This Vagrantfile configures each CentOS 8 server with a static IP on a private network, allowing them to communicate with each other. You can uncomment and adjust the Ansible provisioning block to run your Ansible playbooks automatically.

You’ll have three CentOS 8 servers (server1, server2, and server3) along with an Ansible Tower instance (ansible-tower) for your lab environment. Adjust memory and CPU settings as needed based on your system resources.

Happy Ansible-ing! 🚀

Next - 

To test the Ansible connection to the three CentOS 8 servers you've set up, you can use a simple Ansible playbook that employs the ping module. This module is specifically designed for connection testing and doesn't actually send ICMP pings but attempts an SSH connection and returns pong on success.

Here's an example playbook, test_connection.yml, that you can use:


yaml
--- - name: Test Ansible Connection to Servers hosts: all gather_facts: no tasks: - name: Test connectivity with ping module ansible.builtin.ping:

Before running the playbook, ensure you have an inventory file (inventory.ini or your preferred name) that lists the IPs or hostnames of your servers under a group [servers] or individually. Here's an example:

javascript
[servers] 192.168.56.10 ansible_user=your_username ansible_ssh_private_key_file=/path/to/private_key 192.168.56.11 ansible_user=your_username ansible_ssh_private_key_file=/path/to/private_key 192.168.56.12 ansible_user=your_username ansible_ssh_private_key_file=/path/to/private_key


Replace your_username and /path/to/private_key with the appropriate user and SSH key path for your setup.

To run the playbook and test the connection to all servers in your inventory, use the following command:

bash
ansible-playbook -i inventory.ini test_connection.yml

This command will attempt to connect to each server listed in inventory.ini and report back whether the connection was successful.
....

Nice !! Now, let us push this code further ..  I have tested the script on my machine and Made all 3 instances up and running.  Further improved the code and stored in Github source code here

Here the code on VisualCode:


Continue on  part 2


🌐 Sourcesmedium.com - How to Create Multiple Virtual Machines Using Vagrant Tool

stackoverflow.com - Two Operating Systems in a single Vagrantfile



Friday, 5 April 2024

I working with Ansible Playbook to get a count on the output of shell command, using the following task

 


I working with Ansible Playbook to get a count on the output of shell command, using the following task,


" - name: Check running number of JVM Services shell: ps -H -fu "{{ backendAppUser }}" register: apps_count become: yes become_user: "{{ backendAppUser }}" - name: Display Register var debug: var: apps_count.stdout" , however while running the task, I am getting a following error ("apps_count.stdout": "VARIABLE IS NOT DEFINED!: 'dict object' has not attribute ''stdout"


I'll address the error, provide a solution, and create a working configuration:

Understanding the Error:

  • The error "VARIABLE IS NOT DEFINED!: 'dict object' has not attribute 'stdout'" indicates that the variable apps_count exists as a dictionary, but it does not contain a key named stdout. This means the shell command's output is not being captured as expected.

Resolving the Issue:

  1. Ensure Correct Shell Command:

    • Verify that the ps -H -fu "{{ backendAppUser }}" command produces expected output when executed manually on the target host.
    • If necessary, adjust the command or consider using Ansible's command module, as it's generally more reliable for capturing output.
  2. Modify Playbook Tasks:

    • Register Output: Use register: apps_count to capture the result of the shell command, regardless of whether it's captured under stdout or another key.

    • Check for Correct Output Structure: If the output structure is different (e.g., doesn't contain stdout), use a suitable key to access the output, such as apps_count.output or other available keys.

Working Configuration:

YAML
- name: Check running number of JVM Services
  command: ps -H -fu "{{ backendAppUser }}"
  register: apps_count
  become: yes
  become_user: "{{ backendAppUser }}"

- name: Display Register var
  debug:
    var: apps_count.output

Explanation:

  • The command module is used, as it generally captures output more reliably.
  • The register: apps_count captures the output in the apps_count variable.
  • The debug task now displays apps_count.output to ensure the correct output is accessed.

Additional Tips:

  • Use failed_when: Consider using failed_when: apps_count.rc != 0 to make the playbook fail if the command returns a non-zero exit code.
  • Explore set_fact: If you need to process the output further, use set_fact to create custom variables based on the captured output.
  • Test Thoroughly: Test the configuration with a small selection of hosts before deploying it widely.

By following these steps and using the provided configuration, you should be able to successfully capture and display the output of the shell command in your Ansible playbook.

How to check for open ports on Linux

Checking for open ports is among the first steps to secure your device. Listening services may be the entrance for attackers who may exploit...