Ansible Tutorial Part-1 Remarkable Introduction

Ansible Tutorial

 Ansible Tutorial

In this Ansible Tutorial, you will learn that:

  • It is a RedHat.
  • It is a configuration management tool
  • It is a Push based configuration tool.
  • It is infrastructure as a Code (IaC) but we can manage network, containers, cloud, security, applications using Ansible
  • It is agentless means we need to install Ansible only on the Master node and connect to the agent using the master’s ssh public key( ssh-keygen)
  • To Manage IaC using Ansible you can use Ansible Adhoc Commands or Ansible playbooks (script).

Ansible Tutorial-Architecture

Master Server

In this Ansible Tutorial, the server where Ansible is installed and using Ansible you are managing the configuration on host machines (Agent machine)

Host servers/machines

In this Ansible Tutorial, the host servers are agent machines where you need to change the configuration using Ansible. For example, if you need to change the configuration on webservers and DB servers then webservers and DB servers are host servers.

Inventory or host file 

It is a file where all host machines’ IP addresses or FQDN ( Full qualified domain name) are mentioned.

By default the path is /etc/ansible/hosts

Below are the formats by which we can configure hosts machines IP or FQDN in the hosts file

IP Addresses:- You can specify the IP addresses of your host machine.

Group:- You can add IP address which is relevant to a group. For example, if you have 2 IPs 192.168.10.10 and 192.168.10.11 are web servers then you can specify a group called webservers

[webservers]

192.168.10.10

192.188.10.11

Range:- You can also define a range of domain names in the host file. In below example, we are specifying domain names like db-99.mydomain to db-110.mydomain.com

db-[99-110].mydomain.com

Ansible Modules

  • Modules are used to accomplish automation tasks in Ansible. These programs are written to be resource models of the desired state of the system. Ansible then executes these modules and removes them when finished. Without modules, you’d have to rely on ad-hoc commands and scripting to accomplish tasks.
  • Modules are used with Adhoc commands as well as with playbooks.
  • Modules are having attributes or properties which help to define the desired state of a given task.
  • For example, if you want to install an apache server on a Ubuntu machine then the apt module has a property called name and state where name indicates package name (apache2) and state indicates installed, removed etc.
  • To display all the modules ( ansible-doc -l)
  • To search a particular module ( ansible-doc -s yum)

Example:

  1. yum module represents yum package manager
  2. apt module represents package manager for Debian-based OS.

Ansible configuration file (ansible.cfg)

It is the file that has settings related to the Ansible package.

for example

Change the inventory path

Change role path

Ansible Adhoc Commands:

An Ansible ad hoc command uses the /usr/bin/ansible command-line tool to automate a single task on one or more managed nodes. ad hoc commands are quick and easy, but they are not reusable. So why learn about ad hoc commands first? ad hoc commands demonstrate the simplicity and power of Ansible.

Ansible PlayBooks:

