Module-5_Ansible_Assignment

  1. What is Ansible and what are the advantages of using Ansible?

    Ansible is an open-source automation tool that is used for configuration management, application deployment, task automation, and IT orchestration. It allows you to automate repetitive tasks, streamline complex workflows, and manage infrastructure as code. Ansible is agentless, meaning it doesn't require any software to be installed on the remote systems you want to manage. Instead, it uses SSH (Secure Shell) for communication.

    Here are some advantages of using Ansible:

    1. Agentless Architecture: Ansible operates in an agentless manner, meaning you don't need to install any software or agents on the managed nodes. This simplifies the setup and reduces potential security vulnerabilities.

    2. Simplicity and Ease of Use: Ansible uses a simple and human-readable language (YAML) for defining automation tasks. This makes it easy to learn and write playbooks, which are the configuration files used by Ansible.

    3. Declarative Language: Ansible playbooks are written in declarative language, meaning you describe the desired state of the system rather than specifying a sequence of steps to reach that state. This makes playbooks more understandable and less prone to errors.

    4. Broad Platform Support: Ansible supports a wide range of operating systems and can manage heterogeneous environments with different types of systems.

    5. Idempotency: Ansible is designed to be idempotent, meaning you can run the same automation tasks repeatedly without changing the system's state if it's already in the desired state. This ensures predictable and consistent results.

    6. Community and Ecosystem: Ansible has a large and active community, providing a wealth of modules and playbooks that you can reuse for common tasks. The Ansible Galaxy is a hub for sharing and finding pre-built roles.

    7. Integration with Existing Tools: Ansible can integrate with other tools and systems, making it a flexible choice for incorporating into existing workflows. It has modules for interacting with various cloud providers, networking devices, and more.

    8. Scalability: Ansible can scale from managing a few servers to thousands of servers with ease. It supports parallel execution of tasks, allowing you to manage large infrastructures efficiently.

    9. Auditability and Logging: Ansible provides detailed logs of playbook execution, making it easy to review and audit changes made to the infrastructure.

    10. Security: Ansible uses SSH for secure communication and sensitive data such as passwords or private keys can be encrypted and securely stored.

