Categories

Top 40 Ansible Interview Questions and Answers of 2021

CTA

Q1. What is Ansible?
Q2. What is the use of Ansible?
Q3. What are the features of Ansible?
Q4. What are the advantages of Ansible?
Q5. What is Ansible Galaxy?
Q6. What is CI/CD?
Q7. What is configuration management?
Q8. What are Ansible server requirements?
Q9. What are Ansible tasks?
Q10. Explain a few of the basic terminologies or concepts in Ansible

The Ansible Interview Questions blog is largely divided into the following parts:

1. Basic-level Ansible Interview Questions

2. Intermediate-level Ansible Interview Questions

Watch this video from Intellipaat on YouTube to learn more about Ansible

Top 40 Ansible Interview Questions and Answers of 2021

Youtube subscribe

Basic-level Ansible Interview Questions

Let us look into some basic level ansible interview questions and answers for DevOps:

1. What is Ansible?

Ansible is a configuration management system. It is used to set up and manage infrastructure and applications. It allows users to deploy and update applications using SSH, without needing to install an agent on a remote system.

2. What is the use of Ansible?

Ansible is used for managing IT infrastructure and deploying software apps to remote nodes. Ansible allows you to deploy an application to many nodes with one single command. However, for that, there is a need for some programming knowledge to understand the Ansible scripts.

3. What are the features of Ansible?

Ansible has the following features:

  • Agentless: Unlike Puppet or Chef, there is no software or agent managing the nodes
  • Python: Built on top of Python, which is very easy to learn and write scripts. It is one of the robust programming languages
  • SSH: Passwordless network authentication makes it more secure and easy to set up
  • Push architecture: The core concept is to push multiple small codes to configure and run the action on client nodes
  • Set up: This is very easy to set up with a very low learning curve. It is open-source; so, anyone can access it.
  • Manage inventory: Machines’ addresses are stored in a simple text format and we can add different sources of truth to pull the list using plug-ins such as OpenStack, Rackspace, etc.

4. What are the advantages of Ansible?

Ansible has many strengths which include:

  • It is agentless and only requires SSH service running on target machines.
  • Python is the only required dependency and, fortunately, most systems come with it pre-installed.
  • It requires minimal resources; so, there is low overhead.
  • It is easy to learn and understand since Ansible tasks are written in YAML.
  • Unlike other tools, most of which are procedural, Ansible is declarative; it defines the desired state and fulfills the requirements needed to achieve it.

5. What is Ansible Galaxy?

Ansible can communicate with configured clients from the command line by using the Ansible command. It also allows you to automate configuration by using the Ansible-playbook command. To create the base directory structure, you can use a tool bundled with Ansible, which is known as ansible-galaxy.

Command: ansible-galaxy init azavea. Packer

Check out this Ansible tutorial and practice for getting a better understanding of Ansible.

6. What is CI/CD?

Continuous integration is something that is used for streamlining the development and deployment process. This has led to the more rapid development of cohesive software. Each integration is verified by an automated build to detect integration errors as quickly as possible.

Continuous delivery is the process where your code after being pushed to a remote repository can be taken to production at any time. It is, in simpler words, a process where you build software in such a way that it can be released to production at any time.

Ansible CICD

7. What is configuration management?

It is a practice that we should follow in order to keep track of all updates that are going into the system over a period of time. This also helps in a situation where a major bug has been introduced to the system due to some new changes that need to be fixed with minimum downtime. Configuration management (CM) keeps a track of all updates that are needed in a system and it ensures that the current design and build state of the system is up to date and functioning correctly.

Get 50% Hike!

Master Most in Demand Skills Now !

8. What are Ansible server requirements?

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. If these requirements are fulfilled, then you can proceed with ease.

9. What are Ansible tasks?

The task is a unit action of Ansible. It helps by breaking a configuration policy into smaller files or blocks of code. These blocks can be used in automating a process. For example, to install a package or update a software:

Command: Install <package_name>

Command: update <software_name>

10. Explain a few of the basic terminologies or concepts in Ansible