In this ansible tutorial ansible playbooks are the script files that are used for managing the infrastructure on host machines that are configured in the inventory file. For example if you want to install a package on Webservers then you can write a yaml script (playbook) to install package on webservers.

 Ansible Tutorial-Roles

  • Ansible Tutorial is a standard directory structure to abstract the functionality of Ansible playbooks.
  • You can search and download some of the existing roles from Ansible Galaxy website ( https://galaxy.ansible.com/)

Ansible Tutorial Roles Directory Structure

Ansible Tutorial when you create or install an ansible galaxy role than the following directories automatically get created and these directories have a special purpose. Except for the templates and tests directory, all the pre-defined directories contain main.yml, if any of these directories get called then the execution of that directory is started from main.yml code only.

defaults:- For default variables values.

files: – files which are referred to in the role.

handler:– Whenever there is any notification is triggered when the handler’s main.yml file gets called which should have a definition of those notification services.

meta:- It stores role’s metadata like Authorname, version etc

tasks:- Contains the definition of modules which are supposed to execute as a task.

templates:- It includes the Jinja templates definition.

tests:- Contains test cases for role

vars:- To define global variables for the roles.

To download and install an ansible-galaxy roleStep 1:- Download and use apache role from Ansible Galaxy.

Step 2: Goto this Ansible Galaxy Page ( which I got by searching apache2 in ansible-galaxy website).

Step 3: Copy the installation step.

Step 4: Uncomment roles_path in ansible.cfg file

Step 5: Run the installation step which will download the apache role

ansible-galaxy install geerlingguy.apache

Step 6: Goto /etc/ansible/roles directory and you will find a folder  “geerlingguy.apache”

Step 7: To use this role you need to write a playbook

      —
– name: using predefined ansible galaxy role to install apache
            hosts: webservers
roles:
– geerlingguy.apache

Step 8: Execute the playbook

ansible-playbook apacherole.yaml

Step 9:- Check all the webservers, apache should be installed on these servers and apache service is up and running.

To create user-defined roles.

Step 1:– Create an apache user-defined role

ansible-galaxy init apache –offline

Step 2:– By Executing the above command will create a folder under /etc/ansible/roles directory which has the required directory structure for the apache role.

Step 3:– Create tasks to install apache on agent node.

cd /etc/ansible/roles/apache/tasks

Step 4:– Open main.yml file and add below code where I am including 2 yaml files, one for installing apache and second for configuring apache service

– include: install.yml

 

– include: configure.yml

Step 5:– Create Install.yml file

 - name: Installing apache on ubuntu
   apt:
       name: apache2
       state: present
   when: ansible_facts['os_family'] == "Debian"
 - name: Installing httpd on Redhat
   yum:
       name: httpd
       state: present
   when: ansible_facts['os_family'] == "RedHat"

Step 6:- Create Configure.yml file

---
  - name: apache status
    copy: src=status.txt dest=/tmp/status.txt
    notify:
       restart apache service
    when: ansible_facts['os_family'] == "Debian"
  - name: httpd status
    copy: src=status.txt dest=/tmp/status.txt
    notify:
       restart httpd service
    when: ansible_facts['os_family'] == "RedHat"

  - name: send the file
    copy: src=test.html dest=/var/www/html/test.html

Step 7:- Define handler in main.yml file.

---
  # handlers file for apache
  - name: restart apache service
    service: name=apache2 state=restarted
  - name: restart httpd service
    service: name=httpd state=restarted

Step 8:- Create test.html and status.txt file in  files folder.

cd /etc/ansible/roles/apache/files

echo “<h1> Super Cool Html file </h1>” >> test.html

touch status.txt

Step 9:- Create playbook (apache.yaml) and call apache role.

– hosts: webservers

roles:

– apache

Step 10: Execute playbook and verify on webservers that apache is installed and running.

ansible-playbook apache.yml

Ansible Tutorial-Playbooks Examples

  • Ansible Tutorial should be installed on the master node.
  • Should have root access to Master and other nodes
  • Not  mandatory but In my example, I am working as a root user
  • Master node and Managed Nodes ( Agent nodes) should be configured and in the network.
  • Master node’s public and private ssh should generate (ssh-keygen)
  • Master node’s public is to be shared with Agent nodes ( /root/.ssh/authorized_keys) file

 

Current Setup: 3 Ubuntu Servers ( 1 master and 2 agent nodes)\

Master server is also a DB server.

   Master IP: 192.168.33.10

   Webserver1 IP: 192.168.33.11

   Webserver2 IP: 192.168.33.12

Host file Setup

Goto /etc/ansible/hosts file and add below entries

 [dbservers]
192.168.33.10
[webservers]
192.168.33.11
192.168.33.12
Ansible Configuration file
/etc/ansible/ansible.cfg
uncomment(remove #) host file path
inventory      = /etc/ansible/hosts
Example 1: Create a playbook to run an echo “Hello World” command on dbservers.
Playbook: hello.yaml
Create a hello.yaml ( you can give any primary name but the extension should be .yaml or .yml).
---
 - name: play for running shell commands
   hosts: dbservers
   tasks:
         - name: Executing command module
           command: echo "Hello World"
Execute
             ansible-playbook hello.yaml
Example 2: 
Playbook: hello.yaml
In Example1 playbook was executed successfully but it did not print Hello World. You can use “register” to store the output of the previous command in a variable. Let’s modify hello.yaml file
---
 - name: play for running shell commands
   hosts: dbservers
   tasks:
           - name: Executing echo command
             command: echo "Hello World"
             register: output
           - name: Print the output
             debug:
                 msg: "{{ output.stdout }}"
Execute: ansible-playbook hello.yaml

Adhoc Commands

Ansible commands to manage the IaC.

If the configuration is not complex( do not have conditional statements or loops etc.) then we can use the Adhoc commands.

 

Challenge 1 ping Module:

 

  1. To check web servers are reachable or not using Adhoc commands.
  2. To check all hosted servers are reachable or not using Adhoc commands.
  3. To check webserver1 is reachable or not using Adhoc command.
  4. To check all hosted servers are reachable or not using Adhoc commands when the hosts file is in a different location (/home/vagrant/mydir/hosts)

The module used: ping

Solution

Run the below ansible adhoc command with ping module

  1. ansible webservers -m ping
  2. ansible all -m ping
  3. ansible 192.168.33.11 -m ping
  4. ansible -i /home/vagrant/mydir/hosts all -m ping

Challenge 2 Shell Module

  1. Install apache on webservers
  2. Uninstall apache on webservers
  3. Create a file in /tmp/1.txt on dbservers and webservers
  4. Change the permission of /tmp/1.txt file by give rw permission to owner, r permission to group, and other users.
  5. Copy /tmp/1.txt file to /tmp/2.txt file

Module:- Shell ( it is the module to run any Linux commands using Ansible)

Solution:

  1. ansible webservers -m shell -a ” apt update && apt install apache2 -y”
  2. ansible webservers -m shell -a ” apt purge apache2 -y”
  3. ansible webservers,dbservers -m shell -a “touch /tmp/1.txt”
  4. ansible webservers,dbservers -m shell -a “chmod 644 /tmp/1.txt”
  5. ansible webservers,dbservers -m shell -a “cp /tmp/1.txt /tmp/2.txt”

Challenge: apt/yum Module

 

  1. Install apache on webservers.
  2. Uninstall apache package.

 

Solution

  1. ansible webservers -m apt -a “name=apache2 state=present”
  2. ansible webservers -m apt -a “name=apache2 state=absent purge=yes”

Challenge 3 service module

  1. Start apache server on webservers
  2. Stop apache service on webservers
  3. Restart apache service on webservers

Solution

  1.  ansible webservers -m service -a “name=apache2 state=started”
  2.  ansible webservers -m service -a “name=apache2 state=stopped”
  3.  ansible webservers -m service -a “name=apache2 state=restarted”

Challenge 4 copy module

 

  1. Copy a file/tmp/status.txt from master server to webservers.
  2. Copy a file /tmp/status.txt from master server to webservers at /tmp/newstatus.txt
  3. Create a file on webservers /tmp/4.txt with content Hello World

 

Solution

  1.   ansible webservers -m copy -a “src=/tmp/status.txt dest=/tmp/status.txt”
  2.   ansible webservers -m copy -a “src=/tmp/status.txt dest=/tmp/newstatus.txt”
  3.   ansible webservers -m copy -a “content=’Hello World’ dest=/tmp/4.txt”

Ansible Tutorial : Vault

In this Ansible tutorial we also explain ansible vault that is a feature of ansible that allows you to keep sensitive data such as passwords or keys in encrypted files, rather than as plaintext in playbooks or roles. These vault files can then be distributed or placed in source control.

Ansible Tutorial : Vault Commands

1. Create ansible-vault password-protected encrypted file.

ansible-vault create playbook.yaml

2. Execute encrypted ansible-vault file.

ansible-playbook playbook.yaml –ask-vault

3. Decrypt an ansible-vault file

ansible-vault decrypt playbook.yaml

4. Encrypt existing playbook with ansible-vault

ansible-vault encrypt playbook.yaml

If you are also learning Python, you can check out our detailed guide on Mastering Conditional Statements In Python
If you want to clear common misconceptions, check out my detailed guide on 6 Myths About File Handling In Python-open() and close() Functions Exposed