Ansible Notes By ShariqSP

What is Ansible?

Ansible is an open-source automation tool that automates software provisioning, configuration management, and application deployment. It enables infrastructure as code, allowing IT administrators to automate repetitive tasks and manage configurations across a large number of servers efficiently.

Why Ansible?

Ansible simplifies complex tasks such as deploying applications, managing configurations, and orchestrating complex workflows. It is agentless, meaning it does not require any additional software to be installed on managed nodes, making it lightweight and easy to deploy. Ansible also uses YAML for its playbooks, which are easy to read, write, and understand.

Ansible in Real World

Ansible is widely used in various industries and scenarios, including:

  • Automating server provisioning and configuration management.
  • Deploying and managing applications across different environments.
  • Managing network devices and switches.
  • Automating cloud infrastructure provisioning and management.
  • Streamlining DevOps processes and workflows.

Where to Use Ansible?

Ansible can be used in various scenarios, including:

  • Infrastructure automation: Automating tasks related to server provisioning, configuration management, and software deployment.
  • Application deployment: Streamlining the deployment process and ensuring consistency across different environments.
  • Continuous integration/continuous deployment (CI/CD): Integrating Ansible into CI/CD pipelines to automate deployment and testing processes.
  • Configuration management: Managing configurations across a large number of servers or network devices efficiently.
  • Orchestration: Orchestrating complex workflows involving multiple systems and services.

Installation

Follow these steps to install Ansible, pip, Boto, and Boto3 on Ubuntu:

  1. Update your package index:
  2. sudo apt update
  3. Install software-properties-common:
  4. sudo apt install software-properties-common
  5. Add Ansible PPA repository:
  6. sudo add-apt-repository --yes --update ppa:ansible/ansible
  7. Update package index again:
  8. sudo apt update
  9. Install Ansible:
  10. sudo apt install ansible

Once installed, you can verify the Ansible version:

  • Check Ansible version:
  • ansible --version

What is pip and how to install it?

Pip is a package management system used to install and manage software packages written in Python. It stands for "Pip Installs Packages". If you're planning to install additional Python packages, you'll need pip.

To install pip on Ubuntu, you can use the following command:

sudo apt install python3-pip

After installation, you can verify the pip version:

pip3 --version

What is Boto and Boto3 and their use in Ansible?

Boto and Boto3 are Python libraries used for interacting with Amazon Web Services (AWS). They provide an easy-to-use interface to AWS services such as EC2, S3, and many others.

In Ansible, Boto and Boto3 are often used in conjunction with the EC2 module to manage AWS infrastructure. They allow Ansible playbooks to create, delete, and manage AWS resources.

To use Boto and Boto3 with Ansible, you need to install them using pip:

sudo pip3 install boto boto3

After installation, you can verify the Boto and Boto3 versions:

  • Check Boto version:
  • python3 -c "import boto; print(boto.__version__)"
  • Check Boto3 version:
  • python3 -c "import boto3; print(boto3.__version__)"

YAML and Playbooks in Ansible

