The Ultimate Ansible tutorial with Ansible Playbook Examples

Are you tired of managing multiple hosts manually? It’s time to learn and automate configuration management with Ansible with this Ultimate Ansible tutorial with Ansible Playbook Examples.

Ansible is the most popular and widely used automation tool to manage configuration changes across your on-prem and cloud resources.

In this article, you’re going to learn everything you should know about Ansible and will get a jump start on running your Ansible commands and Ansible Playbooks!

Let’s get started!

Join 28 other followers

Table of Contents

  1. What is Ansible?
  2. Ansible Architecture Diagram and Ansible components
  3. Ansible Inventory
  4. Ansible Adhoc command
  5. What is Ansible playbook and Ansible playbook examples!
  6. Executing Ansible when conditional using Ansible playbook
  7. Ansible Variables and Dictionary
  8. Ansible Error Handling
  9. Ansible Handlers
  10. Ansible Variables
  11. Ansible Tags
  12. Ansible Debugger
  13. What are Ansible Roles and a Ansible roles examples?
  14. Conclusion

Join 28 other followers

What is Ansible?

Ansible is an IT automation tool and is most widely used for deploying applications and system configurations easily on multiple servers, either hosted on a data center or on Cloud, etc.

Ansible is an agentless automation tool that manages machines over the SSH protocol by default. Once installed, Ansible does not require any database, no daemons to start or keep running.

Ansible uses inbuilt ansible ad hoc command and Ansible Playbooks to deploy the changes. Ansible Playbooks are YAML-based configuration files that you will see later in the tutorial in depth.

Ansible Architecture Diagram and Ansible components

Now that you have a basic idea about what is Ansible? Let’s further look at Ansible Architecture Diagram and Ansible components that will give you how Ansible works and the components Ansible requires.

Ansible Control Node

Ansible Control Node, also known as Ansible Controller host, is the server where Ansible is installed. This node executes all the Ansible ad hoc commands and Ansible playbooks. /commands. You can have multiple Control nodes but not windows. Must have Python Installed.

Ansible Remote Node or Ansible Managed Nodes

Ansible remote nodes or Ansible managed nodes are the servers or network devices on which you deploy applications or configurations using the Ansible ad hoc commands or playbook. These are also known as Ansible hosts.

Ansible Inventory

Ansible inventory is the file on the Ansible controller host or control node, which contains a list of all the remote hosts or managed nodes.

Ansible Core

Ansible core modules or ansible-core are the main building block and architecture for Ansible, including CLI tools such as ansible-playbook, ansible-doc, and interacting with automation.

The Ansible core modules are owned and managed by the core ansible team and will always ship with ansible itself.

Ansible Modules

Ansible modules or Ansible core modules are the code plugins or libraries plugins that can be used from the command line or a playbook task. Ansible executes each module, usually on the remote managed node, and collects return values.

Ansible Collections

Ansible Collections are a distribution format for Ansible content. Using collections, you can package and distribute playbooks, roles, modules, and plugins. A typical collection addresses a set of related use cases. You can create a collection and publish it to Ansible Galaxy or a private Automation Hub instance.

Ansible Task

Ansible Task is a unit of action executed when running the Ansible Playbook. Ansible Playbook contains one or more Ansible tasks.

Ansible Architecture Diagram and Ansible components
Ansible Architecture Diagram and Ansible components

Ansible Inventory

Ansible works against Ansible remote nodes or hosts to create or manage the infrastructure, but how does Ansible know those Ansible remote nodes? Yes, you guessed it right. Ansible Inventory is a file containing the list of all Ansible remote nodes or remote nodes grouped together, which Ansible uses while deploying or managing the resources.

The default location for Ansible inventory is a file called /etc/ansible/hosts. You can specify a different inventory file using the -I <path> option at the command line. Ansible Inventory is declared in two formats, i.e., INI and YAML.

Ansible installed on the control node communicates with remote nodes over SSH Protocol.

Related: working-with-ssh-connectivity

  • Ansible inventory in ini format is declared as shown below.
           automate2.mylabserver.com
           [httpd]
           automate3.mylabserver.com
           automate4.mylabserver.com
           [labserver]
           automate[2:6].mylabserver.com
  • Ansible inventory in YAML format is declared as shown below.
           all:
             hosts:
                automate2.mylabserver.com
             children:
                 httpd:
                   hosts:
                     automate3.mylabserver.com
                     automate4.mylabserver.com
                 labserver:
                    hosts:
                     automate[2:6].mylabserver.com

Ansible Adhoc command

If you plan to create, launch, deploy, or work with a single configuration file such as restarting an nginx service, a reboot of the machine, copying a file to a remote machine, starting or stopping any particular service, etc. on Ansible remote node then running ad hoc commands will suffice.

Ad hoc commands are a quick and efficient way to run a single command on Ansible remote nodes. Let’s quickly learn how to run Ansible Adhoc commands.

  • To ping all the Ansible remote nodes using Ansible Adhoc command.
ansible all -m ping            # Ping Module to Ping all the nodes
ping all the Ansible remote nodes
ping all the Ansible remote nodes
  • To run echo command on all the Ansible remote nodes using Ansible Adhoc command.
ansible all -a "/bin/echo Automate"  # Echo Command to Provide the output
echo command on all the Ansible remote nodes
echo command on all the Ansible remote nodes
  • To check uptime of all the Ansible remote nodes using Ansible Adhoc command.
ansible all -a /usr/bin/uptime   # Provides the Uptime of the Server
checking uptime of all the Ansible remote nodes
checking uptime of all the Ansible remote nodes
  • To create a user on a Ansible remote node using Ansible adhoc command.
ansible all -m ansible.builtin.user -a "name=name password=password" -b
creating Linux user on Ansible remote node
creating Linux user on Ansible remote node
  • To install Apache nginx service on all the Ansible remote nodes using Ansible Adhoc command.
