Ansible Playbooks

Ansible Playbooks

#90 Days of DevOps Challenge - Day 57 & 58

Ansible playbooks are YAML files used to define a set of tasks and configurations that should be executed on remote hosts. Playbooks provide a way to automate complex tasks and orchestrate multiple steps in a desired sequence. Here's an overview of Ansible playbooks:

An Ansible playbook consists of a collection of plays, which are the units of work in Ansible. Each play consists of one or more tasks that should be executed on the target hosts.

Syntax:- Playbooks are written in YAML format. Here's a basic structure of a playbook:-

---
- name: Playbook Name
  hosts: target_hosts
  gather_facts: true|false
  vars:
    variable_name: value
  tasks:
    - name: Task Name
      module_name:
        module_parameter: value

Components:-

  • name: A descriptive name for the playbook or a particular play/task.

  • hosts: Specifies the target hosts or groups of hosts on which the tasks should be executed.

  • gather_facts: Specifies whether to gather facts about the target hosts before executing tasks. Facts provide information about the host's system, such as network interfaces, IP addresses, etc.

  • vars: Allows defining variables that can be used throughout the playbook.

  • tasks: Contains a list of tasks to be executed on the target hosts. Each task consists of a name and a module with its parameters.

Modules:- Modules are the building blocks of Ansible playbooks and define the desired state of the system. Ansible provides a wide range of modules to perform various tasks, such as managing files, installing packages, configuring services, executing commands, etc.

Task-01

  • Write an Ansible playbook to create a file on a different server

Create an inventory file for Ansible

[servers]
server1 ansible_host=<Server1_ip_address>
server2 ansible_host=<Server2_ip_address>

[all:vars]
ansible_python_interpreter=/usr/bin/python3

Create an ansible playbook to create a file on a different server

---
- name: This playbook will create a file
  hosts: all
  become: true
  tasks:
    - name: Create a file
      file:
        path: /home/ubuntu/sample.txt
        state: touch

In this playbook, we define a single task that uses the file module to create the file. The path parameter specifies the full path to the file we want to create, and state parameter set to touch which will create the file if it doesn't exist and do nothing if it does exist.

You can run this playbook using the ansible-playbook command

ansible-playbook file-name.yml -i <inventory-file-path> --private-key=<private-key-path>
Ex:- ansible-playbook create_file.yml -i /home/ubuntu/ansible/hosts --private-key=/.ssh/ansible_key

Now lets Verify that the file has been created at the specified location

lets verify also that the file has been created on different servers

ansible all -a "ls /home/ubuntu" -i <inventory-file> --private-key=<key-path>
Ex:- ansible all -a "ls /home/ubuntu" -i /home/ubuntu/ansible/hosts --private-key=/.ssh/ansible_key

  • Write an ansible playbook to create a new user

---
- name: This playbook will create a new user
  hosts: all
  become: true
  tasks:
    - name: to create a user riju
      user: name=Riju

In this playbook, we define a single task that uses the user module to create the new user.

Run playbook using the ansible-playbook command,

ansible-playbook create_user.yml -i /home/ubuntu/ansible/hosts --private-key=/.ssh/ansible_key

To check if the user has been created, look for the user's name in the /etc/passwd file."

ansible all -a "cat /etc/passwd" -i /home/ubuntu/ansible/hosts --private-key=/.ssh/ansible_key

  • Write an ansible playbook to install docker on a group of servers

---
- name: This playbook will Install Docker
  hosts: all
  become: true

  tasks:
    - name: Add Docker GPG key
      apt_key:
        url: https://download.docker.com/linux/ubuntu/gpg
        state: present

    - name: Add Docker repository
      apt_repository:
        repo: deb [arch=amd64] https://download.docker.com/linux/ubuntu {{ ansible_lsb.codename }} stable
        state: present

    - name: Install Docker engine
      apt:
        name: docker-ce
        state: present

    - name: Start and enable Docker service
      service:
        name: docker
        state: started
        enabled: yes
  • name: Descriptive name for the playbook.

  • hosts: Specifies the target hosts or group of hosts where Docker should be installed. Replace docker_servers with the appropriate group name from your inventory.

  • become: true: Enables privilege escalation, allowing the playbook to execute tasks with elevated privileges (e.g., using sudo).

  • tasks: Contains a list of tasks to be executed on the target hosts.

  • name: Descriptive name for each task.

  • apt: Ansible's apt module is used to manage packages on Ubuntu.

  • apt_key: Adds the Docker GPG key to verify package authenticity.

  • apt_repository: Adds the Docker repository to the system's package sources.

  • update_cache: Updates the apt package cache to ensure the latest package information is available.

  • service: Manages the Docker service.

    • name: Specifies the name of the service to manage (docker).

    • state: started: Ensures that the Docker service is started.

    • enabled: yes: Enables the Docker service to start automatically at boot.

