Top 30+ Ansible Interview Questions and Answers for 2023 - Interviewbit

Basic Ansible Interview Questions

1. What is CI/CD?

Ansible is a tool used for Continuous Integration / Continuous Delivery (CI/CD). CI/CD refers to a set of practices and methodologies used to streamline the software development lifecycle (SDLC) and automate the delivery of software to production. It helps teams deliver better and high-quality software faster by automating build, test, and deployment processes. Ansible assists with automating the deployment process, thereby streamlining the delivery of the software and helping to quickly detect and address any issues that arise.

Introduction to Configuration Management

Configuration Management refers to the process of managing changes and maintaining the consistency of the software product throughout its lifecycle. It involves identifying and controlling the functional and physical characteristics of software and hardware in order to prevent any unauthorized changes that could potentially impact the integrity of the system. Effective Configuration Management helps to ensure that the software product is accurate, complete, and dependable. In software development, it is a vital aspect for maintaining the integrity and reliability of the product.

How Ansible Works?

Ansible is a tool that automates IT tasks, such as application deployment, configuration management, and orchestration. It works by connecting to remote systems through SSH or WinRM, and then running modules to perform tasks on those systems.

Ansible uses a declarative language to describe the desired state of the systems, and it ensures that the systems are always in that state. It does this by comparing the current state of the systems to the desired state, and then making any necessary changes to bring the systems into alignment.

Ansible is designed for simplicity and ease of use. It has a very shallow learning curve, and it requires no custom agents or software to be installed on the target systems. This makes it a popular choice for automating IT tasks in organizations of all sizes.

Features of Ansible

Ansible is a powerful automation tool used for managing IT infrastructure. It has various features that make it stand out as a preferred choice over other configuration management tools:

- Agentless: Ansible does not require any agents to be installed on managed nodes, making it lightweight and easy to set up.
- Idempotent: Ansible ensures that the desired state of the infrastructure is achieved, regardless of the initial state. If a task is run multiple times, it will only make the necessary changes to bring the infrastructure to the desired state.
- YAML-based: Ansible uses YAML syntax, which is easy to read and write for both humans and machines.
- Extensible: Ansible can be extended with plugins or modules to support a wide range of use cases and technologies.
- Playbooks: Ansible allows users to write automation workflows in a declarative YAML format called playbooks, which are easy to understand and maintain.
- Scalable: Ansible can manage thousands of nodes, making it suitable for large-scale deployments.

Explanation of Infrastructure as Code

Infrastructure as Code (IaC) is a practice that emphasizes using code to manage and provision infrastructure. This process involves writing code that can automate the deployment, management, and scaling of infrastructure resources like servers, networks, and storage. With IaC, the entire infrastructure can be versioned, tested, and deployed just like any other code. This approach provides numerous benefits, including increased efficiency, consistency, and reproducibility of infrastructure deployments. Additionally, IaC makes it easier to manage large and complex infrastructure and allows for easy collaboration among team members.

What is Ansible Galaxy?

Ansible Galaxy is a platform that provides a centralized repository for finding, reusing, and sharing Ansible roles. Ansible roles are a way to organize and package up reusable Ansible code. With Ansible Galaxy, developers can easily find and share roles with other members of the Ansible community, making it simpler to automate infrastructure and manage configurations. Ansible Galaxy also offers a robust search feature that allows users to filter roles by tags, categories, and other criteria, making it easy to find the right roles for their needs.

Explanation of Ansible Modules

Ansible has a large collection of pre-built modules that can be used to automate various system tasks such as installing packages, managing users, and configuring network devices. These modules can be executed on remote systems using SSH and require minimal setup.

Ansible modules are executed in a push model fashion where the control machine sends the required module command to the remote host, the module is executed on the remote host, and the result is returned to the control machine. This allows for a high degree of flexibility and ease of use.

There are several types of modules in Ansible:

1. Command modules: These modules execute commands on the remote host and return the output.

2. File modules: These modules manage files and directories on the remote host.

3. Package modules: These modules manage packages and repositories on the remote host.