A few of the basic terms that are commonly used while operating on Ansible are:

  • Controller machine: The controller machine is responsible for provisioning 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 that 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., installing a library.
  • Module: A module is a set of tasks that can be executed. Ansible has hundreds of built-in modules but you can also create custom ones.
  • Role: An Ansible role is a predefined 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 such as network interfaces or operating systems.
  • Handlers: Handlers are used to trigger the status of a service such as restarting or stopping a service.

11. What is a playbook?

A playbook has a series of YAML-based files that send commands to remote computers via scripts. Developers can configure complete complex environments by passing a script to the required systems rather than using individual commands to configure computers from the command line remotely. Playbooks are one of Ansible’s strongest selling points and are often referred to as Ansible’s building blocks.

12. State the differences between variable names and environment variables

Variable Names Environment Variables
It can be built by adding strings. To access the environment variable, the existing variables need to be accessed.
{{ hostvars[inventory_hostname][‘ansible_’ + which_interface][‘ipv4’][‘address’] }} # … vars: local_home: “{{ lookup(‘env’,’HOME’) }}”
You can easily create multiple variable names by adding strings. To set environment variables, you need to see the advanced playbooks section.
Ipv4 address type is used for variable names. For remote environment variables, use {{ ansible_env.SOME_VARIABLE }}.

13. Where are tags used?

A tag is an attribute that sets the Ansible structure, plays, tasks, and roles. When an extensive playbook is needed, it is more useful to run just a part of it as opposed to the entire thing. That is where tags are used.

14. Which protocol does Ansible use to communicate with Linux and Windows?

For Linux, the protocol used is SSH.

For Windows, the protocol used is WinRM.

Also, have a look at our DevOps course in Bengaluru if you are looking for a DevOps certification!

15. What are ad hoc commands? Give an example

Ad hoc commands are simple one-line commands used to perform a certain task. You can think of ad hoc commands as an alternative to writing playbooks. An example of an ad hoc command is as follows:

Command: ansible host -m netscaler -a "nsc_host=nsc.example.com user=apiuser password=apipass"

16. Compare Ansible with Chef

Ansible vs Chef

Ansible Chef
Easy to set up Not very easy to set up
Easy to manage Management is not easy
Configuration language is YAML (Python) Configuration language is DSL (Ruby)
Self-support package is $5,000 annually.

Premium version costs $14,000 annually for each 100 nodes

Standard plan starts at $72 annually per node. The automation version charges $137 per node annually

Career Transition

17. What is a YAML file and how do we use it in Ansible?

YAML files are like any formatted text file with a few sets of rules similar to that of JSON or XML. Ansible uses this syntax for playbooks as it is more readable than other formats.

18. Code difference between JSON and YAML:

JSON:

{
 "object": {
"key": "value",
"array": [
   {
     "null_value": null
   },
   {
     "boolean": true
   },
   {
     "integer": 1
   },
   {
     "alias": "aliases are like variables"
   }
]
  }
}

YAML:

---
object:
  key: value
  array:
  - null_value:
  - boolean: true
  - integer: 1
  - alias: aliases are like variables

19. How is Ansible different from Puppet?

Ansible vs Puppet

Ansible Puppet
Easy to set up Comparatively harder to set up
Very easy to manage Not very easy to manage
Configuration language is YAML (Python) Configuration language is DSL (Puppet DSL)
Self-support package is $5,000 annually. The premium version costs $14,000 annually for each 100 nodes Enterprise pricing starts at $120 for every node annually. The premium version costs $19,900 annually for each 100 nodes

Intermediate-level Ansible Interview Questions

Stepping up the level, let us now look into some intermediate-level Ansible interview questions and answers for experienced professionals:

20. Explain how you can disable cowsay?

If cowsay is installed, then by executing playbooks inside the Ansible, you can disable cowsay by using the two ways given below:

  • Uninstall cowsay
  • Set up value for the environment variable

export ANSIBLE_NOCOWS = 1

21. What is Ansible-doc?

Ansible-doc displays information on modules installed in Ansible libraries. It displays a listing of plug-ins and their short descriptions, provides a printout of their documentation strings, and creates a short snippet that can be pasted in a playbook.

