Learn Ansible: A Simple Guide for Starters

Managing infrastructure can often seem overwhelming, but automation tools like Ansible offer a streamlined approach to simplify this complexity. At the heart of Ansible’s power are its modules , reusable scripts designed to handle specific tasks with ease. In this guide, we’ll delve into what Ansible modules are, how they function, and how you can use them effectively in your playbooks.

Configuration Management

  • Automates administrative tasks.

  • Transforms your code into infrastructure.

  • Ensures code is testable, repeatable, and versionable.

Problems Solved by Ansible

  • Managing user and group accounts.

  • Taking backups.

  • Deploying various applications.

  • Handling packages.

  • Configuring services.

Why Use a Configuration Management Tool?

  • Achieves complete automation.

  • Ensures compliance.

  • Prevents errors.

  • Increases uptime.

  • Improves performance.

  • Reduces costs.

  • Automates tasks which were traditionally done manually by system admins (Linux/Windows) using Ansible (or any CM tool).

  • Usable for servers both on-premises and in the cloud.

  • Specifies desired configurations without detailing the steps to achieve them.

  • Achieves the desired server state through automation.

Install & Configure Infrastructure using Ansible

Setup: This is short lab to understand how exactly ansible works--

  1. Launch 3 AWS Instances:

    • One server machine

    • Two nodes.

  2. On Amazon Linux (Server Machine):

    • Install prerequisites required for Ansible:

        yum install wget -y
        wget http://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
        yum install epel-release-latest-7.noarch.rpm -y
        sudo yum update -y
        sudo yum install git python python-devel python-pip openssl ansible -y
      
    • Verify Ansible installation:

        ansible --version
      
  3. Test Environment Setup (On All Machines):

    • Add a new user:

        adduser ansadmin
        passwd ansadmin
      
    • Edit sudoers file to add Ansible user to sudo users list:

        visudo
      
        #include the following line into that editor window 
      
        ansadmin ALL=(ALL) NOPASSWD: ALL
      
    • Enable password authentication for SSH:

      ```sh vi /etc/ssh/sshd_config

      #Set PasswordAuthentication to yes and then exit from this file . #Once you came out of the editor, perform below cmds , cause we have made some changes and those need to be applied.into file

service sshd restart



    **Test Environment Setup (On Server Instance):**

    * Switch to the new user and ensure sudo works without asking for a password:

        ```sh
        su - ansadmin
        whoami
        sudo yum update
        # It should prompt for the password
  1. Run the following commands as ansadmin user (On Server Instance):

    • Generate SSH keys:

        ssh-keygen
        #Keys will be in the .ssh directory & copy that key.
      
    • Copy the SSH keys to remaining two nodes from server machine :

        cd .ssh
        ssh-copy-id ansadmin@<node-private-ip>
      

This will paste public key that we have generated earlier, into nodes inside root directory .ssh/authorized_keys folder.

  1. Test SSH connection to other two Nodes:

    • Ensure it does not ask for a password: like you can directly get logged into nodes system where public key we have copied earlier.

        ssh ansadmin@<node-private-ip>
      
  2. To check connection of server with nodes using Host patterns:

     sudo mkdir /etc/ansible
     sudo vi /etc/ansible/hosts
     ansible all -m ping              # will enlist all connected machines
     ansiible webservers[0] -m ping   # will ping 1st machine
     ansiible webservers[-2] -m ping  # will ping 1st machine
     ansible webservers[1] -m ping    # will ping 2nd connected machine
     ansible webservers[-1] -m ping   # will ping 2nd connected machine
     ansible all --list-hosts         # will show ip address of all connected nodes.
    

And if systems are configured successfully, it should show output like above.


The general purpose of using Ansible is to create infrastructure:

Like if you went to Dmart and brought 4,5 items so you prefer to get billed faster and so you choose faster billing counter rather than other counters where generally customers with more items of shopping get billed.

In the same way, for purpose of 1 task performance we go with :

Ad-hoc commands

we want to apply changes to specific group of nodes , so need to create host file where we can collect host ip's of our nodes to which machines/instances specifically we are willing to make changes .It goes like follow :

sudo mkdir /etc/ansible 
sudo vi /etc/ansible/hosts  #paste private ip's of 2 nodes inside this file as shown in below image.

[Here webservers is for or reference to understand these are ip's of webservers]

Now by giving command we can target any group's nodes to apply changes in them easily.

To run any linux command inside ansible we use command module as shown in below image :

ansible all -m command -a "ls"            # m = method a = arbitory task that you r telling ahead.
ansible all -a "sudo yum install tree -y" # This command will install tree in all nodes of all groups that v have configured in previous step. 
ansible all -s "yum install tree -y"-b    #Insted of using sudo everytime we can use -b anywhere in command to achieve same result
ansible all -b -m yum -a "pkg=git state=present"  #to install git package
ansible all -b -m yum -a "pkg=git state=abscent" #to uninstall git package
ansible all -a "which httpd" -b # to check installation status of httpd package
ansible all -b -m service -a "name=httpd status=present" # to start httpd service
ansible all -a "service httpd status" -b # to check status od service
ansible all -b -m user -a "name=rani state=present" #user with name rani will get created in all connected nodes  
ansible all -m setup #to check all information about connected nodes 
history  # this will display all the commands you executed earlier
##----------------------------------
##Here default nature of ansible system is like install a package, create user/ffile/folder , start a service
##so we r not required to explicitly write that in command,we ust need to write if we need to uninstall package,delete user/ffile/folder,stop service

And if you want to perform many tasks then go with :

Playbooks

$ vi create_user.yml # paste below script inside this ile to create new user 

#-----------
---
- name: This playbook is to create user
  hosts: all
  become: true
  tasks:
  - name: creating a user rohit
    user: name=rohit
#-------------

#save this file by :wq and come out of the editor. Now it;s time to run this file
$ ansible-playbook create_user.yml
  • What Are Ansible Modules?

Ansible modules are standalone scripts used in playbooks to perform tasks such as managing files, packages, and services on remote systems. They abstract the complexity of system management, providing a simplified interface for common operations. Each module has its own structure, including arguments, parameters, and return values, which you specify to achieve the desired outcome.

  • How Ansible Modules Work?

Ansible modules are executed on remote systems through Ansible’s communication methods, such as SSH. This interaction allows modules to perform tasks directly on the target systems. A key feature of these modules is idempotency, which ensures that running the same module multiple times will not result in unintended changes. It’s also important to differentiate between modules and plugins: while modules perform specific tasks, plugins extend Ansible’s functionality.

  • Best Practices for Using Ansible Modules

  1. Modular Playbooks: Utilize modules to keep playbooks clean and manageable.

  2. Version Control: Track changes to modules, particularly custom ones, to ensure stability.

  3. Testing: Always test playbooks in a staging environment before deploying to production to avoid unexpected issues.


Incase you want to know different playbooks please look into my below github repository: Ansible-Playbooks

For further references go through below links :

By following these steps, you can efficiently set up and configure Ansible to manage your infrastructure, whether it's on-premises or in the cloud.

0
Subscribe to my newsletter

Read articles from Anushka Bhujang Pawar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Anushka Bhujang Pawar
Anushka Bhujang Pawar