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

Tuesday, 9 July 2024

How to Write a DevOps Handover Document

A DevOps Handover document template to help a person leaving a project pass on the work done to another engineer, so it is continued, the work is around the Ansible playbook, for ci/cd automation, Jenkins pipeline and GitLab repository..



                          ##### BEGINNING OF  DOCUMENT TEMPLATE #########

DevOps Handover Document

Project Overview

Provide a brief overview of the project, its objectives, and its key components.

  • Project Name:
  • Project Description:
  • Key Stakeholders:
  • Project Timeline:
  • Current Status:

Ansible Playbook

Overview

Provide an overview of the Ansible playbook used in the project.

  • Purpose: Describe the purpose of the playbook.
  • Main Playbooks and Roles: List the primary playbooks and roles, their locations, and their functions.
  • Dependencies: Outline any dependencies or prerequisites for running the playbooks.

Directory Structure

├── ansible/ │ ├── playbooks/ │ │ ├── main_playbook.yml │ │ └── other_playbooks.yml │ ├── roles/ │ │ ├── role1/ │ │ └── role2/ │ ├── inventory/ │ │ ├── production │ │ └── staging │ └── ansible.cfg
  • Playbooks: Detailed description of key playbooks and their functions.
  • Roles: Detailed description of key roles and their tasks.
  • Inventory: Description of the inventory files and their purpose.
  • Configuration: Any special configurations in ansible.cfg.

Running Playbooks

Provide step-by-step instructions for running the playbooks.

  1. Setup Environment:
    bash
    ansible-playbook -i inventory/production main_playbook.yml
  2. Common Commands:
    • Command for running a specific playbook.
    • Command for running playbooks in staging/production environments.
    • Command for checking the playbook syntax.
    • Any other relevant commands.

CI/CD Automation

Jenkins Pipeline

Overview

Provide an overview of the Jenkins pipeline configuration.

  • Purpose: Describe the pipeline’s role in the project.
  • Pipeline Stages: List and describe each stage of the pipeline.

Configuration

  • Jenkinsfile Location:
  • Pipeline Script: Provide a snippet or full script of the Jenkinsfile if possible.
  • Plugins: List the Jenkins plugins used and their purposes.

Common Tasks

  • Triggering Builds: How to manually trigger builds.
  • Monitoring Builds: How to monitor build status and logs.
  • Debugging Issues: Steps to debug common issues.

GitLab Repository

Overview