Overall, Ansible simplifies the automation of complex tasks, enhances collaboration among teams, and contributes to the scalability and consistency of IT environments.

  1. Create an Ansible Node and connect it with the Ansible Controller.

    1. Launch two ec2 instances (in my case ubuntu).

    2. Installing Ansible on Ubuntu (Ansible Manager):

    To configure the PPA on your system and install Ansible run these commands:

     $ sudo apt update
     $ sudo apt install software-properties-common
     $ sudo add-apt-repository --yes --update ppa:ansible/ansible
     $ sudo apt install ansible
     $ ansible --version
    

    3. Create password for ubuntu user:

    sudo passwd ubuntu

    4. Set PasswordAuthentication to yes

    sudo nano /etc/ssh/sshd_config

    Run the following commands on both the ansible manager and ansible node.

    sudo service ssh restart

    Create Ansible Inventory:

    Create an inventory file to store information about your Amazon Linux node. Replace ansible-node-ip with the actual IP address or hostname of your ubuntu node.

     sudo nano /etc/ansible/hosts
    

    Add the following lines:

     [ubuntu]
     private-ip
    

    Configure Ansible:

    Edit the Ansible configuration file to specify the inventory location. The inventory file will contain information about the managed nodes.

     sudo nano /etc/ansible/ansible.cfg
    

    Ensure the inventory line points to the correct location. The default location is /etc/ansible/hosts.

    On Ansible Manager:

    ssh-keygen

    Copying the ssh key to the ansible node:

    ssh-copy-id ec2-user@<public-ip>

    Logging into ansible node:

    ssh 'ubuntu@<private-ip>'

  2. What are Ansible Adhoc modules? Explain Ansible built-in modules like shell, URI, template, script, and hostname module.

    In Ansible, Ad-hoc commands are one-liners that you run on the command line without writing a playbook. They are useful for tasks that you don't need to automate or for quickly testing things on your managed hosts.

    Ansible provides a variety of built-in modules that Ad-hoc commands can use to perform tasks on managed hosts. Here are explanations for some of the mentioned modules:

    1. Shell Module:

      • Purpose: Executes commands in a shell on the remote system.

      • Usage Example:

          - name: Run a shell command
            hosts: localhost
            tasks:
              - name: Execute a command
                shell: echo "Hello, Ansible!"
        
      • The shell module allows you to run commands as if you were typing them directly into the command line.

    2. URI Module:

      • Purpose: Interacts with web services and APIs using HTTP or HTTPS.

      • Usage Example:

          - name: Make an HTTP request
            hosts: localhost
            tasks:
              - name: Get information from a web service
                uri:
                  url: http://example.com/api/data
                  method: GET
        
      • The uri module enables Ansible to make HTTP requests, supporting methods like GET, POST, PUT, etc.

    3. Template Module:

      • Purpose: Copies files and applies Jinja2 templating to them.

      • Usage Example:

          - name: Deploy a configuration file
            hosts: server
            tasks:
              - name: Copy and template a configuration file
                template:
                  src: templates/my_config.j2
                  dest: /etc/my_config.conf
        
      • The template module allows you to use Jinja2 templating to customize configuration files before deploying them.

    4. Script Module:

      • Purpose: Copies a script to the remote server and executes it.

      • Usage Example:

          - name: Run a local script on remote servers
            hosts: server
            tasks:
              - name: Copy and execute a script
                script:
                  src: scripts/install_app.sh
        
      • The script module is used for running custom scripts on remote servers. It copies the script to the target and executes it.

    5. Hostname Module:

      • Purpose: Configures the system hostname.

      • Usage Example:

          - name: Set the hostname
            hosts: localhost
            tasks:
              - name: Set the system hostname
                hostname:
                  name: myserver
        
      • The hostname module allows you to set or retrieve the system hostname.

  1. Write an Ansible Playbook to install a package named “httpd” in Amazon Linux 2003. Also, start and enable the service named “httpd”.

    Node -Amazon Linux 2023

    Controller - Ubuntu

    1. Launch two ec2 instances.

      Ansible controller - Ubuntu

      Ansible Node - Amazon Linux

    2. Installing Ansible on Ubuntu (Ansible Manager):

      To configure the PPA on your system and install Ansible run these commands:

       $ sudo apt update
       $ sudo apt install software-properties-common
       $ sudo add-apt-repository --yes --update ppa:ansible/ansible
       $ sudo apt install ansible
       $ ansible --version
      

      3. Create password for ec2-user:

      sudo passwd ec2-user

      4. Set PasswordAuthentication to yes

      sudo nano /etc/ssh/sshd_config

      Run the following commands on both the ansible manager and ansible node.

      sudo service sshd restart

      Create Ansible Inventory:

      Create an inventory file to store information about your Amazon Linux node. Replace ansible-node-ip with the actual IP address or hostname of your ubuntu node.

       sudo nano /etc/ansible/hosts
      

      Add the following lines:

       [amazonlinux]
       private-ip
      

      Configure Ansible:

      Edit the Ansible configuration file to specify the inventory location. The inventory file will contain information about the managed nodes.

       sudo nano /etc/ansible/ansible.cfg
      

      Ensure the inventory line points to the correct location. The default location is /etc/ansible/hosts.

      On Ansible Manager:

      ssh-keygen

      Copying the ssh key to the ansible node:

      ssh-copy-id ec2-user@<public-ip>

      Logging into ansible node:

      ssh 'ec2-user@<private-ip>'

      Create Ansible Playbook (on Ansible Manager):

      touch install_httpd.yml

      nano install_httpd.yml

       ---
       - name: Install and configure httpd on Amazon Linux
         hosts: amazonlinux  # Replace with your actual inventory group for Amazon Linux
         become: yes
      
         tasks:
           - name: Update package cache
             package_facts:
               manager: auto
      
           - name: Install httpd package
             package:
               name: httpd
               state: present
      
           - name: Start and enable httpd service
             service:
               name: httpd
               state: started
               enabled: yes
      

      Run the ansible-playbook as shown below (on ansible manager).

      ansible-playbook install_httpd.yml

      Check the httpd service status as shown below (on ansible node).

      sudo systemctl status httpd

  1. Set up a Jenkins Server using Ansible without any manual configuration.

    (Pass Jenkins login password as Ansible Global Scope variable.)

    Here's an Ansible playbook to set up a Jenkins server without any manual configuration, including setting the initial login password as an Ansible global scope variable:

    YAML

     ---
     # Define the Jenkins initial login password as an Ansible global variable
     - hosts: localhost
       vars:
         jenkins_password: "{{ lookup('env', 'JENKINS_INITIAL_PASSWORD') }}"
    
       tasks:
         # Install Java
         - name: Install Java JRE
           package:
             name: openjdk-11-jre-headless
             state: present
           become: true
    
         # Add Jenkins repository
         - name: Add Jenkins repository key
           apt_key:
             url: https://pkg.jenkins.io/debian/jenkins.io.key
             state: present
           become: true
         - name: Add Jenkins repository
           apt_repository:
             repo: "deb https://pkg.jenkins.io/debian-stable binary/"
             state: present
             update_cache: yes
           become: true
    
         # Install Jenkins
         - name: Install Jenkins
           package:
             name: jenkins
             state: present
           become: true
    
         # Start and enable Jenkins service
         - name: Start Jenkins service
           service:
             name: jenkins
             state: started
             enabled: yes
           become: true
    
     # Configure Jenkins
     - hosts: localhost
       tasks:
         - name: Wait for Jenkins to start
           wait_for:
             port: 8080
             host: localhost
             delay: 10
             timeout: 60
    
         - name: Install initial Jenkins plugins
           command: "/usr/bin/java -jar /usr/lib/jenkins/jenkins.war -installPlugin hpi:credentials,workflow-aggregator,ssh,git,workflow-job"
           become: true
    
         - name: Unlock Jenkins
           command: "/usr/bin/curl -X POST http://localhost:8080/unlock -d 'JENKINS_ADMIN_PASSWORD={{ jenkins_password }}'"
    
         - name: Set initial Jenkins admin password
           command: "/usr/bin/curl -X POST http://localhost:8080/crumbIssuer/doCrumb -d 'crumbRequestField=Jenkins-Crumb' --silent | sed 's/.*crumb=\"\\([^\"]*\\)\".*/\\1/' -o /tmp/crumb.txt"
           register: crumb_result
           become: true
    
         - name: Create initial Jenkins admin user
           command: "/usr/bin/curl -X POST http://localhost:8080/createAdminUser -d 'username=admin&password={{ jenkins_password }}&confirm password={{ jenkins_password }}&crumb={{ crumb_result.stdout }}'"
           become: true
    
     # Restart Jenkins to apply changes
     - hosts: localhost
       tasks:
         - name: Restart Jenkins service
           service:
             name: jenkins
             state: restarted
           become: true
    

    This playbook will:

    1. Install Java JRE.

    2. Add the Jenkins repository key and repository.

    3. Install Jenkins.

    4. Start and enable the Jenkins service.

    5. Wait for Jenkins to start.

    6. Install initial Jenkins plugins like "credentials", "workflow-aggregator", "ssh", "git", and "workflow-job".

    7. Unlock Jenkins using the JENKINS_ADMIN_PASSWORD variable.

    8. Set the initial Jenkins admin password using the JENKINS_ADMIN_PASSWORD variable.

    9. Restart the Jenkins service to apply changes.