22. What is the code you need to write for accessing a variable name?

The following command will do the job:

{{ hostvars[inventory_hostname]['ansible_' + which_interface]['ipv4']['address'] }}

The method of using hostvars is important because it is a dictionary of the entire namespace of variables. ‘inventory_hostname’ variable specifies the current host you are looking over in the host loop.

23. What is the method to check the inventory vars defined for the host?

This can be done by using the following command:

ansible -m debug -a "var=hostvars['hostname']" localhost

24. Explain Ansible facts

Ansible facts can be thought of as a way for Ansible to get information about a host and store it in variables for easy access. This information stored in predefined variables is available to use in the playbook. To generate facts, Ansible runs the set-up module.

25. When should you test playbooks and roles?

In Ansible, tests can be added either in new playbooks or to existing playbooks. Therefore, most testing jobs offer clean hosting each time we use them. By using this testing methodology, we need to make very minute or zero code changes.

26. Discuss the method to create an empty file with Ansible

To create an empty file you need to follow the steps given below:

  • Step 1: Save an empty file into the files directory
  • Step 2: Copy it to the remote host

27. Explain Ansible modules in detail

Ansible modules are small pieces of code that perform a specific task. Modules can be used to automate a wide range of tasks. Ansible modules are like functions or standalone scripts that run specific tasks idempotently. Their return value is JSON strings in stdout and its input depends on the type of module.

There are two types of modules:

  • Core modules: These are modules that the core Ansible team maintains and will always ship with Ansible itself. The issues reported are fixed on priority than those in the extras repo. The source of these modules is hosted by Ansible on GitHub in Ansible-modules-core.
  • Extras Modules: The Ansible community maintains these modules; so, for now, these are being shipped with Ansible but they might get discontinued in the future. Popular extras modules may be promoted to core modules over time. The source for these modules is hosted by Ansible on GitHub in Ansible-modules-extras.

28. What are callback plug-ins in Ansible?

Callback plug-ins mostly control the output we see while running CMD programs. Apart from this, it can also be used for adding additional output or multiple outputs. For example, log_plays callback is used to record playbook events into a log file and mail callback is used to send an email on playbook failures.

You can also add custom callback plug-ins by dropping them into a callback_plugins directory adjacent to play, inside a role, or by putting it in one of the callback directory sources configured in ansible.cfg.

29. What is Ansible inventory and its types?

An Ansible inventory file is used to define hosts and groups of hosts upon which the tasks, commands, and modules in a playbook will operate.

In Ansible, there are two types of inventory files, static and dynamic.

  • Static inventory: Static inventory file is a list of managed hosts declared under a host group using either hostnames or IP addresses in a plain text file. The managed host entries are listed below the group name in each line.
  • Dynamic inventory: Dynamic inventory is generated by a script written in Python or any other programming language or, preferably, by using plug-ins. In a cloud set-up, static inventory file configuration will fail since IP addresses change once a virtual server is stopped and started again.

Check out our DevOps training course especially curated by industry experts!

30. What is an Ansible vault?

Ansible vault is used to keep sensitive data, such as passwords, instead of placing it as plain text in playbooks or roles. Any structured data file or single value inside a YAML file can be encrypted by Ansible.

To encrypt the data:

Command: ansible-vault encrypt foo.yml bar.yml baz.yml

To decrypt the data:

Command: ansible-vault decrypt foo.yml bar.yml baz.yml

31. How do we write an Ansible handler with multiple tasks?

Suppose you want to create a handler that restarts a service only if it is already running.

Handlers can understand 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.

- name: Check if restarted
shell: check_is_started.sh
register: result
listen: Restart processes

- name: Restart conditionally step 2
service: name=service state=restarted
when: result
listen: Restart processes

32. How to generate encrypted passwords for a user module?

We can do this by using a small code:

ansible all -i localhost, -m debug -a "msg={{ 'mypassword' | password_hash('sha512', 'mysecretsalt') }}"

We can also use the Passlib library of Python.

Command: python -c "from passlib.hash import sha512_crypt; import getpass; print(sha512_crypt.using(rounds=5000).hash(getpass.getpass()))"