# b is to become root and gain the root privileges
ansible all -m apt -a  "name=apache2 state=latest" -b  
  • To start Apache nginx service on all the Ansible remote nodes using Ansible Adhoc command.
ansible all -m ansible.builtin.service -a "name=apache2 state=started"
start Apache nginx service on all the Ansible remote nodes
start Apache nginx service on all the Ansible remote nodes
  • To reboot all the remote nodes that are part of america-servers group in Ansible inventory using Ansible adhoc command.
    • america-servers is a group of hosts which is saved in /etc/hosts.
    • To run a command use -a flag.
    • “/sbin/reboot” is to command to reboot the machine
    • -f is used to simultenously execute command on 100 servers.
    • -u is used to run this using a different username.
    • –become is used to run as a root.
ansible america-servers -a "/sbin/reboot"  -f 100 -u username --become

What is Ansible playbook and Ansible playbook examples!

Ansible playbooks are used to deploy complex applications, offer reusable and simple configuration management, offer multi-machine deployments, and perform multiple tasks multiple times. Ansible playbooks are written in YAML format containing multiple tasks and executed in sequential order.

Let’s learn how to declare the Ansible playbook to install Apache on the remote node.

# Playbook apache.yml
---
- name: Installing Apache service 
  hosts: my_app_servers                                  # Define all the hosts
  remote_user: ubuntu                                    # Remote_user is ubuntu
  # Defining the Ansible task
  tasks:                                                  
  - name: Install the Latest Apache
    apt:
      name: httpd
      state: latest
  • Before you run your first Ansible playbook using ansible-playbook command make sure to verify the Playbook to catch syntax errors and other problems before you run them using below command.
ansible-playbook apache.yml --syntax-check
executing ansible-playbook
executing ansible-playbook
  • To verify the playbook in detailed view run the ansible-lint command.
ansible-lint apache.yml
verify the playbook in detailed view
verify the playbook in the detailed view
  • To verify the Ansible playbook run the below command with –check flag.
ansible-playbook apache.yml --check
verify the Ansible playbook with --check flag
verify the Ansible playbook with –check flag
  • Finally execute the Ansible playbook using the below command.
ansible-playbook apache.yml 
 execute the Ansible playbook
execute the Ansible playbook
  • If you intend to install and start the Apache service using Ansible Playbook, copy/paste the below content and run the ansible-playbook command.
# Playbook of apache installation and service startup
---
- name: Install and start Apache service 
  hosts: my_app_servers                                  # Define all the hosts
  remote_user: ubuntu                                    # Remote_user is ubuntu
 # Defining the tasks
  tasks:                                                 
  - name: Install the Latest Apache
    apt:
      name: httpd
      state: latest
  - name: Ensure apache2 serice is running
    service:  
      name: apache2
      state: started
    become: yes                   # if become is set to yes means it has activated privileges
    become_user: ubuntu    # Changes user to ubuntu and by default it is root

Executing Ansible when conditional using Ansible playbook

The Ansible when is a Jinja2 expression that evaluates the test or the condition for all remote nodes and wherever the test passes (returns a value of True), run the Ansible task or Ansible playbook on that host.

  • In the below Ansible Playbook there are four tasks i.e
    • To check the latest version
    • Ensuring Apache service is running
    • Creating users with_item
    • Finally editing the file only when ip matches using Ansible when.
---
- name: update web servers
  hosts: webserver
  remote_user: ubuntu

  tasks:
   - name: ensure apache is at the latest version
     apt:
       name: apache2
       state: latest

   - name: Ensure apache2 serice is running
     service:
        name: apache2
        state: started
     become: yes
 
   - name: Create users
     user:
         name: "{{item}}"
     with_items:
      -bob
      -sam
      -Ashok
 
   - name: Edit the text file
     lineinfile:
     path:  /tmp/file
     state: present
     line:  "LogLevel debug"
     when:
     - ansible_hostname == "ip-10-111-4-18" 
  • Finally execute the Ansible playbook using the below command.
ansible-playbook apache.yml 
execute the Ansible playbook
execute the Ansible playbook

In case you have a common parent layer then you don’t need to declare common things every time in the Ansible task as it automatically inherits directives applied at the block level.

In the below example, Ansible when, Ansible become Ansible become_user, ignore_errors are common for the entire block.

---
- name: update web servers
  hosts: webserver
  remote_user: ubuntu

  tasks:
   - name: Install, configure and start Apache
     block:
      - name: Install apache
        apt:
          name: apache2
          state: present
      - name: Ensure apache2 serice is running
        service:
           name: apache2
           state: started
    # Below Directives are common for entire block i.e all tasks
     when: ansible_facts['distribution'] == "Debian" 
     become: true
     become_user: root
     ignore_errors: yes
Execute the Ansible playbook using Ansible when
Execute the Ansible playbook using Ansible when

Ansible Variables and Dictionary

In this section, let’s quickly look into how Ansible loops iterate over a dictionary item and convert it into list items.

  • Create another playbook named abc.yaml and copying the code below.
# Playbook using iterating over a dictionary

 - name: Add several users 
   ansible.builtin.user: 
      name: "{{ item.name }}" 
      state: present 
      groups: "{{ item.groups }}" 
   loop: 
     - { name: 'automate1', groups: 'root' }
     - { name: 'automate2', groups: 'root' } 
  • Now execute the Ansible Playbook using the below command.
ansible-playbook abc.yaml

As you can see below, the Dictionary items have been converted into the List.

Ansible Playbook containing Ansible variables and dictionary
Ansible Playbook containing Ansible variables and dictionary

Ansible Error Handling

When Ansible receives a non-zero return code from a command or a failure from a module, by default, it stops executing on that host and continues on other hosts. Still, at times, a non-zero return code indicates success, or you want a failure on one host to stop execution on all hosts.