Make sure to replace {{ jenkins_password }} with your desired initial Jenkins admin password. You can set this password as an Ansible global variable using the -e flag when running the playbook, e.g.,:

    ansible-playbook jenkins.yaml -e JENKINS_INITIAL_PASSWORD="pavan"

  1. Set up a Jenkins Job to run Ansible Playbook to install tomcat9 onto a different node. Use the Ansible plugin available on Jenkins. The manager node and Jenkins master both are on the same instance.

    Prerequisites:

    1. Launch two ec2 instances (in my case ubuntu).

    2. Install Ansible on one ec2 instance (Ansible Controller) and establish an SSH connection between Ansible Controller and Ansible Node.

      To configure the PPA on your system and install Ansible run these commands:

       $ sudo apt update
       $ sudo apt install software-properties-common
       $ sudo add-apt-repository --yes --update ppa:ansible/ansible
       $ sudo apt install ansible
       $ ansible --version
      

      3. Create password for ubuntu user:

      sudo passwd ubuntu

      4. Set PasswordAuthentication to yes

      sudo nano /etc/ssh/sshd_config

      Run the following commands on both the ansible manager and ansible node.

      sudo service ssh restart

      Create Ansible Inventory:

      Create an inventory file to store information about your Amazon Linux node. Replace ansible-node-ip with the actual IP address or hostname of your ubuntu node.

       sudo nano /etc/ansible/hosts
      

      Add the following lines:

       [ubuntu]
       private-ip
      

      Configure Ansible:

      Edit the Ansible configuration file to specify the inventory location. The inventory file will contain information about the managed nodes.

       sudo nano /etc/ansible/ansible.cfg
      

      Ensure the inventory line points to the correct location. The default location is /etc/ansible/hosts.

      On Ansible Manager:

      ssh-keygen

      Copying the ssh key to the ansible node:

      ssh-copy-id ubuntu@<public-ip>

      Logging into ansible node:

      ssh 'ubuntu@<private-ip>'

    3. Install Jenkins on Ansible Controller(Instance).

    4. Ensure that you have an Ansible playbook for installing Tomcat9. Create a playbook if you don't have one.

Install Ansible Plugin in Jenkins:

  1. Open Jenkins and navigate to "Manage Jenkins" > "Manage Plugins."

  2. Go to the "Available" tab and search for "Ansible" in the filter.

  3. Check the box next to "Ansible" and click on the "Install without restart" button.

    Add SSH private key in the credentials section as shown below.

Configure Ansible in Jenkins:

  1. Go to "Manage Jenkins" > "Global Tool Configuration."

  2. Scroll down to the "Ansible" section and click on "Add Ansible."

  3. Enter a name for the installation, and specify the path to the Ansible executable (e.g., /usr/bin).

  4. Click on "Save."

Create Jenkins Job:

  1. Click on "New Item" to create a new Jenkins job.

  2. Enter a name for the job and choose the "Pipeline" option.

  3. Save the job configuration.

Run Jenkins Job:

  1. Now run the pipeline job as shown below.

    Console output:

    Now check your tomcat9 webserver working or not:

    <public ip of ansible node>:9000

    (Make sure to allow 9000 port number in the inbound rules of your ec2 instance)