Ansible Basic Level Interview Questions
Ansible Basic Level Interview Questions
This category of Ansible Interview Questions consists of questions that you’re expected
to know. These are the most basic questions. An interviewer will start with these and
eventually increase the difficulty level. Let’s have a look at them.
Continuous Delivery is a process where you build software in such a way that it can be
released to production at any time. Consider the diagram below:
Let me explain the above diagram:
Automated build scripts will detect changes in Source Code Management (SCM)
like Git.
Once the change is detected, source code would be deployed to a dedicated build
server to make sure build is not failing and all test classes and integration tests are
running fine.
Then, the build application is deployed on the test servers (pre-production servers)
for User Acceptance Test (UAT).
Finally, the application is manually deployed on the production servers for release.
The New York Stock Exchange (NYSE) encountered a glitch in their software which
prevented them from trading stocks for approx 90 minutes. On the night before, new
software was installed on 8 of its 20 trading terminals. Unfortunately, the software failed
to operate properly on the 8 terminals.
Therefore, by using Configuration Management tools such as Ansible and Puppet, they
reverted back to the old software. Had they not implemented CM, they would’ve taken a
much longer time to fix the issue which would lead to a much bigger loss.
Q3. What is Ansible and what makes it stand out from the rest of the
Configuration Management tools?
Here’s a list of features that makes Ansible such an effective Configuration Management
and Automation tool:
Ansible, unlike other configuration management tools, is categorized into two types of
servers – Controlling machines and Nodes. Controlling machine is where Ansible is
installed and nodes are the ones that are managed by the controlling machines through
SSH. There is an inventory file in the controlling machine that holds the location of the
node systems. Ansible deploys modules on the node systems by running the playbook
on the controlling machine. Ansible is agentless, that means there is no need to have a
third party tool to make a connection between one node and the other.
The main component of Ansible is the Ansible automation engine. This engine directly
interacts with various cloud services, Configuration Management Database (CMBD) and
different users who write various playbooks to execute the Ansible Automation engine.
Inventories: These are a list of nodes containing their respective IP addresses, servers,
databases, etc. which needs to be managed.
APIs: Just like any other API, the Ansible APIs are used for commuting various Cloud
services, public or private services.
Modules: The modules are used to manage system resources, packages, libraries, files,
etc. Ansible modules can be used to automate a wide range of tasks. Ansible provides
around 450 modules that automate nearly every part of your environment.
Plugins: If you want to execute Ansible tasks as a job, Ansible Plugins can be used. They
simplify the execution of a task by building a job like an environment that basically
contains pieces of code corresponding to some specific functionality. There are 100s of
Plugins provided by Ansible. An example is the Action plugin, which acts as front ends to
modules and can execute tasks on the controller before calling the modules themselves.
Networking: Ansible can also be used to automate different networks and services. It
can do this by creating a playbook or an Ansible role that easily spans different network
hardware.
Hosts: The Ansible Hosts/ Node systems are machines (Linux, Windows, etc) that are
getting automated.
Playbooks: Playbooks are simple code files which describe the tasks that need to be
executed. The Playbooks are written in YAML format. They can be used to automate
tasks, declare configurations, etc.
CMDB: It is a database that acts as a storehouse for various IT installations. It holds data
about various IT assets (also known as configuration items (CI)) and describes the
relationships between such assets.
Cloud: It is a network of remote servers hosted on the Internet to store, manage, and
process data, rather than a local server.
To learn more about Ansible, you can go through this Ansible Tutorial blog.
If you are a windows user then you need to have a virtual machine in which Linux should
be installed. It requires Python 2.6 version or higher. you fulfill these requirements and
you’re good to go!
EPEL (Extra Packages for Enterprise Linux) is an open source and free community-based
repository project from Fedora team which provides high-quality add-on software
packages for Linux distribution including RHEL (Red Hat Enterprise Linux), CentOS, and
Scientific Linux.
The Ansible package is not available in the default yum repositories, so we will enable
EPEL repository by using the below command:
sudo rpm -ivh http://dl.fedoraproject.org/pub/epel/6/i386/epel-release-6-
8.noarch.rpm
This will download all the necessary packages which will be required to install Ansible.
Now that your EPEL repository has been added, all you have to do now is install Ansible
using the command below:
If you wish to check the version of Ansible installed on your system, use the command
below:
ansible –version
Few of the basic terms that are commonly used while operating on Ansible are:
Controller Machine: The Controller machine is responsible for provisioning the servers
that are being managed. It is the machine where Ansible is installed.
Inventory: An inventory is an initialization file that has details about the different servers
you are managing.
Playbook: It is a code file written in the YAML format. A playbook basically contains the
tasks that need to be executed or automated.
Task: Each task represents a single procedure that needs to be executed, e.g. Install a
library.
Module: A module is a set of tasks that can be executed. Ansible has 100s of built-in
modules, but you can also create custom ones.
Role: An Ansible role is a pre-defined way for organizing playbooks and other files in
order to facilitate sharing and reusing portions of provisioning.
Play: A task executed from start to finish or the execution of a playbook is called a play.
Facts: Facts are global variables that store details about the system, like network
interfaces or operating system.
Handlers: Are used to trigger the status of a service, such as restarting or stopping a
service.
Infrastructure as Code (IaC) is a process for managing and operating data servers,
storage systems, system configurations, and network infrastructure.
Therefore, we do not require most of the manual effort since everything is managed and
automated by following the IaC approach. Tools such as Ansible can be used to
implement IaC approach.
Galaxy is a website that lets Ansible users share their roles and modules. The Ansible
Galaxy command line tool comes packed with Ansible, and it can be used to install roles
from Galaxy or directly from a Source Control Management system such as Git. It can
also be used to build new roles, remove existing ones and perform tasks on the Galaxy
website.
You can use the below command to download roles from the Galaxy website:
Instructor-led Sessions
Real-life Case Studies
Assignments
Lifetime Access
Explore Curriculum
The above Adhoc command accesses the netscaler module to disable the server.
Variables in Ansible are very similar to variables in any programming language. Just like
any other variable, an Ansible variable is assigned a value which is used in computing
playbooks. You can also use conditions around the variables. Here’s an example:
Q16. What are the Ansible Modules? Explain the different types.
Ansible modules are a small set of programs that perform a specific task. Modules can
be used to automate a wide range of tasks. Modules in Ansible are considered to be
idempotent or in other words, making multiple identical requests has the same effect as
making a single request.
1. Core modules
2. Extras modules
Core Modules
These are modules that the core Ansible team maintains and will always ship with Ansible
itself. They will also receive a slightly higher priority for all requests than those in the
“extras” repos. The source of these modules is hosted by Ansible on GitHub in the
Ansible-modules-core.
Extras Modules
These modules are currently shipped with Ansible but might be shipped separately in the
future. They are also mostly maintained by the Ansible Community. Non-core modules
are still fully usable but may receive slightly lower response rates for issues and pull
requests.
Popular “extras” modules may be promoted to core modules over time. The source for
these modules is hosted by Ansible on GitHub in the Ansible-modules-extras.
Ansible Tasks allow you to break up bits of configuration policy into smaller files. These
are blocks of code that can be used to automate any process. For example, if you wish
to install a package or update a software, you can follow the below code snippet:
Q18. Can you explain what are playbooks in Ansible? Explain with some
examples.
Playbooks in Ansible are written in the YAML format. It is a human-readable data
serialization language. It is commonly used for configuration files. It can also be used in
many applications where data is being stored.
For Ansible, nearly every YAML file starts with a list. Each item in the list is a list of
key/value pairs, commonly called a “hash” or a “dictionary”. So, we need to know how to
write lists and dictionaries in YAML.
All members of a list are lines beginning at the same indentation level starting with a “- ”
(dash and space). More complicated data structures are possible, such as lists of
dictionaries or mixed dictionaries whose values are lists or a mix of both.
For example, if you want a playbook containing details about the USA:
1 -USA
2 -continent: North America
3 -capital: Washington DC<a name="AnsibleIntermediateLevelInterviewQuestions"></a>
4 -population: 319 million
Now that you know the basic level questions, let’s take a look at a little more advanced
Ansible Interview Questions.
Q19. Can you write a simple playbook to install Nginx on a host machine?
Step 1: Generate a public SSH key and by using SSH connect to your host.
$ ssh-keygen
Ansible Playbook – Ansible Interview Questions – Edureka
Step 2: Next, copy the public SSH key on your hosts. Follow the below command to do
it:
vi /etc/ansible/hosts
Once you run the command, the vi editor will open where you can list down the IP
addresses of your hosts. This is now your inventory.
The above image shows that a connection has been made between the control machine
and the host.
Step 5: Create a playbook to install Nginx on the host machine. To create a playbook
you just need to open a file with a yml extension, like shown below:
In an Ansible Playbook, the tasks are defined as a list of dictionaries and are executed
from top to bottom.
Each task is defined as a dictionary that can have several keys, such as “name” or “sudo”
which signify the name of the task and whether it requires sudo privileges.
A variable server_port is set that listens on TCP port 8080 for incoming requests.
Here, the first task is to get the necessary package for installation of Nginx and then install
it. Internally, Ansible will check if the directory exists and create it if it’s not, otherwise, it
will do nothing.
The next task is to configure Nginx. In Nginx, contexts contain configuration details.
Here, the template is a file you can deploy on hosts. However, template files also include
some reference variables which are pulled from variables defined as part of an Ansible
playbook or facts gathered from the hosts. Facts containing the configuration details are
being pulled from a source directory and being copied to a destination directory.
Handlers here define the action to be performed only upon notification of tasks or state
changes. In this playbook, we defined, notify: restart Nginx handler which will restart
Nginx once the files and templates are copied to hosts.
Step 7: Check if Nginx is installed on the machine. Use the following command:
In the above image, the different process IDs 3555 and 103316 are running which shows
that Nginx is running on your host machines.
Q20. How would you access a variable of the first host in a group?
{{ hostvars[groups['webservers'][0]]['ansible_eth0']['ipv4']['address'] }}
In the above command, we’re basically accessing the hostname of the first machine in
the webservers group. If you’re using a template to do this, use the Jinja2 ‘#set’ or you
can also use set_fact, like shown below:
One basic rule is to ‘always use {{}} except when:’. Conditionals are always run through
Jinja2 as to resolve the expression. Therefore, ‘when:failed_when:’ and ‘changed_when:’
are always templated and we should avoid adding {{}}.
In other cases, except when clause, we have to use brackets, otherwise, differentiating
between an undefined variable and a string will be difficult to do.
DevOps Training
Next
Q22. What is Ansible role and how are they different from the playbook?
Ansible Roles is basically another level of abstraction used to organize playbooks. They
provide a skeleton for an independent and reusable collection of variables, tasks,
templates, files, and modules which can be automatically loaded into the playbook.
Playbooks are a collection of roles. Every role has specific functionality.
Let’s understand the difference between Ansible roles and playbook with an example.
Suppose you want your playbook to perform 10 different tasks on 5 different systems,
would you use a single playbook for this? No, using a single playbook can make it
confusing and prone to blunders. Instead, you can create 10 different roles, where each
role will perform one task. Then, all you need to do is, mention the name of the role inside
the playbook to call them.
Suppose you want to create a handler that restarts a service only if it is already running.
Handlers can “listen” to generic topics, and tasks can notify those topics as shown below.
This functionality makes it much easier to trigger multiple handlers. It also decouples
handlers from their names, making it easier to share handlers among playbooks and
roles:
1
- name: Check if restarted
2 shell: check_is_started.sh
3 register: result
4 listen: Restart processes
5
6
7
8 - name: Restart conditionally step 2
9 service: name=service state=restarted
when: result
10 listen: Restart processes
11
Q24. How to keep secret data in a playbook?
Suppose you have a task that you don’t want to show the output or command given to it
when using -v (verbose) mode, the following task can be used to do it:
1 - hosts: all
2 no_log: True
Q25. What are Ansible Vaults and why are they used?
Ansible Vault is a feature that allows you to keep all your secrets safe. It can encrypt
entire files, entire YAML playbooks or even a few variables. It provides a facility where
you can not only encrypt sensitive data but also integrate them into your playbooks.
Vault is implemented with file-level granularity where the files are either entirely encrypted
or entirely unencrypted. It uses the same password for encrypting as well as for decrypting
files which makes using Ansible Vault very user-friendly.
To create an encrypted file, use the ‘ansible-vault create’ command and pass the
filename.
Once your password is confirmed, a new file will be created and will open an editing
window. By default, the editor for Ansible Vault is vi. You can add data, save and exit.
Ansible Playbook – Ansible Interview Questions – Edureka
The tower allows you to share the SSH credentials without exposing them, logs all the
jobs, manage inventories graphically and syncs them with a wide variety of cloud
providers.
The following section will cover only the technical based Ansible Interview Questions.
These questions are mostly based on the practical implementation of Ansible.
It is well known that in DevOps development and operations work is integrated. This
integration is very important for modern test-driven applications. Hence, Ansible
integrates this by providing a stable environment to both development and operations
resulting in a smooth delivery pipeline.
Ansible In DevOps – Ansible Interview Questions – Edureka
Q30. How can you create a LAMP stack and deploy a webpage by using
Ansible?
Suppose you’re trying to deploy a website on 30 systems, every website deployment will
require a base OS, web-server, Database, and PHP. We use ansible playbook to install
these prerequisites on all 30 systems at once.
For this particular problem statement, you can use two virtual machines, one as a server
where Ansible is installed and the other machine acts as the remote host. Also, I’ve
created a simple static webpage saved in a folder index which has two files, index.html,
and style.css.
In the below code I’ve created a single Ansible playbook to install Apache, MySql, and
PHP:
1
2
3
4 ---
5 # Setup LAMP Stack
6 - hosts: host1
tasks:
7
8 - name: Add ppa repository
9 become: yes
10 apt_repository: repo=ppa:ondrej/php
11
12 - name: Install lamp stack
become: yes
13
apt:
14 pkg:
15 - apache2
16 - mysql-server
17 - php7.0
- php7.0-mysql
18 state: present
19 update cache: yes
20
21 - name: start apache server
22 become: yes
23 service:
name: apache2
24 state: started
25 enabled: yes
26
27 - name: start mysql service
28 become: yes
services:
29 name: mysql
30 state: started
31 enabled: yes
32
33 - name: create target directory
34 file: path=/var/www/html state=directory mode=0755
35
- name: deploy index.html
36 became: yes
37 copy:
38 src: /etc/ansible/index/index.html
39 dest: var/www/html/index/index.html
40
41
42
Now, there are 6 main tasks, each task performs a specific function:
The first task adds the repository required to install MySQL and PHP.
The second task installs apache2, MySQL-server, PHP, and PHP-MySQL.
The third and fourth task starts the Apache and MySQL service.
The fifth task creates a target directory in the host machine and
Finally, the sixth task executes the index.html file, it picks up the file from the server
machine and copies it into the host machine.
To finally run this playbook you can use the following command:
$ ansible-playbook lamp.yml -K
Q31. How do I set the PATH or any other environment variable for a task?
The environment variables can be set by using the ‘environment’ keyword. It can be set
for either a task or an entire playbook as well. Follow the below code snippet to see how:
1 environment:
2 PATH: "{{ ansible_env.PATH }}:/thingy/bin"
3 SOME: value
Q32. How can one generate encrypted passwords for the user module?
There are a couple of ways to do this. The simplest way is to use the ad-hoc command:
mkpasswd --method=sha-512
However, if you’re using a macOS then you can generate these passwords using Python.
To do this you must first install the Passlib password hashing library:
After installing it, the SHA512 password values can be generated in the following manner:
Q33. How can looping be done over a list of hosts in a group, inside of a
template?
An easy way to do this is to iterate over a list of hosts inside of a host group, in order to
fill a template configuration file with a list of servers. This can be done by accessing the
“$groups” dictionary in your template, like so:
1 {% for host in groups['db_servers'] %}
2 {{ host }}
3 {% endfor %}
In order to access facts about these hosts, like, the IP address of each hostname, you
need to make sure that the facts have been populated. For instance, make sure you have
a play that talks to db_servers:
1 - hosts: db_servers
2 tasks:
3 - debug: msg="doesn't matter what you do, just that they were talked to previous
Now you can use the facts within your template, like so:
In order to check the inventory vars resulting from what you’ve defined in the inventory,
you can execute the below command:
Q35. How should one configure a jump host to access servers that I have
no direct access to?
1 [gatewayed]
2 foo ansible_host=192.0.2.1
3 bar ansible_host=192.0.2.2
Next, you can create group_vars/gatewayed.yml containing the following:
Ansible will then append these arguments to the command line while trying to connect to
any hosts in the group gatewayed.
Q36. How can you handle different machines needing different user accounts or
ports to log in with?
The simplest way to do this is by setting inventory variables in the inventory file.
Let’s consider that these hosts have different usernames and ports:
1 [webservers]
2 asdf.example.com ansible_port=5000 ansible_user=alice
3 jkl.example.com ansible_port=5001 ansible_user=bob
Also, if you wish to, you can specify the connection type to be used:
1 [testcluster]
2 localhost ansible_connection=local
3 /path/to/chroot1 ansible_connection=chroot
4 foo.example.com ansible_connection=paramiko
To make this more clear it is best to keep these in group variables or file them in a
group_vars/<group-name> file.
To set all the arguments in a task you can use the dictionary-typed variable. Even though
this is usually good for dynamic executions, it induces a security risk. Therefore, when
this happens, Ansible issues a warning. For example, consider the below code:
1 vars:
2 usermod_args:
3 name: testuser
4 state: present
5 tasks:
- user: '{{ usermod_args }}'
6
This example is safe but creating similar tasks is risky because the parameters and values
passed to usermod_args could be overwritten by malicious values in the host facts on a
compromised target machine.
Yes, Ansible uses a feature called password file, where all the passwords to your
encrypted files can be saved. So each time the user is asked for the password, he can
simply make a call to the password file. The password is automatically read and entered
by Ansible.
Q39. Have you worked with Ansible before? Please share your
experience.
Be very honest here. If you have used ansible before then talk about your experience.
Talk about the projects that required ansible. You can tell the interviewer about how
Ansible has helped you in provisioning and configuration management. If you haven’t
used Ansible before then just talk about any related tools that you’ve used. These related
tools could be anything like Git, Jenkins, Puppet, Chef, Satltstack, etc.
Yes, Ansible is open source. That means you take the modules and rewrite them. Ansible
is an open-source automated engine that lets you automate apps.
Once Ansible is installed on the controlling machines, an inventory file is created. This
inventory file specifies the connection between other nodes. A connection can be made
using a simple SSH. To check the connection to a different device, you can use the ping
module.
The above command checks the connection to all the nodes specified in the inventory
file.
Q42. Is it possible to build our modules in Ansible?
Yes, we can create our own modules within Ansible. It’s an open-source tool which
basically works on python. You can start creating your own modules. The only
requirements would be to be amazingly good at programming.
When any new variable about the system has been discovered it’s considered to be a
“fact” in the playbook. Facts are mainly used to implement conditional executions. It can
also be used to get the ad-hoc information about the system.
So when you want to extract only a part of the information, you use the setup module to
filter out only the needed information.
Ask_pass is the control module in an Ansible playbook. This controls the prompting of the
password when the playbook is getting executed. By default, it’s always set to True. If
you are using SSH keys for authentication purposes then you really don’t have to change
this setting at all.
Callback plugins are enable adding new behaviors to Ansible when responding to events.
By default, callback plugins control most of the output you see when running the
command line program. It can also be used to add additional output, integrate with other
tools, etc.
Ansible has hundreds of modules supporting AWS and some of them include:
Autoscaling groups
CloudFormation
CloudTrail
CloudWatch
DynamoDB
ElastiCache
Elastic Cloud Compute (EC2)
Identity Access Manager (IAM)
Lambda
Relational Database Service (RDS)
Route53
Security Groups
Simple Storage Service (S3)
Virtual Private Cloud (VPC)
Yes, Ansible can provision hardware. A lot of companies are still stuck on to massive data
centers of hardware. There are a few requirements. You must set up some services
before you go ahead. Some of them are – DHCP, PXE, TFTP, Operating System Media,
Web Server, etc.
1
2
3 ---
4 - name: Create an ec2 instance
hosts: web
5 gather_facts: false
6
7 vars:
8 region: us-east-1
9 instance_type: t2.micro
10 ami: ami-05ea7729e394412c8
keypair: priyajdm
11
12 tasks:
13
14 - name: Create an ec2 instance
15 ec2:
16 aws_access_key: '********************'
17 aws_secret_key: '****************************************'
key_name: "{{ keypair }}"
18 group: launch-wizard-26
19 instance_type: "{{ instance_type }}"
20 image: "{{ ami }}"
21 wait: true
region: "{{ region }}"
22
count: 1
23 vpc_subnet_id: subnet-02f498e16fd56c277
24 assign_public_ip: yes
25 register: ec2
26
27
We start by mentioning AWS access key id and secret key using the
parameters aws_access_key and aws-secret_key.
key_name: pass the variable that defines the keypair being used here
group: mention the name of the security group. This defines the security rules of
the EC2 instance we’re trying to bring up
instance_type: pass the variable that defines the type of instance we’re using
here
image: pass the variable that defines the AMI of the image we’re trying to start.
wait: This has a boolean value of either true or false. If true, it waits for the instance
to reach the desired state before returning
region: pass the variable that defines the region in which an EC2 instance needs
to be created.
count: This parameter specifies the number of instances that need to be created.
In this case, I’ve only mentioned only one but this depends on your requirements.
vpc_subnet_id: pass the subnet id in which you wish to create the instance
assign_public_ip: This parameter has a boolean value. If true like in our case, a
public IP will be assigned to the instance when provisioned within VPC.
Q49. Can you copy files recursively onto a target host? If yes, how?
Yes, you can copy files recursively onto a target host using the copy module. It has a
recursive parameter which copies files from a directory. There is another module called
synchronize which is specifically made for this.
1 - synchronize:
2 src: /first/absolute/path
3 dest: /second/absolute/path
4 delegate_to: "{{ inventory_hostname }}"
1
- hosts: blocks
2 tasks:
3 - name: ansible copy file backup example
4 copy:
5 src: ~/helloworld.txt
dest: /tmp
6 backup: yes
7
This brings us to the end of the Ansible Interview Questions article. With increasing
business competition, companies have realized the importance of adapting and taking
advantage of the changing market. Few things that kept them in the game were faster
scaling of systems, better software delivery, adapting to new technologies, etc. That’s
when Ansible swung into the picture and gave these companies boosting support to
continue the race.
If you want to learn more about DevOps, check out the DevOps Training by Edureka, a
trusted online learning company with a network of more than 250,000 satisfied learners
spread across the globe. The Edureka DevOps Certification Training course helps
learners gain expertise in various DevOps processes and tools such as Puppet, Jenkins,
Nagios and GIT for automating multiple steps in SDLC.