Top 40 Basic Ansible Interview Questions and Answers

Red Hat produces the Ansible product, which offers a variety of features. When we mention Ansible, we will mainly focus on the Ansible Core. Top 40 Basic Ansible Interview Questions

Therefore, Ansible is an IT automation tool. It streamlines deployment, runs playbooks for continuous deployments, and orchestrates different environments. Setting this up can be a little tricky at first, but the documentation provides plenty of guidance.

Top 40 Basic Ansible Interview Questions

1. What is CI/CD?

The purpose of Continuous Integration is to streamline the development and deployment process. As a result, cohesive software can be developed more rapidly. 

On the other hand, continuous delivery refers to the ability to take your code to production at any time after it has been pushed to a remote repository.

We perform our integration tests and unit tests without any manual intervention, and then after UAT we only need the approval to ship our tested features to production, and this is where CI/CD comes in handy.

2. What is Configuration Management?

In order to keep track of all updates that are going into the system over time, it’s a practice we should follow. We can also use this if a major bug is introduced to the system because of some new changes and we need to fix it with minimum downtime. Instead of fixing the bug, we can roll back the new changes (which caused it) as we have been tracking them.

3. How does Ansible work?

As an automation tool, Ansible is a combination of multiple pieces. Modules, playbooks, and plugins are the most common.

    • A module is a small piece of code that gets executed. As a starting point for building tasks, there are several inbuilt modules.
    • Playbooks contain plays, which are further divided into tasks. It is here where you define the workflow or the steps needed to complete the process
    • Modules that run on the main control machine for logging purposes are called plugins. Additionally, there are other types of plugins.

Ansible was used to automate the playbooks. Modules in these playbooks are basically actions that run on host machines. In this case, we are using the push mechanism, so ansible pushes small programs to these host machines, which are written to be resource models of the desired state of the system.

4. What are the features of Ansible?

The following features are present:

Unlike puppet or chef, there is no software or agent managing the nodes.

Python – Built on top of Python, which is an easy programming language to learn and use, and one of the most robust.

SSH provides passwordless network authentication, which is more secure and easier to set up.

In a push architecture, multiple pieces of code are pushed to the client node in order to perform the action.

Setup is very simple, has a very low learning curve, and is open-source so that anyone can get started.

Inventory Management – Machine addresses are stored in a simple text format, and we can add different sources of truth to pull the list, such as Openstack, Rackspace, etc.

5. Explain Infrastructure as Code?

IRC is a process that DevOps teams should follow to manage infrastructure more efficiently. The configuration of any cloud component should be done through a code repository instead of throwing away scripts or manually configuring them. It is wise to put it under source control as well. Speed, consistency, and accountability are improved.

6. What is Ansible Galaxy?

Galaxy is a repository of Ansible roles that can be shared among users and can be dropped directly into playbooks for execution. It is also used to distribute packages containing roles, plugins, and modules, also known as collections. Like an ansible-galaxy command, ansible-galaxy-collection implements init, build, install, etc.

7. Explain Ansible modules in detail?

Ansible modules are like functions or standalone scripts that run specific tasks idempotently. The return value depends on the type of module, but generally, it is a JSON string in stdout and input. Ansible playbooks use these.

Ansible has two types of modules:

Core Modules

These modules are maintained by the core Ansible team, so they are included with Ansible. The issues reported are fixed more quickly than those in the “extras” repository.

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. They can be used, but if there are any feature requests or issues they will be updated on a low priority basis.

Now popular extra modules can be incorporated into the core modules at any time. These separate repositories for these modules are ansible-modules-core and ansible-modules-extra, respectively.

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

Like JSON and XML, YAML files are formatted text files with a few rules. Ansible uses this syntax since it is more readable than other formats.