Ansible uses Error handling to work with the above conditions to handle these situations and help you get the behavior and output you want.

  • Create below playbook named main.yml and copy/paste the below code and execute the playbook. The below task perform various tasks such as:
    • One of the Ansible tasks prints a message “i execute normally”
    • Fails a task
    • One task will not proceed
ansible-playbook main.yml
---
- name: update web servers
  hosts: localhost
  remote_user: ubuntu
  tasks:
  - name: Ansible block to perform error handling 
    block:

      - name: This task prints a message i execute normally
        ansible.builtin.debug:
          msg: 'I execute normally'

      - name: This task will fail
        ansible.builtin.command: /bin/false

      - name: This task will not proceed due to the previous task failing
        ansible.builtin.debug:
          msg: 'I never execute, '

    rescue:
      - name: Print when errors
        ansible.builtin.debug:
          msg: 'I caught an error, can do stuff here to fix it'

    always:
      - name: Always do this
        ansible.builtin.debug:
          msg: 'This executes always'
Ansible Playbook with Ansible Error Handling
Ansible Playbook with Ansible Error Handling

Ansible Handlers

Ansible handlers are used when you need to perform any task only when notified. You add all the tasks inside the handler block in Ansible Playbook, and Ansible handlers run whenever notify calls them.

For example, whenever there is any update or change in configuration or restarting, the service is required. Ansible Handlers run when they are notified.

In the below example, if there are changes in the /tmp/file.txt, the apache service is restarted. Ansible Handler will restart the Apache service only when the lineinfile task notifies it.

---
- name: update web servers
  hosts: webserver
  remote_user: ubuntu
 
  tasks:
   - name: ensure apache is at the latest version
     apt:
      name: apache2
      state: latest

   - name: Ensure apache2 serice is running
     service:
        name: apache2
       state: started
     become: yes

# Edit the text file using lineinfile module
   - name: Edit the text file 
      lineinfile:
       path:  /tmp/file.txt
       state: present
       line:  "LogLevel debug"
      when:
        - ansible_hostname == "ip-10-111-4-18"
      notify:
      -  Restart Apache

  handlers:
   - name: Restart Apache
     ansible.builtin.service:
       name: apache2
       start: restarted 
Ansible Playbook with Ansible Handlers
Ansible Playbook with Ansible Handlers

Ansible Variables

Ansible uses Ansible variables to manage multiple configurations with various attributes. With Ansible, you can execute tasks and playbooks on multiple systems with a single command with variations among different systems.

Ansible variables are declared with standard YAML syntax, including lists and dictionaries. There are lots of ways in which you can set your Ansible variables inside the ansible-play; let’s learn by:

  • Defining Ansible variable normally
  • Defining Ansible variables from file
  • Defining Ansible variables from roles
  • Defining Ansible variable at run time
---
- name: update web servers
  hosts: webserver
  remote_user: ubuntu
  remote_install_path: /tmp/mypath       # Defining Simple Variable      ~1
  vars:                                  # Defining Variables from Role  ~2
     favcolor: blue   
  vars_files:                           # Defining Variables from file   ~3  
     - /vars/external_vars.yml
 
  tasks:
   - name: Check Config
     ansible.builtin.template:
       src: my.cfg.j2
       dest: '{{remote_install_path}}/my.cfg'
  • Defining Ansible variable at run time with key : value format
ansible-playbook myplaybook.yml --extra-vars "version=1.23.45 other_variable=auto"
  • Defining Ansible variable at run time with JSON format
ansible-playbook myplaybook.yml --extra-vars '{"version":"1.23.45","other_variable":"auto"}'

Ansible Tags

When you need to run specific tasks in the Ansible playbook, you need to consider using Ansible Tags. Ansible tags are applied on Ansible blocks level, Ansible playbook, Ansible task, or at Ansible role level.

Let’s learn how to add Ansible Tags at different levels.

  • Adding Ansible Tags to individual Ansible tasks.