Run this playbook using the ansible-playbook command,

ansible-playbook install_docker.yml -i /home/ubuntu/ansible/hosts --private-key=/.ssh/ansible_key

Lets Verify that Docker has been installed on multiple servers.

ansible all -a "docker --version" -i /home/ubuntu/ansible/hosts --private-key=/.ssh/ansible_key

Task-02

  • Write a blog about writing ansible playbooks with the best practices

Ansible is a powerful open-source automation tool widely used for configuration management, application deployment, and orchestration. One of the core components of Ansible is playbooks, which allow you to define and execute tasks on remote hosts. In this blog post, we will explore the best practices for writing Ansible playbooks, ensuring maintainability, readability, and scalability.

  1. Start with a Clear Structure:-

A well-organized playbook structure is crucial for readability and maintainability. Here's an example of a playbook structure:

code- name: Playbook Name
  hosts: target_hosts
  become: yes
  vars:
    variable_name: value

  tasks:
    - name: Task 1
      <module>: <module_parameters>

  handlers:
    - name: Restart Service
      <module>: <module_parameters>
  1. Use Descriptive Variable Names:-

Choose descriptive variable names that clearly convey their purpose. Avoid generic names like "var1" or "temp." Here's an example:

codevars:
  database_name: mydb
  database_user: myuser
  1. Leverage Ansible Vault for Sensitive Data:-

Use Ansible Vault to securely store and manage sensitive data. Here's an example:

codevars:
  database_password: !vault |
    $ANSIBLE_VAULT;1.1;AES256
    64326230333063343532383531656533393238383233326136386536636330393964616262353235
  1. Utilize Ansible Roles:-

Roles promote reusability and maintainability. Here's an example structure of a role:

coderoles/
  my_role/
    tasks/
      main.yml
    vars/
      main.yml
  1. Implement Idempotent Tasks:-

Make tasks idempotent to ensure consistent results. Use the changed_when attribute to control task behavior. Here's an example:

codetasks:
  - name: Install Nginx
    apt:
      name: nginx
      state: present
    changed_when: false
  1. Handle Error Conditions:-

Handle errors gracefully using failed_when and ignore_errors attributes. Here's an example:

codetasks:
  - name: Copy Configuration
    template:
      src: templates/nginx.conf.j2
      dest: /etc/nginx/nginx.conf
    failed_when: false
  1. Document Your Playbooks:-

Documenting your playbooks helps with maintenance and knowledge sharing. Use comments to explain complex tasks. Here's an example:

code# Configure Nginx
- name: Copy Configuration
  template:
    src: templates/nginx.conf.j2
    dest: /etc/nginx/nginx.conf
  1. Use Ansible Galaxy for Community Roles:-

Leverage Ansible Galaxy to utilize community-supported roles. Here's an example of installing a role from Ansible Galaxy:

code- name: Install Role
  ansible-galaxy:
    name: username.role_name
    state: present
  1. Test Your Playbooks:-

Implement testing methodologies using tools like Molecule and Ansible-lint. Here's an example of using Molecule for testing:

code$ molecule init role --driver-name docker --role-name my_role
$ molecule test
  1. Version Control and CI/CD Integration:-

Store playbooks in a version control system (e.g., Git) and integrate with CI/CD pipelines. Here's an example using Git and Jenkins:

code$ git add .
$ git commit -m "Added

Conclusion:- Writing Ansible playbooks with best practices in mind not only improves the efficiency and maintainability of your infrastructure automation but also helps in collaboration and knowledge sharing. By following these guidelines and continuously learning from the Ansible community, you can create robust and scalable playbooks that streamline your IT operations and promote DevOps practices.

Devops#devops,#90daysofDevOps

Thank you for reading!! I hope you find this article helpful!!

if any queries or corrections to be done to this blog please let me know.

Happy Learning!!

Saikat Mukherjee

Printable, customizable thank you card templates | Canva

Did you find this article valuable?

Support Saikat Mukherjee by becoming a sponsor. Any amount is appreciated!