4. System modules: These modules manage system-wide configurations such as time zones and hostname.

5. Cloud modules: These modules manage cloud infrastructure such as AWS and Azure.

6. Network modules: These modules manage network devices such as routers and switches.

Ansible modules are written in a language called YAML and can be easily extended or customized to fit specific use cases. They are a fundamental building block in Ansible automation and make it easy to manage large-scale deployments across various systems and platforms.

Understanding YAML Files and Their Use in Ansible

YAML (short for YAML Ain't Markup Language) is a human-readable data serialization language that is commonly used for configuration files and Ansible playbooks. It uses indentation to define the structure of data and allows for comments to be added within the file.

In Ansible, YAML files are used to define the tasks to be executed on a target node. The structure of a YAML file in Ansible includes a list of tasks, which are defined by a name and a module. Modules are Ansible's way of executing specific actions such as file manipulation, package installation, or running commands on the target node.

Here's an example of a simple YAML file:

- name: Update packages
    update_cache: yes
    cache_valid_time: 3600

This YAML file executes the apt module (which is used to manage packages on Debian-based systems) with two specific arguments: update_cache and cache_valid_time.

To execute a YAML file in Ansible, use the "ansible-playbook" command followed by the name of the file.

YAML files are a key component of Ansible and mastering its syntax and structure is essential in creating effective and efficient Ansible playbooks.

Understanding Ansible Tasks

Ansible tasks are the fundamental unit of work in Ansible. They represent independent blocks of code that describe a specific action to be taken on a particular node. Each task consists of a set of instructions, also known as plays, that Ansible will execute in the order in which they are defined.

Tasks can be used to perform different types of operations, such as configuring software, deploying applications, modifying system settings, and managing files. They can include module calls, variable assignments, conditional statements, loops, and other programming constructs.

Ansible tasks are defined in playbooks, which are YAML files that specify the desired state of the target system. Playbooks are executed using the "ansible-playbook" command-line tool and can be customized to suit specific needs.

By breaking down larger automation tasks into smaller, discrete ones, Ansible tasks allow for better modularity, reusability, and maintainability of configuration code.

Using YAML Files in High-Level Programming Languages like Java or Python

YAML is a human-readable and simple data serialization language that is commonly used for configuration files. It is supported by most high-level programming languages, including Java and Python.

To use YAML files in Java, you need to add the SnakeYAML dependency to your Java project. You can do this by adding the following lines to your Gradle build file:

dependencies {
    implementation 'org.yaml:snakeyaml:1.29'

Once you have added the dependency, you can use the SnakeYAML library to parse YAML files as follows:

Yaml yaml = new Yaml();
InputStream inputStream = new FileInputStream(new File("config.yml"));
Map<String, Object> obj = yaml.load(inputStream);

In Python, YAML is supported natively through the PyYAML library. You can install PyYAML using pip:

pip install pyyaml

Once you have installed PyYAML, you can use it to parse YAML files as follows:

import yaml
with open("config.yml", "r") as stream:
        obj = yaml.safe_load(stream)
    except yaml.YAMLError as e:

Overall, YAML is a convenient and easy-to-use format for configuration files in high-level programming languages.

Intermediate Ansible Interview Questions

11. How to Set up a Jump Host to Access Servers Having No Direct Access?

When you want to access a server that doesn't have direct access, you can use a jump host (also known as a Bastion host) to establish the connection.

In order to set up a jump host using Ansible, you can follow these steps:

1. Set up the jump host by installing and configuring the `ssh` server. 2. Add the jump host details (IP address, username, and ssh key) to `~/.ssh/config` on your local machine. 3. Set up the target hosts by configuring `ssh` to proxy through the jump host using the `ProxyJump` configuration option. This can be done through Ansible using the `ssh_config` module. 4. Use Ansible to connect to the target hosts through the jump host by specifying the `ansible_ssh_common_args` variable in your inventory file. For example:

   target_host_1 ansible_host= ansible_user=user1 ansible_ssh_common_args='-o ProxyJump=jump_host'
   target_host_2 ansible_host= ansible_user=user2 ansible_ssh_common_args='-o ProxyJump=jump_host'

With these steps, you should be able to access the target hosts through the jump host using Ansible commands.

Automating Password Input in Playbook using Encrypted Files

In order to automate password input in playbook using encrypted files, you can make use of the ansible-vault command to encrypt the password file. Once the file is encrypted, you can simply add the encrypted file path in your playbook.

First, create the password file using any text editor and add the password in plain text. For example, create a file named "password.txt" with the password "mysecretpassword".

Next, encrypt the file using the ansible-vault command:

ansible-vault encrypt password.txt

This will prompt you to enter a password for encryption. Enter any password of your choice.

Once the file is encrypted, the contents will be replaced with encrypted text. You can verify this by opening the file.

Now, you can add the encrypted file path in your playbook. For example:

- name: Example Playbook
  hosts: web
  become: true
    - vars/password.yml
    - name: Install packages
      apt: name={{ item }} state=latest
        - nginx
        - php5-fpm
        - mysql-server

In the above example, "vars/password.yml" is the encrypted file path.

When you run the playbook, Ansible will prompt you to enter the password for decryption of the encrypted file. Once the password is entered, the playbook will continue to execute normally.

Understanding Callback Plugins in Ansible

Callback plugins in Ansible are responsible for handling events that occur during the execution of playbooks. They listen to these events and execute actions accordingly, providing output to the user. These plugins are written in Python and can be customized or extended to suit the user's needs.

Examples of events that can be captured by callback plugins include:

  • task execution start and end
  • playbook start and end
  • failure of tasks or hosts
  • inventory updates

The default callback plugin in Ansible is the stdout plugin, which simply prints output to the console. However, there are many other callback plugins available that provide additional functionality, such as sending output to a log file, sending notifications, or formatting output in a specific way.

To use a specific callback plugin, simply specify it in the ansible.cfg file or on the command line using the -c or --callback option, followed by the name of the plugin.

Ansible Inventory: Overview and Types

Ansible Inventory is a file containing information about the servers, virtual machines, or devices that Ansible should manage. Inventory can be static or dynamic and the hosts can be grouped conveniently into different categories based on their roles, functions, or locations. There are various ways to organize Inventory, including YAML, INI, or scripts that output JSON, among others. Regardless of the format, the Inventory file is a crucial component of any Ansible project and ensures that the right systems and services are being managed at all times.

What is Ansible Vault?

Ansible Vault is a tool within the Ansible Automation Platform that allows users to encrypt sensitive data such as passwords, API keys, and other confidential information. This encrypted data can then be safely stored in version control systems, shared with team members, or used in playbooks without compromising security. The Vault uses Advanced Encryption Standard (AES) for secure encryption and decryption of data.

Looping through a list of hosts in a group using a template

To loop through a list of hosts in a group using a template in Python, you can do the following:

{% for host in group_name %}
  do something with {{ host }}
{% endfor %}

Replace 'group_name' with the actual name of the group you want to loop through. Then, 'host' holds the value of each host in the group as the loop iterates through. You can replace 'do something with {{ host }}' with any actions you want to perform on each host.

Understanding Ad-hoc Commands in Ansible

An ad-hoc command is a one-liner command that allows you to perform tasks quickly without writing an entire playbook. It is a convenient way to execute a single task on a group of hosts. For example, you can use an ad-hoc command to check the uptime of all hosts in a specific inventory group.

Ad-hoc commands in Ansible are executed using the `ansible` command followed by the name of one or more target hosts or a group of hosts defined in your inventory file.

Here's an example of an ad-hoc command that checks the uptime of all the hosts in the "web_servers" group:

ansible web_servers -i inventory_file -m command -a "uptime"

In this command: - `web_servers` is the inventory group containing the target hosts - `-i inventory_file` specifies the path to the inventory file - `-m command` specifies the module to use (in this case, the `command` module) - `-a "uptime"` is the argument to the module, which in this case is the `uptime` command.

Ad-hoc commands can be very useful for performing one-off tasks, but for more complex configurations and commands, it's better to use playbooks.

Installing Nginx using an Ansible Playbook


- name: Install Nginx
  hosts: web_server
  become: true
    - name: Update apt cache
        update_cache: yes

    - name: Install Nginx
        name: nginx
        state: latest

To install Nginx using an Ansible playbook, we need to create a playbook file with the appropriate tasks. In the given code, we first specify the name of the playbook followed by the hosts on which it should run. Here, we have specified web_server as the host.

We then set the become directive to true to run the tasks with sudo permissions.

The first task is to update the apt cache to get the latest version of the Nginx package. The apt module is used here to update the cache.

The second task is to install the Nginx package using the apt module. We specify the name of the package as nginx and the state as latest to ensure that the latest version of the package is installed.

This playbook can be run using the ansible-playbook command followed by the name of the file. For example, if our playbook file is named nginx-install.yml, we can run it using the following command:

ansible-playbook nginx-install.yml

How to Access a Variable Name Programmatically in JavaScript

In JavaScript, you can access the value of a variable by simply using its name, but accessing the name itself programmatically can be a bit more tricky. One way to achieve this is by using the `Object.keys()` method, which returns an array of all property names of an object, including variables.

Here's an example:

let myVar = "Hello World";
let variableName;

for (let key in window) {
  if (window[key] === myVar) {
    variableName = key;

console.log(variableName); // "myVar"

In this code snippet, we first declare a variable `myVar` and an empty variable `variableName`. We then loop through all properties of the `window` object (which contains all global variables) and check if the value of each property matches our `myVar` variable. If so, we assign the property name (i.e. the variable name) to `variableName` and exit the loop.

Finally, we log the `variableName` to the console, which in this case would be `"myVar"`.

Differences between Ansible and Puppet

Ansible and Puppet are both popular configuration management tools used to automate IT infrastructure. However, there are some key differences between the two:

# Ansible uses YAML syntax while Puppet uses its own domain-specific language

# Ansible is agentless, meaning it doesn't require any software to be installed on client machines, while Puppet requires an agent to be installed

# Ansible is easier to learn and use compared to Puppet which has a steeper learning curve

# Ansible is ideal for orchestrating tasks across multiple servers, while Puppet is better suited for managing individual machines or smaller clusters

Ultimately, the choice between Ansible and Puppet will depend on the specific needs and requirements of the organization or project at hand.

An Introduction to Ansible Tower and Its Key Features

Ansible Tower is a web-based user interface and enterprise framework that is used for managing, automating, and deploying Ansible. Ansible Tower can scale to manage complex deployments across hundreds of servers or as simple as a single instance. It comes with several key features that make it useful for IT automation, including:

1. Role-Based Access Control: Ansible Tower offers granular access levels that allow users or teams to work on projects while keeping data safely segmented.

2. Automation: Ansible Tower can automate repetitive tasks to create workflows, reducing the need for manual intervention and thus, reducing the possibility of human errors.

3. Scheduling: Ansible Tower can keep infrastructure stable by automating maintenance tasks and scheduling them for a particular time or event.

4. REST API: Ansible Tower comes with a RESTful API that allows for easy integration of Ansible Tower with other services, tools, and applications.

5. Inventory Management: Ansible Tower's inventory management feature can keep track of systems and applications being managed and can even manage multiple inventories at the same time.

In summary, Ansible Tower simplifies Ansible deployment, provides workflow automation, role-based access control, and inventory management functionality, resulting in more reliable and effective IT operations and resource management.

How to Copy Files Recursively to a Target Host?

To copy files recursively to a target host, you can use the `scp` command. The `scp` command allows copying files securely between hosts using the SSH protocol.

Here's the basic syntax:


scp -r /path/to/source user@target:/path/to/destination


- `-r` option specifies that the command should be executed recursively. - `/path/to/source` is the path to the source directory on the local host. - `user` is the username of the user on the target host. - `target` is the hostname or IP address of the target host. - `/path/to/destination` is the path to the destination directory on the target host.


Suppose you want to copy the directory `/home/user/documents` on your local machine to the directory `/var/www/` on the target host with IP address ``, and the username `john`. You can execute the following command:


scp -r /home/user/documents [email protected]:/var/www/

This will copy all files and subdirectories in the `/home/user/documents` directory to `/var/www/` on the target host.

Note: You'll need to have SSH access to the target host and have appropriate permissions to copy files to the destination directory.

Best Practices for Making Content Reusable and Redistributable

Creating reusable and redistributable content is important for maximizing its reach and ensuring that it can be easily updated and repurposed. Here are some best practices to consider:

1. Plan ahead: When creating content, keep in mind that you may want to reuse or distribute it in the future. This means designing content with a clear structure and consistent formatting that can be easily adapted to different platforms and mediums.

2. Use universal formats: Opt for formats that are widely used and accepted, such as PDFs, JPEGs, and MP4s. This will make it easier for others to access and utilize your content.

3. Properly attribute: If you are using content created by others, make sure to properly attribute them and seek permission for reuse if necessary. This can help you avoid any legal issues down the line.

4. Utilize Creative Commons: Consider using Creative Commons licenses, which allow others to reuse and remix your content under certain conditions. This can help increase your content's reach and exposure.

5. Make it user-friendly: Ensure that your content is easy to navigate and understand, with clear headings, subheadings, and bullet points. This will make it easier for others to consume and repurpose your content.

By following these best practices, you can make your content more reusable and redistributable, which can increase its reach and impact.

Handlers in Programming

In programming, a handler refers to a block of code that is executed when a particular event occurs in an application or system. Handlers are commonly used in event-driven programming and are responsible for handling events such as mouse clicks, keypresses, and network requests. They can also be used to handle errors and exceptions that occur during program execution. Handlers are essential for creating robust and reactive applications that respond to external stimuli in real-time.

Generating Encrypted Passwords for User Module

To generate encrypted passwords for a user module, you can use a hashing algorithm. The MD5 algorithm, for example, is commonly used for this purpose. Here's an example code snippet in Python:

import hashlib

def generate_password(password):
    # Convert the password string to bytes
    password_bytes = password.encode('utf-8')

    # Generate the hash using MD5 algorithm
    hash_obj = hashlib.md5(password_bytes)

    # Get the hexadecimal representation of the hash
    hex_digest = hash_obj.hexdigest()

    # Return the encrypted password as a string
    return hex_digest

In this code, we first convert the password string to bytes, then generate the hash using the MD5 algorithm. We then convert the hash to a hexadecimal representation and return it as a string.

To use this function in your user module, you can call it whenever you need to generate a new password for a user. For example:

# Generate an encrypted password for a new user
password = generate_password('mypassword')

Keep in mind that MD5 is not the most secure hashing algorithm, and it's recommended to use more secure algorithms like SHA-256 or SHA-512 instead. Additionally, it's a best practice to also salt the password for added security.

Differences between Dot Notation and Array Notation in Variables

In JavaScript, dot notation and array notation are two ways to access or set the value of an object's property.

Dot notation uses a dot (.) followed by the property name to access or set the property value, like this:


Array notation uses brackets [] with the property name or index number inside to access or set the property value, like this:


Both notations can be used interchangeably in most cases, but there are some differences: - Dot notation can only be used with valid identifier names or property names that don't contain special characters like spaces or hyphens. - Array notation can be used with any string or number that can be evaluated as a property name or index number. - Dot notation can be faster to write and easier to read, especially with short or simple property names. - Array notation can be more flexible in dynamic situations, such as looping through an array or accessing properties with variable names.

Advanced Ansible Interview Questions

27. Can you explain how the synchronize module works in Ansible?

The synchronize module

in Ansible is used for efficiently copying files from the local server to a remote server. It uses the rsync algorithm to transfer files, which efficiently synchronizes only the changes between the source and destination files. This reduces network bandwidth usage and speeds up the file transfer process.

The syntax for using the synchronize module is as follows:

- name: Sync files to remote server
    src: /path/to/source/files
    dest: /path/to/destination/files
    mode: push

The mode parameter can be either "push" (default) or "pull". If "push" is used, files will be synced from the local server to the remote server. If "pull" is used, files will be synced from the remote server to the local server.

In addition, the synchronize module has several other parameters, such as archive, compress, delete, and checksum. These parameters can be used to customize the behavior of the module according to the requirements of the task.

Understanding the Functionality of Ansible FirewallD Module

The Ansible FirewallD module facilitates the configuration of FirewallD on remote hosts. FirewallD is a dynamic firewall management tool used to manage host-level firewalls. This module allows users to manage the rules of the firewalls and define the access policies. In other words, this module provides an automated way to manage the firewall configuration of the hosts. By using this module, users can easily modify the firewall rules without needing to log in to the individual hosts and manually configuring them.

Understanding the Differences Between Ansible's set_fact Module and vars, vars_file, or include_var

In Ansible, variables can be defined and accessed in various ways. Among them are the `set_fact` module, `vars`, `vars_file`, and `include_var`. These options have their respective differences and use cases.

- **set_fact module**: This module is used to dynamically set variables in a playbook. It allows you to set task-specific variables by retrieving values from other tasks or system sources. These variables will be available for later use in the playbook.

- **vars**: This is a static variable defined in a playbook. It is usually set at the beginning of the playbook and can be used across all tasks in the playbook.

- **vars_file**: This option allows you to define variables in a separate file and include them in your playbook. It is useful when you have a large number of variables or want to maintain them separately from your playbook.

- **include_var**: This option is similar to `vars_file` However, we will use this when we need to include variables in another playbook as an external reference.

It is crucial to understand the differences between these options as they have varied use cases. By choosing the appropriate option, you can optimize your playbook for better modularity, maintainability, and scalability.

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

Bulk-setting task arguments from a variable is unsafe when the contents of the variable can be modified by another program or user during the execution of the workflow. This can result in unintended changes to the arguments of the tasks in the workflow, leading to unpredictable behavior and errors. To ensure the reliability and consistency of the workflow, it is recommended to use immutable variables or make a copy of the variable before bulk-setting task arguments.

Explanation of Ansible Register

In Ansible, the register module allows you to capture the output and the return code of a command or a task. You can use this information in subsequent tasks or modules within the playbook.

Here's an example of using the register module:

- name: Execute a command and register the output
  shell: ls /path/to/files/
  register: output

- name: Print the registered output
  debug: var=output.stdout_lines

In the above example, the shell module is used to run the `ls` command and its output is assigned to the `output` variable using the register module. The `debug` module is then used to print the value of `output.stdout_lines`.

Overall, the register module is a useful feature in Ansible that allows you to capture the output and return code of a command or task and pass it along to subsequent tasks or modules within the playbook.

Delegating Tasks in Ansible

In Ansible, delegation refers to the ability to handover the execution of a particular task or play to another host. There are two types of delegation in Ansible:

1. Delegation to Another Host 2. Local Delegation

Delegation to Another Host is useful when a task needs to be executed on a particular host, but the control machine is not able to execute that task due to dependencies or restrictions. This delegation can be done using the `delegate_to` keyword.

Local Delegation is useful when a task needs to be executed on the control machine itself, but the task requires elevated privileges. This delegation can be done using the `local_action` keyword.

Example Code for Delegation:

- name: Execute command on delegated host
  command: echo "Executed on target machine."
  delegate_to: "{{ inventory_hostname }}"
  run_once: true

- name: Execute command on control machine with sudo
  command: echo "Executed on control machine with elevated privileges."
  become: true
  become_method: sudo
  local_action: true

In the above code, the first task will be delegated to the target host, while the second task will be executed on the control machine itself with elevated privileges.


This section presents the conclusion that can be drawn from the study or research conducted.

Technical Interview Guides

Here are guides for technical interviews, categorized from introductory to advanced levels.

View All

Best MCQ

As part of their written examination, numerous tech companies necessitate candidates to complete multiple-choice questions (MCQs) assessing their technical aptitude.

View MCQ's
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.