---
 - hosts: appservers
   tasks:
   - name: Deploy App Binary
     copy:
	   src: /tmp/app.war
	   dest: /app/
	   
	tags: 
	  - apptag          # Applying Ansible Tag to task 1
	 
 - hosts: dbserver	   
   tasks:
   - name: Deploy DB Binary
     copy: 
       src: /tmp/db.war`
       dest: /db
     tags:   	         # Applying Ansible Tag to task 2
       - dbtag
  • Adding Ansible Tags to Ansible block.
tasks:
- block:
  tags: ntp                     # Applying Ansible Tags to Ansible block
  - name: Install ntp
    ansible.builtin.yum:
      name: ntp
      state: present

  - name: Enable and run ntpd
    ansible.builtin.service:
      name: ntpd
      state: started
      enabled: yes
  • Adding Ansible Tags to Ansible Playbook.
- hosts: all
  tags: ntp                     #  Applying Ansible Tags to Ansible Playbook
  tasks:
  - name: Install ntp
    ansible.builtin.yum:
      name: ntp
      state: present

Ansible Debugger

Ansible provides a debugger to fix errors during execution instead of editing it and then running.

  • Using Ansible debugger on a Ansible task.
- name: Execute a command
  ansible.builtin.command: "false"
  debugger: on_failed
Ansible debugger in Ansible Playbook
Ansible debugger in Ansible Playbook
  • Using Ansible debugger on a Ansible Playbook.
- name: My play
  hosts: all
  debugger: on_skipped
  tasks:
    - name: Execute a command
      ansible.builtin.command: "true"
      when: False

  • Using Ansible debugger on a Ansible Playbook and Ansible task.
- name: Play
  hosts: all
  debugger: never
  tasks:
    - name: Execute a command
      ansible.builtin.command: "false"
      debugger: on_failed

What are Ansible Roles and a Ansible roles examples

Ansible Roles is a way to structurally maintain your Ansible playbooks, i.e., it lets you load the variables from files, variables, handlers, tasks based on the structure. Similar to the Ansible modules, you can create different Ansible roles and reuse them as many times as you need.

  • Let’s look at what an Ansible Role directory structure looks like.
    • Tasks : This directory contains one or more files with tasks . These file can also refer to files and templates without needing to provide the exact path.
    • Handlers: Add all your handlers in this directory
    • Files: This directory contains all your static files and scripts that might be copied or executed to remote machine.
    • Templates: This directory is reserved for templates that generate files on remote hosts.
    • Vars: You define variables inside this directory and then can be referenced elsewhere in role.
    • defaults: This directory lets you define default variables for included or dependent role.
    • meta: This directory is used for dependency management such as dependency roles.
Ansible Role directory structure
Ansible Role directory structure

Join 28 other followers

  • Creating a Sample Ansible Playbook as shown below which you will break in different file to understand how Ansible role has file structure.
--- 
- hosts: all 
  become: true 
  vars: 
    doc_root: /var/www/example 
  tasks: 
    - name: Update apt 
      apt: update_cache=yes 
 
    - name: Install Apache 
      apt: name=apache2 state=latest 
 
    - name: Create custom document root 
      file: path={{ doc_root }} state=directory owner=root group=root  
 
    - name: Set up HTML file 
      copy: src=index.html dest={{ doc_root }}/index.html owner=root group=root mode=0644 
 
    - name: Set up Apache virtual host file 
      template: src=vhost.tpl dest=/etc/apache2/sites-available/000-default.conf 
      notify: restart apache 
 
  handlers: 
    - name: restart apache 
      service: name=apache2 state=restarted
  • Let’s break the playbook that you created previously into Ansible roles by:
    • Creating a directory named roles inside home directory.
    • Creating a directory named apache inside roles inside home directory.
    • Creating a directory named defaults, tasks, files, handlers, vars, meta, templates inside apache
  • Create main.yml inside ~/roles/apache/tasks directory.
---    
- name: Update apt
      apt: update_cache=yes

    - name: Install Apache
      apt: name=apache2 state=latest

    - name: Create custom document root
      file: path={{ doc_root }} state=directory owner=www-data group=www-data

    - name: Set up HTML file
      copy: src=index.html dest={{ doc_root }}/index.html owner=www-data group=www-data mode=0644

    - name: Set up Apache virtual host file
      template: src=vhost.tpl dest=/etc/apache2/sites-available/000-default.conf
      notify: restart apache
  • Create main.yml inside ~/roles/apache/handlers directory.
---
handlers:
    - name: restart apache
    service: name=apache2 state=restarted
  • Create index.html inside ~/roles/apache/files directory.
<html>
<head><title>Configuration Management Hands On</title></head>
<h1>This server was provisioned using Ansible</h1>
</html>
  • Create vhost.tpl inside cd ~/roles/apache/templates
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot {{ doc_root }}

<Directory {{ doc_root }}>
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
  • Create main.yml inside cd ~/roles/apache/meta
---
dependencies:
  - apt
  • Create my_app.yml inside home directory
---
- hosts: all
  become: true
  roles:
    - apache
  vars:
    - doc_root: /var/www/example

Join 28 other followers

Conclusion

In this Ultimate Guide, you learned what is Ansible, Ansible architecture, and understood Ansible roles and how to declare Ansible Playbooks.

Now that you have gained a handful of Knowledge on Ansible, what do you plan to deploy using it?

Ultimate Ansible interview questions and answers

If you are preparing for a DevOps interview or for an Ansible administrator, consider this guide as your friend to practice ansible interview questions and answers and help you pass the exam or interview.

Without further delay, let’s get into this Ultimate Ansible interview questions and answers guide, where you will have three Papers to practice containing 20 questions of Ansible.

Join 28 other followers

PAPER-1

Q1. What is Ansible ?

Answer: Ansible is open source configuration tool written in python Language. Ansible is used to deploy or configure any software, tools or files on remote machines quickly using SSH Protocol.

Q2. What are advantages of Ansible.

Answer: Ansible is simple to manage, agent-less, has great performance as it is quick to deploy and doesn’t require much efforts to setup and no doubt it is reliable.

Q3. What are the things which Ansible can do ?

Answer: Deployment of apps such as apache tomcat, AWS EC2 instance, configuration Management such as configure multiple file in different remote nodes , Automates tasks and is used for IT orchestration.

Q4. Is it possible to have Ansible control node on windows ?

Answer: No, you can have Ansible controller host or node only on Linux based operating system however you can configure windows machine as your remote hosts.

Q5. What are requirements when the remote host is windows machine ?

Answer: Ansible needs Powershell 3.0 and at least .NET 4.0 to be installed on windows Host, winRM Listener should be created and activated before you actually deploy or configure remote node as windows machine.

Q6. Where are different components of Ansible ?

Answer: API’s, Modules, Host , Playbook , Cloud, Networking and Inventories.

Q7.What are Ansible adhoc commands ?

Answer: Ansible adhoc commands are the single line commands that are generally used for testing purpose or if you need to take an action which is not repeatable and rarely used such as restart service on a machine etc. Below is the example of ansible adhoc command.

The below command starts the apache service on the remote node.

ansible all -m ansible.builtin.service -a “name=apache2 state=started”

Q8. What is the ansible command to check uptime of all servers ?

Answer: Below is the ansible command to check uptime of the servers. This command will provide you an output stating since long the remote node is up.

ansible all -a /usr/bin/uptime 
Ansible ad hoc command to check the uptime of the server which is 33 days.
Ansible ad hoc command to check the server’s uptime, which is 33 days.

Q9. How to Install the Apache service using ansible command ?

Answer: To install apache service using ansible command you can use ansible adhoc command as shown below. In the below command b flag is to become root.

ansible all -m apt -a  "name=apache2 state=latest" -b  

Q10.What are the steps or commands to Install Ansible on Ubuntu Machine ?

Answer: The below commands you will need to execute to Install Ansible on Ubuntu Machine

# Update your system packages using apt update command
sudo apt update 
# Install below prerequisites package to work with PPA repository.
sudo apt install software-properties-common 
# Install Ansible PPA repository (Personal Package repository) 
sudo apt-add-repository –yes –update ppa:ansible/ansible
# Finally Install ansible
sudo apt install ansible

Q11. What is Ansible facts in Ansible ?

Answer: Ansible facts allows you to fetch or access the data or values such as hostname or Ip address from the remote hosts and stored.

Below is the example showing how you can run Ansible facts using ansible-playbook named main.yml.

# main.yml 
---
- name: Ansible demo
  hosts: web
  remote_user: ubuntu
  tasks:
    - name: Print all available facts
      ansible.builtin.debug:
        var: ansible_facts

 ansible-playbook main.yml
Output of the Ansible facts using ansible-playbook
The output of the Ansible facts using ansible-playbook

Q12. What are Ansible tasks ?

Answer: Ansible tasks are group of task which ansible playbook needs to perform such as copy , installing package , editing configurations on remote node and restarting services on remote node etc.

Let’s look at a basic Ansible task. In below code the Ansible task is to check if apache service is running on the remote node?

tasks:
  - name: make sure apache is running
    service:
      name: httpd
      state: started

Q13. What are Ansible Roles ?

Answer: Ansible roles is a way to structurally maintain your playbooks such that you can easily understand and work on it. Ansible role basically contains different folders for the simplicity such as it lets you load the files from files folder, variables from variable folder, handlers, tasks etc.

You can create different Ansible roles and reuse them as many times as you need.

Q14. Command to Create a user on linux machine using Ansible?

Answer: To create a user on linux machine using Ansible you can use ansible adhoc command as shown below.

ansible all -m ansible.builtin.user -a “name=name password=password” -b

Q15. What is Ansible Tower ?

Answer: Ansible tower is web based solution that makes Ansible even more to easy to use for IT teams. Ansible tower can be used for upto 10 nodes. It captures all recent activities like status of host . It integrates with notifications’ about all necessary updates. It also schedules Ansible Jobs very well.

Q16. How to connect with remote machines in Ansible?

Answer: After installing Ansible , configure Ansible inventory with the list of hosts or grouping them accordingly and finally connecting them using SSH protocol. After you configure the Ansible inventory you can test the connectivity between Ansible controller and remote nodes using ping module to ping all the nodes in your inventory

ansible all -m ping

You should see output for each host in your inventory, similar to this:

aserver.example.org | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}

Q17. Does Ansible support AWS?

Answer: Yes. There are lots of AWS modules that are present in Ansible and can be used to manage AWS resources. Refer Ansible collections in the Amazon Namespace.

Q18. Which Ansible module allows you to copy files from remote machine to control machine ?

Answer: Ansible fetch module. Ansible fetch module is used for fetching files from remote machines and storing them locally in a file tree, organized by hostname.

- name: Store file from remote node directory to host directory 
  ansible.builtin.fetch:
    src: /tmp/remote_node_file
    dest: /tmp/fetched_host_file

Q19. Where you can find Ansible inventory by default ?

Answer: The default location of Ansible inventory is /etc/ansible/hosts.

Q20. How can you check the Ansible version?

Answer: To check the ansible version, run the ansible –version command below.

ansible --version
Checking the ansible version by using ansible --version command.
Checking the ansible version by using the ansible –version command.

Join 28 other followers

PAPER-2

Q1. Is Ansible agentless ?

Answer: Yes, Ansible is an open source tool that is agentless. Agentless here means when you install Ansible on host controller and when you use to deploy or configure changes on remote nodes, the remote node doesn’t require any agent or softwares to be installed.

Q2. What is Primary use of Ansible ?

Answer: Ansible can be used in IT Infrastructure to manage and deploy software application on remote machines.

Q3. What are Ansible Hosts or remote nodes ?

Answer: Ansible hosts are machines or nodes on which Ansible controller host deploys the software’s. Ansible host could be Linux, RedHat, Windows, etc.

Q4. What is CI (Continuous Integration) ?

Answer: CI also known as Continuous integration is primarily used by developers. Successful Continuous integration means when developers code is built , tested and then pushed to Shared repository whenever there is a change in code.

Q5. What is the main purpose of role in Ansible ?

Answer: The main purpose of Ansible role is to reuse the content again by using the proper Ansible folder structure directory. These directory’s folder contains multiple configuration files or content accordingly that needs to be declared at various places and in various modules, to minimize the re-code work roles are used.

Q6. What is Control Node?

Answer: The Control node is the Ansible node on which Ansible is installed. Before you install control node make sure Python is already installed on machine prior to installing Ansible.

Q7. Can you have Windows machine as Controller node ?

Answer: No.

Q8. What is the other names of Ansible Hosts?

Answer: Ansible hosts can also be called as Managed nodes. Ansible is not installed on managed nodes.

Q9. What is host file in Ansible ?

Answer: Inventory file is also known as host file in Ansible which is by default stored in /etc/ansible/hosts directory.

Q10. What is collections in Ansible ?

Answer: Ansible collections is a distribution format that include playbooks, roles, modules, plugins.

Q11. What is Ansible module in Ansible.

Answer: Ansible contains various Ansible modules that have a specific purpose such as copying the data, adding a user and many more. You can invoke a single module within a task defined in playbooks or several different modules in a playbook.

Q12. What is task in Ansible ?

Answer: To perform any action you need a task. Similarly in Ansible you need a task to run modules. For Ansible ad hoc command you can execute task only once.

Q13. What is Ansible Playbook?

Answer: Ansible playbook is an ordered lists of tasks that you run and are designed to be human-readable and are developed in a basic text language. For example in the below ansible playbook there are two tasks first is to create a user named adam and other task is to create a user shanky in the remote node.

---
- name: Ansible Create user functionality module demo
  hosts: web # Defining the remote server
  tasks:

    - name: Add the user 'Adam' with a specific uid and a primary group of 'sudo'
      ansible.builtin.user:
        name: adam
        comment: Adam
        uid: 1095
        group: sudo
        createhome: yes        # Defaults to yes
        home: /home/adam   # Defaults to /home/<username>

    - name: Add the user 'Adam' with a specific uid and a primary group of 'sudo'
      ansible.builtin.user:
        name: shanky
        comment: shanky
        uid: 1089
        group: sudo
        createhome: yes        # Defaults to yes
        home: /home/shanky  # Defaults to /home/<username>

Creating two users using ansible playbook
Creating two users using ansible-playbook

Q14. Where do you create basic inventory in Ansible?

Answer: /etc/ansible/hosts

Q15. What is Ansible Tower ?

Answer: Ansible tower is web based solution that makes Ansible even more to easy to use for IT teams. Ansible tower can be used for upto 10 nodes. It captures all recent activities like status of host . It integrates with notification’s about all necessary updates. It also schedules Ansible Jobs very well.

Q16. What is the command for running the Ansible playbook?

Answer: The below is the command to run or execute the ansible-playbook.

ansible-playbook my_playbook

Q17. On which protocol does Ansible communicate to remote node?

Answer: SSH

Q18. How to use ping module to ping all the nodes?

Answer: Below is the command which you can use to ping all the remote nodes.

ansible all -m ping

Q19. Provide an example to run a live command on all of your nodes?

Answer:

ansible all -a "/bin/echo hello"
Printing hello on remote node using ansible command.
Printing hello on remote node using ansible command.

Q20. How to run ansible command with privilege escalation (sudo and similar) ?

Answer: Below command executes the ansible command with root access by using --become flag.

ansible all -m ping -u adam --become

PAPER-3

Q1. Which module allows you to create a directory?

Answer: Ansible file module allows you to create a directory.

Q2. How to define number of parallel processes while communicating to hosts .

Answer: By setting the forks in ansible and to set the forks you need to edit ansible.cfg file.

Q3. Is Ansible agentless configuration management Tool ?

Answer: Yes

Q4. What is Ansible Inventory ?

Answer: Ansible works against managed nodes or hosts to create or manage the infrastructure . We list down these hosts or nodes in a file known as Inventory. Inventory can be of two types one is ini and other is YAML format

Q5. How to create a Ansible inventory in the ini format ?

Answer:

automate2.mylabserver.com
[httpd]
automate3.mylabserver.com
automate4.mylabserver.com
[labserver]
automate[2:6].mylabserver.com

Q6. How to create a Ansible inventory in the YAML format?

Answer:

all:
  hosts:
     automate2.mylabserver.com
  children:
      httpd:
        hosts:
          automate3.mylabserver.com
          automate4.mylabserver.com
      labserver:
         hosts:
          automate[2:6].mylabserver.com

Q7.What is Ansible TAG ?

Answer: When you need to add tags with Ansible then you can use Ansible Tags to do this. You can apply Ansible Tags on block level , playbook level, individual task level or role level.

tasks:
- name: Install the servers
  ansible.builtin.yum:
    name:
    - httpd
    - memcached
    state: present
  tags:
  - packages
  - webservers

Q8. What are key things required for Playbook ?

Answer: Hosts should be configured in inventory, Tasks should be declared in ansible playbook and Ansible should already be installed.

Q9. How to use existing Ansible tasks ?

Answer: We can use by importing the tasks import_tasks. Ansible import_tasks imports a list of tasks to be added to the current playbook for subsequent execution.

Q10. How can you secure the data in Ansible-playbook ?

Answer: You can secure the data using ansible-vault to encrypt the data and later decrypt it. Ansible Vault 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.

Q11. What is Ansible Galaxy?

Answer: Ansible Galaxy is a repository for Ansible Roles that are available to drop directly into your Playbooks to streamline your automation projects.

Q12. How can you download roles from Ansible Galaxy ?

Answer: Below code allows you to download roles from Ansible Galaxy.

ansible-galaxy install username.role_name

Q13. What are Variables in ansible?

Answer: Ansible variables are assigned with values which are further used for commuting. After you create variables, either by defining them in a file, passing them at the command line, or registering the return value or values of a task as a new variable

Q14. Command to generate a SSH key-pair for connecting with remote machines?

Answer: ssh-keygen

Q15. What is Ansible Tower ?

Answer: Ansible tower is web based solution that makes Ansible even more to easy to use for IT teams. Ansible tower can be used for upto 10 nodes. It captures all recent activities like status of host . It integrates with notification’s about all necessary updates. It also schedules Ansible Jobs very well.

Q16. What is the command for running a playbook?

Answer:

ansible-playbook my_playbook

Q17. Does Ansible support AWS?

Answer: Yes.There are lots of modules that are present in Ansible.

Q18. How to create encrypted files using Ansible?

Answer: By using the below ansible-vault command.

ansible-vault create file.yml 

Q19. What are some key features of Ansible Tower?

Answer:

With Ansible Tower, you can view dashboards and see whatever is going on in real-time, job updates, who ran the playbook or ansible commands, Integrated notifications, schedule ansible jobs, run ansible remote commands, and perform.

Q20. What is the first-line syntax of any Ansible playbook?

Answer: First line syntax of ansible-playbook is – – –

---   # The first Line Syntax of ansible playbook

Join 28 other followers

Conclusion

In this ultimate guide, you had a chance to revise everything you needed to pass the interview with Ansible interview questions and answers.

Now that you have sound knowledge of Ansible and various components, modules, and features, and are ready for your upcoming interview.

How to Install Apache tomcat using Ansible.

If you are looking to install apache tomcat instances, consider using Ansible as a great way.

Ansible is an agentless automation tool that manages machines over the SSH protocol by default. Once installed, Ansible does not add a database, and there will be no daemons to start or keep running.

With Ansible, you can create an ansible playbook and use it to deploy dozens of tomcat in one go. In this tutorial, you will learn how to install apache tomcat using Ansible. Let’s get started.

Join 28 other followers

Table of Content

  1. Prerequisites
  2. Building tomcat Ansible-playbook on the Ansible Controller
  3. Running Ansible-playbook on the Ansible Controller
  4. Tomcat files and Tomcat directories on a remote node
  5. Conclusion

Prerequisites

This post will be a step-by-step tutorial. If you’d like to follow along, be sure you have:

  • An Ansible controller host. This tutorial will be using Ansible v2.9.18.
  • A remote Linux computer to test out the tomcat installation. This tutorial uses Ubuntu 20.04.3 LTS as the remote node.
  • An inventory file and one or more hosts are configured to run Ansible commands and playbooks. The remote Linux computer is called webserver, and this tutorial uses an inventory group called web.

Ensure your remote machine IP address is inside /etc/ansible/hosts ( either one remote machine or define it as a group)

Building tomcat Ansible-playbook on the Ansible Controller

Ansible is an automation tool used for deploying applications and systems easily; it could be Cloud, Services, orchestration, etc. Ansible uses YAML Language to build playbooks which are finally used to deploy or configure the required change. To deploy tomcat, let’s move ahead and create the ansible-playbook.

  • SSH or login into your any Linux machine.
  • Create a file named my_playbook3.yml inside /etc/ansible folder and paste below code.

The below playbook contains all the tasks to install tomcat on the remote node. The first task is to update your system packages by using the apt command, further creating tomcat user and group. The next task is to install java, install tomcat, and create necessary folders and permissions for the tomcat directory.

---
- name: Install Apache Tomcat10 using ansible
  hosts: webserver
  remote_user: ubuntu
  become: true
  tasks:
    - name: Update the System Packages
      apt:
        upgrade: yes
        update_cache: yes

    - name: Create a Tomcat User
      user:
        name: tomcat

    - name: Create a Tomcat Group
      group:
        name: tomcat

    - name: Install JAVA
      apt:
        name: default-jdk
        state: present


    - name: Create a Tomcat Directory
      file:
        path: /opt/tomcat10
        owner: tomcat
        group: tomcat
        mode: 755
        recurse: yes

    - name: download & unarchive tomcat10 
      unarchive:
        src: https://mirrors.estointernet.in/apache/tomcat/tomcat-10/v10.0.4/bin/apache-tomcat- 10.0.4.tar.gz
        dest: /opt/tomcat10
        remote_src: yes
        extra_opts: [--strip-components=1]

    - name: Change ownership of tomcat directory
      file:
        path: /opt/tomcat10
        owner: tomcat
        group: tomcat
        mode: "u+rwx,g+rx,o=rx"
        recurse: yes
        state: directory

    - name: Copy Tomcat service from local to remote
      copy:
        src: /etc/tomcat.service
        dest: /etc/systemd/system/
        mode: 0755

    - name: Start and Enable Tomcat 10 on sever
      systemd:
        name: tomcat
        state: started
        daemon_reload: true


Running Ansible-playbook on the Ansible Controller

Earlier in the previous section, you created the ansible-playbook, which is great, but it is not doing much unless you deploy it. To deploy the playbook using the ansible-playbook command.

Assuming you are logged into Ansible controller:

  • Now run the playbook using the below ansible-playbook command.
ansible-playbook my_playbook3.yml

As you can see below, all the tasks are successfully completed; if the status of TASK shows ok, that means the task was already completed; else, for changed status, Ansible performs the task on the remote node.

Running the ansible-playbook in the Ansible controller host
Running the ansible-playbook in the Ansible controller host
  • Next, verify remote machine if Apache Tomcat is installed successfully and started use the below command.
systemctl status tomcat 
service tomcat status
Verifying the tomcat service on the remote node
Verifying the tomcat service on the remote node
  • Also you can verify by running process command.
ps -ef | grep tomcat
ps -aux | grep tomcat
Checking the tomcat process
Checking the tomcat process
Checking the tomcat process
Checking the tomcat process

Join 28 other followers

Tomcat files and Tomcat directories on a remote node

Now that you have successfully installed the tomcat on the remote node and verified the tomcat service, it is equally important to check the tomcat files created and the purpose of each of them.

  • Firstly all the tomcat files and tomcat directories are stored under <tomcat-installation-directory>/*.

Your installation directory is represented by environmental variable  $CATALINA_HOME

  • The tomcat directory and files should be owned by user tomcat
  • The tomcat user should be member of tomcat group.
Verify all files of tomcat
Verify all files of tomcat
  • <tomcat-installation-directory>/bin: This directory consists of startup and shutdown scripts (startup.sh and shutdown.sh) to run or stop the tomcat directly without using the tomcat service configured.
Verify installation directory of tomcat
Verify installation directory of tomcat
  • <tomcat-installation-directory>/conf: This is very crucial directory where tomcat keeps all its configuration files.
Tomcat configuration directory
Verify Tomcat configuration directory
  • <tomcat-installation-directory>/logs: In case you get any errors while running your tomcat then you can look at your safeguard ie. logs , tomcat creates its own logs under this directory.
Tomcat logs directory
Verify Tomcat logs directory
  • <tomcat-installation-directory>/webapps: This is the directory where you place your code such as .war and run your applications. It is highly recommended to stop tomcat and then deploy your application inside this directory and then start tomcat.
Tomcat Code directory
Verify Tomcat Code directory

Join 28 other followers

Conclusion

In this tutorial, we covered in-depth how can you install Apache Tomcat 10 on the ubuntu 18.0 version using Ansible controller and finally discussed files and directories which are most important for any Apache tomcat admins and developers.

If you wish to run your application on lightweight and easily, Apache Tomcat is your friend.

How to Work with Ansible When and Other Conditionals

If you need to execute Ansible tasks based on different conditions, then you’re in for a treat. Ansible when and other conditionals let you evaluate conditions, such as based on OS, or if one task is dependent on the previous task.

In this tutorial, you’re going to learn how to work with Ansible when and other conditionals so you can execute tasks without messing things up.

Click here and Continue reading

How to Install Ansible and Run ansible-playbooks on Ubuntu 18.04 LTS

Installing software or running commands on one machine is ok, but what if you have dozens of servers to manage? To deploy software or configuration file changes on dozens of servers, consider using Ansible.

Ansible is a configuration and automation tool used to easily deploy multiple applications on multiple systems; it could be CLOUD, Services, orchestration, etc.

In this tutorial, you will learn step by step how to Install Ansible and Run Ansible playbooks on Ubuntu machines. Let’s get started.

Join 28 other followers

Table of Content

  1. What is Ansible ?
  2. Prerequisites
  3. How to Install Ansible on Ubuntu 18.04 LTS
  4. What is Ansible playbook and Ansible playbook examples!
  5. Conclusion

What is Ansible ?

Ansible is an automation tool used for deploying applications and systems easily; it could be CLOUD, Services, orchestration, etc. Ansible uses YAML Language to build playbooks to deploy or configure the required change. Ansible is an agentless automation tool that manages machines over the SSH protocol by default. Once installed, Ansible does not add a database, and there will be no daemons to start or keep running.

Related: The Ultimate Ansible tutorial with Ansible Playbook Examples

Prerequisites

  • Ubuntu machine preferably 18.04 plus version. If you don’t have any machine you can create an AWS EC2 instance on AWS account with recommended 4GB RAM and atleast 5GB of drive space

You may incur a small charge for creating an EC2 instance on Amazon Managed Web Service.

How to Install Ansible on Ubuntu 18.04 LTS

Let’s kick off this tutorial by installing Ansible on ubuntu. Installing Ansible on the ubuntu machine is a straightforward task. This tutorial will install Ansible from the Personal Package Archive repository (PPA).

  • Login to Ubuntu machine using your favorite SSH client.
  • First, update your existing list of packages by running the below command
sudo apt update
  • Install below prerequisites softwares so that apt uses packages over https protocol. The apt transport software allow your machine to connect with external respositories to connect over HTTPS or HTTP over TLS.
sudo apt install software-properties-common # This Package is used to work with PPA  
  • Add PPA ansible Repository in the system. This repository contains the Ansible software package.
sudo apt-add-repository --yes --update ppa:ansible/ansible 
#  PPA is Personal Package Archive 
Adding PPA ansible Repository in the system
Adding PPA ansible Repository in the system
  • Next install the Ansible Package using the below command.
sudo apt install ansible
  • Now verify if Ansible installation is successful.
ansible --version
Verifying the Ansible installation
Verifying the Ansible installation

What is Ansible playbook and Ansible playbook examples!

Ansible playbooks are used to deploy complex applications, offer reusable and simple configuration management, offer multi-machine deployments, and perform multiple tasks multiple times. Ansible playbooks are written in YAML format containing multiple tasks and executed in sequential order.

Now that you have successfully installed Ansible on the ubuntu machine let’s learn the basics of Ansible Playbook and how to build and run Ansible Playbooks using the Ansible tool. Let’s learn how to declare the Ansible playbook to install Apache on the remote node.

Basic inventory that is remote machines can be configured inside /etc/ansible/hosts. Make sure Ansible controller host node can ssh into worker node that is remote machine.

Related: working-with-ssh-connectivity

  • Create a folder under home directory named ansibledemo.
cd ~
mkdir ansibledemo
  • Create a apache.yml file inside the same directory. This Plaubook will install Apache service on the remote nodes.
- name: Installing Apache service on all my_app_servers  # Define the process
  hosts: webserver                                          # Define the host or group
  remote_user: ubuntu                                    # Remote_user is ubuntu

 
  become: true
  tasks:                                                 # Define the tasks
  - name: Install the Latest Apache
    apt:
      name: apache2
      state: latest

  • Before you run your first ansible-playbook you can verify the syntax , check tasks and details of playbook.
ansible-playbook apache.yml --syntax-check
Checking the syntax of Ansible Playbook
Checking the syntax of Ansible Playbook
ansible-lint apache.yml   # To check detailed 
Checking the syntax of Ansible Playbook in detail
Checking the syntax of Ansible Playbook in detail
  • Now run the ansible-playbook command
ansible-playbook apache.yml --check
Executing the Ansible Playbook
Executing the Ansible Playbook
  • Now, verify in remote host if apache2 is has been installed successfully and if service is running by running the service command.
service apache2 status
Verifying the Apache service on ubuntu machine
Verifying the Apache service on ubuntu machine
  • You can also verify if apache is running using Ip address of the sever followed by port 80.
Verifying the Apache service on Browser
Verifying the Apache service on Browser

Conclusion

In this article, you learned Ansible, how to install Ansible on an Ubuntu machine, and how to declare Ansible Playbooks and run Ansible playbooks.

Now that you have gained a handful of Knowledge on Ansible, what do you plan to deploy using it?