Showing posts with label Pipeline. Show all posts
Showing posts with label Pipeline. 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.

Monday, 1 July 2024

How to Reboot RedHat Server 9 using Jenkins and Ansible Playbooks

 In order for you to automate the process of Reboot RedHat Servers with Jenkins and Ansible Playbooks.

You have to create a Jenkins pipeline for an application that involves the following steps: rebooting a Red Hat Server 9 using Ansible Playbooks, building, testing, scanning with SonarQube and Fortify, and storing the artifact in JFrog Artifactory. 

Below are the detailed steps along with the required Jenkinsfile, Ansible playbook, and information on the necessary credentials.

Prerequisites

  1. Jenkins Setup:

    • Jenkins should be installed and configured.
    • Plugins: Ansible, SonarQube Scanner, Fortify, JFrog Artifactory.
  2. Credentials:

    • Ansible: SSH Key for Red Hat Server.
    • SonarQube: API Token.
    • Fortify: API Token.
    • JFrog Artifactory: Username and API Key.
  3. Tools:

    • Ansible installed and configured on Jenkins.
    • SonarQube and Fortify servers accessible from Jenkins.
    • JFrog Artifactory accessible from Jenkins.

Jenkins Pipeline Script (Jenkinsfile)

groovy
pipeline { agent any environment { ANSIBLE_PLAYBOOK = 'reboot-server.yml' ANSIBLE_INVENTORY = 'hosts' SONARQUBE_SERVER = 'sonarqube.example.com' SONARQUBE_TOKEN = credentials('sonarqube-token') FORTIFY_SERVER = 'fortify.example.com' FORTIFY_TOKEN = credentials('fortify-token') ARTIFACTORY_SERVER = 'artifactory.example.com' ARTIFACTORY_CREDENTIALS = credentials('artifactory-credentials') } stages { stage('Reboot Server') { steps { script { ansiblePlaybook( playbook: "${ANSIBLE_PLAYBOOK}", inventory: "${ANSIBLE_INVENTORY}", extras: "--become --extra-vars '
ansible_become_pass=${env.ANSIBLE_SSH_PASS}'" ) } } } stage('Build') { steps { // Replace with your build steps, e.g., Maven, Gradle echo 'Building the application...' } } stage('Test') { steps { // Replace with your testing steps echo 'Running tests...' } } stage('SonarQube Scan') { environment { SONARQUBE_URL = "${SONARQUBE_SERVER}" } steps { withSonarQubeEnv('SonarQube') { sh 'sonar-scanner -Dsonar.projectKey=my_project
-Dsonar.sources=. -Dsonar.host.url=${SONARQUBE_URL}
-Dsonar.login=${SONARQUBE_TOKEN}' } } } stage('Fortify Scan') { steps { script { // Assuming Fortify command-line tools are
installed and configured sh "sourceanalyzer -b my_project -scan -f
my_project.fpr -url ${FORTIFY_SERVER} -token ${FORTIFY_TOKEN}" } } } stage('Artifact Storage') { steps { script { // Replace with your artifact storage steps sh "curl -u ${ARTIFACTORY_CREDENTIALS} -T
./path/to/your/artifact.ext https://${ARTIFACTORY_SERVER}/
artifactory/path/to/repo/" } } } } post { always { cleanWs() } } }

Ansible Playbook (reboot-server.yml)

yaml
--- - name: Reboot Red Hat Server hosts: all become: yes tasks: - name: Reboot the server ansible.builtin.reboot: reboot_timeout: 300

Inventory File (hosts)

css
[all] redhat-server-1 ansible_host=your.server.ip ansible_user=your_ssh_user
ansible_ssh_private_key_file=/path/to/ssh_key

Adding Credentials in Jenkins

  1. Ansible SSH Key:

    • Go to Jenkins Dashboard > Credentials > System > Global credentials (unrestricted).
    • Add a new credential of type "SSH Username with private key".
    • Add your SSH key file for the Red Hat Server.
  2. SonarQube Token:

    • Go to Jenkins Dashboard > Credentials > System > Global credentials (unrestricted).
    • Add a new credential of type "Secret text".
    • Enter your SonarQube API token.
  3. Fortify Token:

    • Repeat the same steps as for the SonarQube Token, but use your Fortify API token.
  4. JFrog Artifactory Credentials:

    • Add a new credential of type "Username with password".
    • Enter your Artifactory username and API key.

Summary

This Jenkins pipeline script is designed to:

  1. Reboot a Red Hat Server 9 using Ansible.
  2. Build the application (customise the build steps according to your project).
  3. Run tests (customise the test steps according to your project).
  4. Perform a SonarQube scan for code quality analysis.
  5. Perform a Fortify scan for security analysis.
  6. Upload the artifact to JFrog Artifactory.

Make sure to replace placeholder steps with your actual build and test commands, and ensure that your Jenkins environment is configured correctly with the necessary tools and credentials.

Thursday, 29 February 2024

Terraform configuration to build a Zero-trust network



Terraform configuration to build a Zero-trust network for web applications in Azure MS, with Azure Firewall and application gateways:

Terraform
terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = ">= 3.0.0"
    }
  }
}

provider "azurerm" {
  features {}
}

resource "azurerm_resource_group" "zerotrust" {
  name     = "zerotrust-rg"
  location = "westus"
}

resource "azurerm_virtual_network" "app-vnet" {
  name     = "app-vnet"
  location = azurerm_resource_group.zerotrust.location
  address_prefixes = ["10.0.0.0/16"]

  subnet {
    name         = "app-subnet"
    address_prefix = "10.0.1.0/24"
  }
}

resource "azurerm_application_gateway" "app-gw" {
  name     = "app-gw"
  location = azurerm_resource_group.zerotrust.location
  capacity = 2

  frontend_port {
    name     = "http"
    port     = 80
    protocol = "Http"
  }

  frontend_port {
    name     = "https"
    port     = 443
    protocol = "Https"
  }

  backend_address_pool {
    name = "app-backend-pool"
  }

  frontend_ip_configuration {
    name   = "app-frontend-ip"
    public_ip_address_id = null
  }

  listener {
    name                 = "http-listener"
    protocol             = "Http"
    frontend_port_name   = "http"
    frontend_ip_config_name = "app-frontend-ip"
  }

  listener {
    name                 = "https-listener"
    protocol             = "Https"
    frontend_port_name   = "https"
    frontend_ip_config_name = "app-frontend-ip"
  }

  request_routing_rule {
    name         = "app-http-rule"
    listener_name = "http-listener"
    backend_address_pool_name = "app-backend-pool"
    backend_http_setting_name = "app-http-setting"
  }

  request_routing_rule {
    name         = "app-https-rule"
    listener_name = "https-listener"
    backend_address_pool_name = "app-backend-pool"
    backend_http_setting_name = "app-https-setting"
  }

  backend_http_setting {
    name         = "app-http-setting"
    idle_timeout_in_minutes = 10

    path_rule {
      name         = "app-rule"
      path_patterns = ["/*"]
      backend_pool_name = "app-backend-pool"
      backend_http_setting_name = "app-http-setting"
    }
  }

  backend_http_setting {
    name         = "app-https-setting"
    idle_timeout_in_minutes = 10

    path_rule {
      name         = "app-rule"
      path_patterns = ["/*"]
      backend_pool_name = "app-backend-pool"
      backend_http_setting_name = "app-https-setting"
    }
  }

  probe {
    name        = "app-probe"
    path        = "/"
    interval_in_seconds = 30
    threshold = 3
  }

  health_monitor {
    name     = "app-monitor"
    probe_name = "app-probe"
  }
}
YAML
---
- name: Provision whitelist configuration
  hosts: all
  become: true
  tasks:
    - name: Get whitelist data from database
      uri:
        url: "https://database

OBS: 

Disclaimer

This Terraform and Ansible code is provided for informational purposes only and should not be considered production-ready. Running this code may have unintended consequences and could potentially compromise your Azure environment.

By using this code, you assume all risk and responsibility for any damages or losses that may occur. It is highly recommended to thoroughly understand the code and modify it to fit your specific needs and security requirements before deploying it in a production environment.

Additionally, always consult with qualified Azure and security professionals before implementing any changes in your environment.


Source Code:


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...