YAML (YAML Ain't Markup Language) is a human-readable data serialization format commonly used for configuration files. In Ansible, YAML is used extensively for writing playbooks.

A playbook in Ansible is a file written in YAML format that defines a set of tasks to be executed on managed nodes. Playbooks are used to automate tasks such as server provisioning, configuration management, and application deployment.

Components of a Playbook

  • Play: A play is a set of tasks that are executed on a specific group of hosts. Each play can have one or more tasks defined within it.
  • Task: A task is a single unit of work performed by Ansible. Tasks are executed sequentially and can include modules, which are Ansible's building blocks for performing actions such as installing packages, copying files, or restarting services.
  • Module: A module is a reusable, standalone script that Ansible executes on managed nodes to perform specific tasks. Ansible provides a wide range of built-in modules for common operations, such as managing files, packages, services, users, and more.

Example Playbook

Below is a simple example of a YAML-based playbook that installs and starts the Apache web server on a group of web servers:


      ---
      - name: Install and start Apache
        hosts: webservers
        tasks:
          - name: Install Apache
            yum:
              name: httpd
              state: present
      
          - name: Start Apache service
            service:
              name: httpd
              state: started
      

In this example:

  • The name field under each task is a human-readable description of the task.
  • The hosts field specifies the group of hosts (in this case, webservers) on which the tasks will be executed.
  • The tasks section defines the list of tasks to be executed.
  • Each task uses a module (yum and service) to perform specific actions.
  • The state parameter specifies whether the package or service should be present (installed/running) or absent (uninstalled/stopped).

Ansible Modules for AWS

Ansible provides a comprehensive set of built-in modules for automating various tasks on Amazon Web Services (AWS). These modules allow users to interact with AWS services such as EC2 (Elastic Compute Cloud), S3 (Simple Storage Service), VPC (Virtual Private Cloud), and more.

EC2 (Elastic Compute Cloud)

Ansible provides several modules for managing EC2 instances, including:

  • ec2: Used for launching, terminating, stopping, starting, and managing EC2 instances.
  • ec2_ami: Manages Amazon Machine Images (AMIs), allowing users to create, delete, and copy AMIs.
  • ec2_key: Manages EC2 key pairs, enabling users to create, delete, and import key pairs.
  • ec2_instance_info: Retrieves information about EC2 instances.

S3 (Simple Storage Service)

For managing objects in Amazon S3 buckets, Ansible provides the following modules:

  • s3: Manages objects (files) in S3 buckets, allowing users to upload, download, delete, and synchronize objects.
  • s3_bucket: Manages S3 buckets, enabling users to create, delete, and configure bucket properties.

VPC (Virtual Private Cloud)

Ansible offers modules for managing VPC resources, such as:

  • ec2_vpc: Manages VPCs (Virtual Private Clouds), allowing users to create, delete, and modify VPC configurations.
  • ec2_vpc_subnet: Manages subnets within VPCs, enabling users to create, delete, and modify subnet configurations.
  • ec2_vpc_route_table: Manages route tables associated with VPCs, allowing users to create, delete, and modify route table entries.

Other AWS Modules

In addition to the core EC2, S3, and VPC modules, Ansible offers modules for managing other AWS services, including:

  • RDS Module: Manages Amazon Relational Database Service (RDS) instances.
  • Route 53 Module: Manages DNS records and hosted zones in Amazon Route 53.
  • CloudFormation Module: Interacts with AWS CloudFormation to create, update, and delete stacks.
  • IAM Module: Manages AWS Identity and Access Management (IAM) users, groups, roles, and policies.
  • Auto Scaling Module: Manages Auto Scaling groups and launch configurations.
  • Elastic Load Balancing (ELB) Module: Manages Application Load Balancers (ALBs) and Classic Load Balancers.

These modules provide a high-level interface for interacting with AWS services, allowing users to automate infrastructure provisioning, configuration, and management on the AWS cloud using Ansible.

Ansible Host File

In Ansible, the host file is a simple text file that defines the inventory of hosts and groups managed by Ansible. It serves as the inventory source, providing information about the systems that Ansible will interact with during playbook execution.

Format of Host File

The host file follows a straightforward format:


  [group_name]
  host1 ansible_host=host1_ip ansible_user=ssh_user ansible_ssh_private_key_file=/path/to/ssh/key
  
  [other_group_name]
  host2 ansible_host=host2_ip ansible_user=ssh_user ansible_ssh_private_key_file=/path/to/ssh/key
      

In this format:

  • [group_name] and [other_group_name] are group names that categorize hosts. Groups allow for logical organization of hosts.
  • host1 and host2 are the hostnames or IP addresses of the systems managed by Ansible.
  • ansible_host specifies the hostname or IP address of the remote host.
  • ansible_user specifies the username used to authenticate to the remote host via SSH.
  • ansible_ssh_private_key_file (optional) specifies the path to the SSH private key file used for authentication.

Variables in Host File

Host file entries can include additional variables that define specific attributes or configurations for hosts. These variables can be used in playbooks to customize tasks based on host properties.

Example Host File

Here's an example of a host file:


  [web_servers]
  web1 ansible_host=192.168.1.101 ansible_user=ubuntu ansible_ssh_private_key_file=~/.ssh/id_rsa
  
  [db_servers]
  db1 ansible_host=192.168.1.102 ansible_user=centos ansible_ssh_private_key_file=/path/to/key.pem
      

In this example:

  • The [web_servers] group contains a host web1 with IP address 192.168.1.101 and SSH user ubuntu.
  • The [db_servers] group contains a host db1 with IP address 192.168.1.102 and SSH user centos, using a specific private key file for authentication.

The host file allows Ansible to efficiently manage and execute tasks across multiple hosts in a network infrastructure.

Ansible Playbooks for AWS Tasks

Below are example Ansible playbooks demonstrating how to perform various tasks on Amazon Web Services (AWS) using Ansible modules.

Creating an EC2 Instance


  ---
  - name: Create EC2 Instance
    hosts: localhost
    tasks:
      - name: Launch EC2 Instance
        ec2_instance:
          key_name: my-key
          instance_type: t2.micro
          image: ami-12345678
          region: us-east-1
          count: 1
          state: present
        register: ec2
  

Stopping an EC2 Instance


  ---
  - name: Stop EC2 Instance
    hosts: localhost
    tasks:
      - name: Stop EC2 Instance
        ec2:
          instance_ids: i-12345678
          state: stopped
  

Terminating an EC2 Instance


  ---
  - name: Terminate EC2 Instance
    hosts: localhost
    tasks:
      - name: Terminate EC2 Instance
        ec2:
          instance_ids: i-12345678
          state: absent
  

Creating an S3 Bucket


  ---
  - name: Create S3 Bucket
    hosts: localhost
    tasks:
      - name: Ensure S3 Bucket exists
        s3_bucket:
          name: my-bucket
          state: present
  

Deleting an S3 Bucket


  ---
  - name: Delete S3 Bucket
    hosts: localhost
    tasks:
      - name: Ensure S3 Bucket is absent
        s3_bucket:
          name: my-bucket
          state: absent
  

Uploading an Object to an S3 Bucket


  ---
  - name: Upload Object to S3 Bucket
    hosts: localhost
    tasks:
      - name: Upload Object to S3 Bucket
        s3:
          bucket: my-bucket
          object: /path/to/local/file
          dest: /path/in/bucket/object
          mode: put
  

Deleting an Object in an S3 Bucket


  ---
  - name: Delete Object in S3 Bucket
    hosts: localhost
    tasks:
      - name: Delete Object in S3 Bucket
        s3:
          bucket: my-bucket
          object: /path/in/bucket/object
          mode: delete
  

Creating and Deleting VPC Resources


  ---
  - name: Create VPC, Subnet, Route Table, and Gateway
    hosts: localhost
    tasks:
      - name: Create VPC
        ec2_vpc_net:
          name: my-vpc
          cidr_block: 10.0.0.0/16
          state: present
        register: vpc
  
      - name: Create Subnet
        ec2_vpc_subnet:
          vpc_id: "{{ vpc.id }}"
          cidr: 10.0.0.0/24
          state: present
  
      - name: Create Internet Gateway
        ec2_vpc_igw:
          vpc_id: "{{ vpc.id }}"
          state: present
  
      - name: Create Route Table
        ec2_vpc_route_table:
          vpc_id: "{{ vpc.id }}"
          routes:
            - dest: 0.0.0.0/0
              gateway_id: "{{ vpc.internet_gateway_id }}"
          state: present
  
  - name: Delete VPC Resources
    hosts: localhost
    tasks:
      - name: Delete Internet Gateway
        ec2_vpc_igw:
          vpc_id: "{{ vpc.id }}"
          state: absent
  
      - name: Delete Subnet
        ec2_vpc_subnet:
          vpc_id: "{{ vpc.id }}"
          state: absent
  
      - name: Delete Route Table
        ec2_vpc_route_table:
          vpc_id: "{{ vpc.id }}"
          state: absent
  
      - name: Delete VPC
        ec2_vpc_net:
          id: "{{ vpc.id }}"
          state: absent
  

Launch EC2 Instance and Deploy Web Application using Ansible

In this example, we'll demonstrate how to use Ansible to launch an EC2 instance and deploy a simple web application on it.

Ansible Playbook

First, let's create an Ansible playbook that launches an EC2 instance and deploys a web application:


---
- name: Launch EC2 Instance and Deploy Web Application
  hosts: localhost
  tasks:
    - name: Launch EC2 Instance
      ec2_instance:
        key_name: my-key
        instance_type: t2.micro
        image: ami-12345678
        region: us-east-1
        count: 1
        state: present
      register: ec2

    - name: Wait for SSH to come up
      wait_for:
        host: "{{ item.public_ip }}"
        port: 22
        delay: 60
        timeout: 300
        state: started
      with_items: "{{ ec2.instances }}"

    - name: Deploy Web Application
      hosts: "{{ item.public_ip }}"
      become: yes
      tasks:
        - name: Install Apache web server
          yum:
            name: httpd
            state: present

        - name: Start Apache service
          service:
            name: httpd
            state: started

        - name: Copy web application files
          copy:
            src: /path/to/web/application
            dest: /var/www/html
            remote_src: yes

In this playbook:

  • We use the ec2_instance module to launch an EC2 instance with specified parameters.
  • We wait for SSH to come up on the newly launched instance.
  • We then use tasks to install and configure Apache web server and deploy the web application files.

Running the Playbook

To run the playbook, save it to a file (e.g., deploy-web-app.yml) and execute the following command:

ansible-playbook deploy-web-app.yml

This will launch an EC2 instance, wait for SSH to come up, install Apache, and deploy the web application.