33. Explain the concept of blocks under Ansible?

Blocks allow for logical grouping of tasks and in-play error-handling. Most of what you can apply to a single task can be applied at the block level, which also makes it much easier to set data or directives common to the tasks. This does not mean that the directive affects the block itself but is inherited by the tasks enclosed by a block, i.e., it will be applied to the tasks, not the block itself.

34. Do you have any idea of how to turn off the facts in Ansible?

If you do not need any factual data about the hosts and know everything about the systems centrally, we can turn off fact gathering. This has advantages in scaling Ansible in push mode with very large numbers of systems, mainly, or if we are using Ansible on experimental platforms.

Command:
- hosts: whatever
gather_facts: no

35. What are the registered variables under Ansible?

Registered variables are valid on the host for the remainder of the playbook run, which is the same as the lifetime of facts in Ansible. Effectively registered variables are very similar to facts. While using register with a loop, the data structure placed in the variable during the loop will contain a results attribute, which is a list of all responses from the module.

36. By default, the Ansible reboot module waits for how many seconds. Is there any way to increase it?

By default, the Ansible reboot module waits 600 seconds. Yes, it is possible to increase Ansible reboot to certain values. The syntax given-below can be used for the same:

- name: Reboot a Linux system 
reboot:
reboot_timeout: 1200

Have a look at our range of Cloud Computing courses and get certified!

Certification in Cloud & Devops

37. What do you understand by the term idempotency?

Idempotency is an important Ansible feature. It prevents unnecessary changes in managed hosts. With idempotency, we can execute one or more tasks on a server as many times as we need to, but it will not change anything that has already been modified and is working correctly.

To put it simply, the only changes added are the ones needed and not already in place.

38. Can you copy files recursively onto a target host? If yes, how?

We can copy files recursively onto a target host by using the copy module. It has a recursive parameter that copies files from a directory. There is another module called synchronize, which is specifically made for this.

- synchronize:
    src: /first/absolute/path
    dest: /second/absolute/path
    delegate_to: "{{ inventory_hostname }}"

39. Can you keep data secret in the playbook?

The following playbook might come in handy if you want to keep secret any task in the playbook when using -v (verbose) mode:

- name: secret task
  shell: /usr/bin/do_something --value={{ secret_value }}
  no_log: True

It hides sensitive information from others and provides the verbose output.

40. Can docker modules be implemented in Ansible? If so, how can you use it?

Yes, you can implement docker modules in Ansible.

Ansible requires you to install docker-py on the host.

Command: $ pip install 'docker-py>=1.7.0'

The docker_service module also requires docker-compose.

Command: $ pip install 'docker-compose>=1.7.0'

41. How do you test Ansible projects?

There are three testing methods available:

 

  • Asserts: Asserts duplicates how the test runs in other languages like Python. It verifies that your system has reached the actual intended state, and not just as a simulation that you would find in check mode. Asserts shows that the task did the job it was supposed to do and changed the appropriate resources.
  • Check mode: Check mode shows you how everything would run without the simulation. Therefore, you can easily see if the project behaves the way we expected it to. The limitation is that check mode does not run the scripts and commands used in the roles and playbooks. To get around this, we have to disable check mode for specific tasks by running.
  • Command: check_mode: no
  • Manual run: Just run the play and verify that the system is in its desired state. This testing choice is the easiest method, but it carries an increased risk because it results in a test environment that may not be similar to the production environment.

Hope these top Ansible interview questions helped you in preparing for your next job interview. Best of luck and excel at your job interview!

Stuck on something and want to get your doubts clarified? Intellipaat’s DevOps community is just the right place for you!

Course Schedule

Name Date
AWS Certification 2021-10-30 2021-10-31
(Sat-Sun) Weekend batch
View Details
AWS Certification 2021-11-06 2021-11-07
(Sat-Sun) Weekend batch
View Details
AWS Certification 2021-11-13 2021-11-14
(Sat-Sun) Weekend batch
View Details

Leave a Reply

Your email address will not be published. Required fields are marked *