Provide an overview of the GitLab repository setup.

  • Repository URL:
  • Branches: List and describe the purpose of key branches (e.g., main, develop, feature/*, hotfix/*).
  • Branching Strategy: Explain the branching strategy used in the project.
  • Merge Requests: Outline the process for creating and reviewing merge requests.

Repository Structure

bash
├── .gitlab/ │ ├── ci/ │ │ ├── stages/ │ │ ├── jobs/ │ │ └── scripts/ ├── src/ │ ├── main/ │ └── test/ ├── docs/ └── README.md
  • Key Directories: Description of key directories and their contents.
  • CI Configuration: Details of GitLab CI configuration (.gitlab-ci.yml).

Common Tasks

  • Cloning the Repository:
    bash
    git clone <repository_url>
  • Working with Branches:
    • Creating a new branch.
    • Merging branches.
  • CI/CD Pipelines:
    • How to trigger pipelines.
    • Monitoring pipeline status.
    • Debugging failed pipelines.

Contacts and Resources

Provide a list of key contacts and resources for further assistance.

  • Project Manager: Name, email, phone number.
  • Technical Lead: Name, email, phone number.
  • Relevant Documentation: Links to any additional documentation or resources.
  • Access Credentials: Securely provide any necessary credentials or access details.

Additional Notes

Any additional notes, tips, or important information to be aware of.


Prepared by: [Your Name]
Date: [Date]


                                   ##### END OF  DOCUMENT TEMPLATE #########

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.

Wednesday, 8 May 2024

DevOps for Small Businesses: Simplifying Deployment and Scaling

Introduction

Hey there, small business owners! Are you tired of software deployments that move at the speed of a sloth? Want to scale up faster than a caffeine-fueled coder on a deadline? It’s time to talk about DevOps, a superhero team-up of development and operations that's all about getting things done better and faster. Let’s dive into how you can zap those old-school methods and boost your business into the fast lane!



The Basics of DevOps for Small Businesses

What’s the Big Deal with DevOps?

DevOps isn't just for the big leagues; it's like the Swiss Army knife for your business—versatile, efficient, and surprisingly affordable. It blends development (the "Dev") with operations (the "Ops") into a dynamic duo. Think Batman and Robin, but for pushing updates and fixing bugs. Small businesses can particularly rock this by speeding up delivery times and nailing quality from the get-go.


Tools and Technologies

Picking Your Gadget Arsenal

Choosing the right tools is less about stocking up for an apocalypse and more about picking the niftiest gadgets for the job:
  • Version Control Systems (Git): This is your diary but for code. It remembers everything, so you don’t have to.
  • CI/CD Tools (Jenkins or CircleCI): These are your assembly lines, automating the nitty-gritty so you can sip coffee and brainstorm.
  • Monitoring Tools (Nagios, Prometheus): These are your lookouts, keeping an eagle eye on operations and squawking loudly if something goes haywire.
  • Configuration Management Tools (Ansible, Puppet): Think of these as your magical elves, setting up everything perfectly while you’re off handling other business spells.

Implementation Strategies

Your DevOps Game Plan

Jumping into DevOps might seem like leaping into a double-dutch jump rope game. Here’s how to not trip up:
  1. Look Before You Leap: Check out what you’re doing now and where a dash of DevOps could make life easier.
  2. Plan Like a Pro: Set some goals. Nothing fancy—just some milestones you’d like to hit with DevOps.
  3. Pick Your Tools Wisely: Gear up based on what you need, not what the cool kids are using.
  4. Start Small: Kick off a mini-project. It’s like your own pilot episode, so make it good!


Overcoming Challenges

Dodging the DevOps Pitfalls

Sure, roadblocks pop up, but here’s how to swerve around them:
  • Tiny Budgets: Embrace open-source tools. They’re free and often just as good as the pricey stuff.
  • Skill Shortages: Consider some quick training, or maybe even bring in a freelancer to help raise your team’s game.
  • Fear of Change: Change can be scary, but so was your first smartphone, right? And look at you now!

Case Studies

Success Stories to Make You Smile

Consider the local boutique that streamlined its online checkout system with DevOps magic, turning its once-glacial process into a sprinter’s paradise. They cut down issue resolution from days to hours. Now, that’s moving at the speed of business!

Conclusion and Next Steps

Take the DevOps Plunge

Think of DevOps as your business’s new best friend. It’s here to help you deploy faster, scale bigger, and react quicker to whatever the market throws at you. Start small, think big, and scale fast. Ready to become a DevOps believer? Dive into some resources, connect with experts, or just start tinkering. The future’s bright, and it’s streamlined!

References Used on This Blog:

- CircleCI - https://circleci.com/ 
- Nagios -  https://www.nagios.org/ 
- Prometheus - https://prometheus.io/ 

Monday, 16 October 2023

List of the best Terraform infrastructure as Code Books, based on Readers feedback.

Based on readers’ feedback, here are some of the best books on Terraform Infrastructure as Code:



  • Continuous Delivery with Jenkins, Kubernetes, and Terraform: by Mohamed Labouardy. This book is a practical guide to automating your development pipeline in a cloud-native, service-driven world. It covers topics like the basics of Terraform and Jenkins, how to use Jenkins for code-driven CI/CD pipelines, and mastering the usage of Terraform for code-based infrastructure management.
Continuous Delivery with Jenkins, Kubernetes, and Terraform: by Mohamed Labouardy12


  • Terraform: Up & Running: Writing Infrastructure as Code by Yevgeniy (Jim) Brikman. This hands-on book shows you how to get up and running with Terraform fast. It covers topics like manual and automated testing for Terraform code, comparing Terraform to Chef, Puppet, Ansible, CloudFormation, and Salt Stack, and deploying server clusters, load balancers, and databases. It also important to mention here, this book is at 3rd edition already.


Terraform in Action




  • Terraform Cookbook: Efficiently define, launch, and manage Infrastructure as Code across various cloud platforms. This book is ideal for those who are new to Terraform and want to learn more about it.



Please, bear in mind that the availability of these books may vary. I recommend checking them out on your preferred book retailer or library.

1 - Here I can leave you guys with some more learning/Reading resources - GitHub - shuaibiyy/awesome-terraform: Curated list of resources on HashiCorp's Terraform

2 - Hashicorp Terraform source documentation - https://developer.hashicorp.com/terraform/docs 

3 - Master Terraform: A cheat sheet for infrastructure automation - https://www.architect.io/blog/2023-02-02/terraform-cheat-sheet/ 






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