Here is an example of JSON vs. YAML:


 The object is: {

The “key” is the “value”,

An array consists of: [


    Null value for “null_value”



    True: “boolean”



    The integer 1 is an integer



    “An alias is like a variable”






 Value: key


 In case of null_value:

 Boolean value: true

 -1 integer

 Aliases are like variables

9. What are Ansible tasks?

Ansible’s task is a unit action. A configuration policy can be broken down into smaller files or blocks of code. Automating a process can be done using these blocks. Installing a package or updating a software, for example

Install <package_name>, update <software_name>

10. How to use YAML files in high programming languages such as JAVA, Python, etc?

Most programming languages support YAML, which can be easily integrated into user programs.

We can also parse XML and JSON in Java using the Jackson module. As an example

Topic class must be declared with attributes such as name, total_score, user_score, and sub_topics

ArrayList*Topic> topics = new ArrayList<Topic>();

(new Topic(“String Manipulation”, 10, 6));

(topics.add(“Knapsack”, 5, 5));

(new Topic(“Sorting”, 20, 13));

We want to save this Topic as a YAML file

The topic topic is new Topic(“DS & Algo”, 35, 24, topics);

ObjectMapper is instantiated as before

NewObjectMapper om = new ObjectMapper(new YAMLFactory());

*topic* is written into `topic.yaml`

writeValue(new File(“/src/main/resources/topics.yaml”), topic);

DS & Algo

35 points total

Score: 24


“String Manipulation” is the name of the program.

 Score: 10

 Score: 6

“Knapsack” – name

 Score: 5

 Score: 5

Sorting – name:

 Score: 20

 Score: 13

We can also read from YAML:

The YAML file is loaded from the /resources folder

Loader classLoader = Thread.currentThread().getContextClassLoader();


Creating a new ObjectMapper as a YAMLFactory

Om = new ObjectMapper(new YAMLFactory());

Mapping of the employee from the YAML file to the Employee class

File topic = om.readValue(file, Topic.class);

In the same way, we can use the pajama library in Python to read and write YAML files.

Intermediate Ansible Interview Questions

11. How to set up a jump host to access servers having no direct access?

In the ansible_ssh_common_args inventory variable, we need to define a ProxyCommand since any arguments in this variable are added to the command line when connecting to the relevant host(s). As an example


Ansible_host= on staging1

Ansible_host= in staging2

We need to add a command to ansible_ssh_common_args to create a jump host for these

In ansible_ssh_common_args, specify ‘-o ProxyCommand=”ssh -W %h:%p -q [email protected]”‘.

Thus, whenever we try to connect to any host in the gatewayed group, ansible will append these arguments to the command line.

12. How to automate the password input in the playbook using encrypted files?

To automate password input, we can create a password file where all passwords for encrypted files are saved, and then ansible can call that file when needed.

In Ansible_ssh_common_args, specify ‘-o ProxyCommand=”ssh -W %h:%p -q [email protected]”‘.

You can also do this by having a separate script that specifies the passwords. In this case, however, we need to print a password to stdout to avoid annoying errors.

Playbook launch.yml –vault-password-file

13. What are callback plugins in Ansible?

Most of the output we see when we run cmd programs is controlled by callback plugins. However, it can also be used to add additional output. The log_plays callback records playbook events to a log file, and the mail callback sends an email when a playbook fails. In addition, customized callback plugins can also be added by dropping them into a callback_plugins directory adjacent to a play, inside a role, or by putting it in one of the callback directory sources configured in ansible.

14. What is Ansible Inventory and its types?

Ansible offers two types of inventory files: static and dynamic.

  • It is a list of managed hosts declared under a host group using either hostnames or IP addresses in plain text. In each line, the managed host entries are listed below the group name. As an example


Ansible_host= on staging1

Ansible_host= in staging2

  • The dynamic inventory is created by a script written in Python or any other programming language, or by using plugins (preferred). As soon as a virtual server is stopped and started again, static inventory file configuration will fail since IP addresses change. For the configuration, we create a demo_aws_ec2.yaml file as shown below

Aws_ec2 regions:

Filters for AP-South-1:

Testing tag:tagtype

Using this command, we can fetch

Demo_aws_ec2.yaml -graph

15. What is Ansible Vault?

Ansible vaults are used to store sensitive data such as passwords instead of storing them plaintext in playbooks or roles. Ansible can encrypt any structured data file or any value inside a YAML file. 

Encrypting a file

Encrypt foo.yml bar.yml baz.yml with ansible-vault

Similarly, decryption

Decrypt foo.yml bar.yml baz.yml with Ansible-Vault

16. How can looping be done over a list of hosts in a group, inside of a template?

This can be done by accessing the “$groups” dictionary in the template, like so:

{% for host in groups[‘db_servers’] %}

{{ host }}

For [%endfor %}

We need to ensure that the facts are also populated if we want to access them. For example, a play that talks to db_servers:

db_servers: hosts

Tasks include:

“Something to debug”: msg

This can now be used within a template, as follows:

{% for host in groups[‘db_servers’] %}

{{ hostvars[host][‘ansible_eth0’][‘ipv4’][‘address’] }}

{% endfor %}.

17. What is the ad-hoc command in Ansible?

The ad-hoc command is like a one-line playbook that performs a specific task. Ad-hoc commands have the following syntax

“[pattern] -m [module] -a “[module options]”

We need to reboot all servers in the staging group, for example

Atlanta -a “/sbin/reboot” -u username –become [–ask-become-pass]

18. Install Nginx using Ansible playbook?

The playbook file would be:

– hosts: stagingwebservers

 gather_facts: False


  – server_port: 8080

 Tasks include:

  Install nginx

    NGINX: pkg=nginx state=installed update_cache=true

  – name: serve nginx configuration

     src=../files/flask.conf dest=/etc/nginx/conf.d


     NGINX should be restarted


   – name: restart nginx

     service: name=nginx state=restarted

   – name: restart the flask app

     Name=flask-demo state=restarted

The above playbook fetches all hosts in the staging web servers group to execute these tasks. It is first necessary to install Nginx and then configure it. As a reference, we are also taking a flask server. We also defined handlers so that if the state changes, Nginx would be restarted. If we execute the above playbook, we can verify if Nginx is installed.

grep nginx ps waux

19. How do I access a variable name programmatically?

Strings can be combined to form variable names. We can use this method, for example, to obtain the IPv4 address of an arbitrary interface, where the address may be supplied through a role parameter or other input.

{{ hostvars[inventory_hostname][‘ansible_’ + which_interface][‘ipv4’][‘address’] }}

20. What is the difference between Ansible and Puppet?

In Ansible, the server pushes the configuration to the nodes, whereas in Puppet, the client pulls the configuration from the server.

The puppet has a scheduling feature as A good agent polls every 30 minutes (default settings) to ensure that all nodes are in a desirable state. The free version of Ansible does not have that feature.

Puppet has more than one master node, while Ansible has backup secondary nodes. Both strive to be highly available.

Puppet is considered more difficult to set up than Ansible since it has a client-server architecture and also has its own language called Puppet DSL.

21. What is Ansible Tower and what are its features?

RedHat’s Ansible Tower is an enterprise-level solution. Ansible can be managed across teams in an organization through a web-based console and REST API. There are many features, including

  • With Workflow Editor, we can set up different dependencies among playbooks, or run multiple playbooks maintained by different teams at the same time
  • The status of any play or task can be monitored easily and we can track what’s going to happen next
  • Audit Trail – Logging is very important so that we can quickly return to a functioning state in the event of a problem.
  • Execute Commands Remotely – We can use the tower to execute any command to a host or group of hosts in our inventory.

There are also other features like Job Scheduling, Notification Integration, CLI, etc.

22. Explain how you will copy files recursively onto a target host?

There is a copy module with a recursive parameter, but synchronize is more efficient for large numbers of files. 

For example:


   Source: /first/absolute/path

   Destination: /second/absolute/path

   Delegate: “{{ inventory_hostname }}”

23. What is the best way to make Content Reusable/ Redistributable?

Ansible roles can be used to make content reusable and redistributable. Ansible roles are essentially a way to organize playbooks. If we need to execute 10 tasks on 5 systems, for example, writing them all in the playbook will cause confusion and blunders. Instead, we create 10 roles and refer to them in the playbook.

24. What are handlers?

Handlers are special tasks that will only run if the Task contains a “notify” directive. 

Tasks include:

  Install Nginx

    NGINX: pkg=nginx state=installed update_cache=true


     NGINX should be started


   Start nginx is the name

     Name: nginx state: started

After installing NGINX, we start the server with a `start nginx` handler.

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

Ansible provides a very simple ad-hoc command for this

‘mypassword’ -m debug -a “msg={{ ‘mypassword’ | password_hash(‘sha512’, ‘mysecretsalt’) }}”

We can also use the Passlib library of Python, for example

“From passlib.hash import sha512_crypt; import getpass; print(sha512_crypt.using(rounds=5000).hash(getpass.getpass()))”

On top of that, we should also avoid storing raw passwords in playbooks or host_vars. Instead, we should use integrated methods to generate a hash version of the password.

26. How do dot notation and array notation of variables are different?

The dot notation works fine except for a few special cases, for instance

  • Any variable containing a dot(. ), colon(:), starting or ending with an underscore, or any other public attribute.
  • There is a collision between the methods and attributes of Python dictionaries.
  • The array notation also allows for dynamic variable composition.

Advanced Ansible Interview Questions

27. How does Ansible synchronize module works?

A playbook can use Ansible synchronize, a module similar to sync on Linux machines. There are some features similar to rsync, such as archiving, compressing, deleting, etc, but there are also some limitations, such as

  • Both the source and target systems must have Rsync installed
  • You need to specify delegate_to to change the source from localhost to another port
  • As files are accessible by remote users, user permissions must be handled.
  • It is imperative that the full path of the destination host location is provided when using sudo, otherwise files are copied to the remote user’s home directory.
  • Linux rsync limitations related to hard links also apply here.
  • The -delay-updates option is used to prevent the broken state in the event of a connection failure

Synchronize modules are examples of

Host-remote tasks:

Sync from sync_folder


Synchronized folder /var/tmp: /var/tmp/

We are transferring files from the /var/tmp/sync_folder folder to the remote machine’s /var/tmp folder

28. How does the Ansible firewall module work?

Firewall rules are managed by Ansible firewall on host machines. It works just like Linux firewalled daemons for allowing/blocking access to services from the port. It is divided into two major concepts

  • Zones: This is the location where we can control which services are exposed to or to which the local network interface is connected.
  • Services are usually a series of port/protocol combinations (sockets) that your host might be listening on, which can then be placed in one or more zones

Here are a few examples of how to set up a firewall

Permit traffic in the default zone for HTTPS


   The service is available at HTTPS

   Yes, permanent



Name: do not permit traffic on port 8081/tcp in the default zone


   The port is 8081/tcp

   A permanent position: yes

   The current state is disabled

29. How is the Ansible set_fact module different from vars, vars_file, or include_var?

 A set_fact is used in Ansible to set new variables on a host-by-host basis, just like ansible facts are discovered by the setup module. In a playbook, these variables are available to subsequent plays. When using vars, vars_file, or include_var, we know the value beforehand, whereas when using set_fact, we can store the value after preparing it on the fly using certain tasks, such as filters or subparts of another variable. A fact cache can also be set over it.

Assignment to the set_fact variable is done by using key-pair values where the key is the variable name and the value is the assignment. Below is a simple example

The set_fact is:

Here’s one fact: value1



30. When is it unsafe to bulk-set task arguments from a variable?

All the arguments of the task can be dictionary-typed variables, which can be useful in some dynamic execution scenarios. In spite of this, Ansible issues a warning since it introduces a security risk.



Username: testuser


Passwords should always be updated

Tasks include:

“[[ usermod_args ]]”

The values passed to the variable usermod_args could be overwritten by some other malicious values in the host facts on a compromised target machine. In order to avoid this

  • Priority should be given to bulk variables over host facts.
  • To prevent fact values from colliding with variables, disable INJECT_FACTS_AS_VARS.

31. Explain Ansible register.

The output of a task execution is stored in an Ansible register. We can use this when we have different outputs from different remote hosts. As long as the register value is valid throughout the playbook execution, we can use set_fact to manipulate the data and provide input to other tasks as necessary.

All hosts:

Find all txt files in /home shell: “find /home -name *.txt” register: find_txt_files


Variable: find_txt_files

We are searching for all .txt files in the remote host’s home folder, capturing them in find_txt_files, and displaying the variable found.

32. How can we delegate tasks in Ansible?

In Ansible, task delegation is important because we may need to perform a task on one host with reference to other hosts. Using the delegate_to keyword, we can accomplish this. 

If we want to manage nodes in a load balancer pool, we can do the following:

Webservers: hosts

 Serial number: 5


 Tasks include:

– name: Remove machine from ELB pool

  /usr/bin/take_out_of_pool [[ inventory_hostname ]] Ansible.builtin.command

  You are delegated to:


Name: Actual steps go here



    Latest state


– add machine back to ELB pool

  The ansible.builtin.command is: /usr/bin/add_back_to_pool {{ inventory_hostname }} is the delegation address

Additionally, we define serial to control how many hosts can run at the same time. In addition to delegate_to, there is another shorthand syntax called local_action. 

Tasks include:

   – name: Remove the machine from the ELB pool

     Ansible.builtin.command /usr/bin/take_out_of_pool {{ inventory_hostname }}

However, there are a few exceptions, such as include, add_host, and debug tasks, that cannot be delegated.


Every developer or member of the DevOps team should know the basics of Ansible because it is a great tool for automating IT tasks. Furthermore, it’s very easy to set up, so we can get started right away. In addition to helping in interviews and understanding Ansible in-depth, these questions will cover the most important concepts related to Ansible.

Top 40 Basic Ansible Interview Questions


Top 40 Basic Ansible Interview Questions
Top 40 Basic Ansible Interview Questions
Scroll to Top