Open In App

Ansible Interview Questions

Last Updated : 11 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Ansible is a configuration management tool and an open-source product from Redhat company. Before moving into the details of Ansible, let’s explore the evolution of the Software Development Life Cycle (SDLC). In the past, IT and Linux administrators manually updated software with the latest versions and configured updates, causing significant delays in bringing new ideas or features to the public. This delay affected server performance and made business growth difficult. The demand for an agile nature led to the rapid rise of the DevOps culture, aiming to accelerate the time-to-market for new services or features and stay ahead of competitors.

In this article, we have curated a list of 50 Ansible interview questions and answers. These questions span various aspects of Ansible, from fundamental concepts to advanced topics like playbook development, role creation, and Ansible Tower integration. Whether you are a beginner who just starting with Ansible or you are an experienced professional (5 or 10 years of experience) gearing up for an upcoming interview, this guide provides a valuable resource to enhance your understanding and confidently tackle Ansible-related questions in your upcoming Technical interview.

Ansible Architecture

Initially, automation was done through scripting to replace the manual mode of workflow. However, scripting brought out challenges such as the requirement of writing different scripts on various platforms. For example, a script written for Linux wouldn’t support Windows, and separate scripts had to be provided for different Linux distributions like Red Hat, Ubuntu, Fedora, etc. The imperative nature of scripting involved specifying detailed guidelines for performing the actions making it cumbersome.

To address these challenges, configuration management tools like Ansible, Puppet, and Chef have emerged. Among these such as Ansible vs Puppet, and Ansible vs Chef, Ansible gained wide popularity due to its declarative nature and its use of a push mechanism with an agentless approach. Because of the declarative nature of Ansible, Users only need to specify where to act and what action to perform through its intelligence ansible determines how to execute the action using its inbuilt callback plugins for fetching information. This approach enhances efficiency and simplifies the management of different infrastructure environments. Refer to this Terraform vs Ansible to understand the difference between configuration and Infrastructure management. The below figure illustrates the Ansible Architecture.

Table of Content

Basic Ansible Interview Questions

1. What Is Ansible ?

Ansible is an open-source automation tool developed by Redhat that is meant for simplifying the configuration management, application deployment, and automation of tasks. It allows us in automating repetitive tasks, ensuring consistency and efficiency in managing servers and networks using SSH protocol for make communication with the network Agentlessly.

2. What Is Inventory ?

In Ansible, an inventory is a file with specifying the information of hosts that going to be managed. It contains information such as hostnames, IP addresses, and groups of organization. The inventory can be either static or dynamic, and it may be with inclusion of variables by specific host details. It’s a key component for targeting and managing nodes infrastructure in Ansible. A sample inventory file is given below.

[web]
webserver1 ansible_host=192.168.1.11
webserver2 ansible_host=192.168.1.12

[db]
dbserver1 ansible_host=192.168.1.21

3. Explain The Concept Of Configuration Management And Its Importance In IT Operations.

Configuration management is the process of systematically handling changes to a system’s configuration by ensure consistency, reliability of the IT environment of managed nodes in a network. For better understanding refer how Ansible configure remote nodes article once.

4. What Are The Features Of Ansible ?

Ansible comes with several features that make it powerful and popular automation tool. A few of the key features are listed here:

  • Agentless: Ansible does not require any agent installation on the managed nodes. It communicates with the nodes in the network using SSH simplifying deployment and reduces complexity.
  • Declarative Language: Ansible uses a simple human-readable YAML syntax to specify the desired state of the system making it easy to write and understand automation scripts.
  • Idempotent Operations: Ansible ensures for the achievement of desired state i.e., running a playbook multiple times has the same effect as running it once. This prevents from unintended changes ensuring consistency.
  • Playbooks: Automation scripts in Ansible are known as playbooks. Playbooks are written in YAML by defining a set of tasks that to be executed on remotely specifying in the hosts section.
  • Modules: Modules are used in ansible to perform specific tasks on managed nodes.They are 2 types of modules as built-in modules ( that are already created and comes with ansible ) and custom modules that are created by users.
  • Inventory Management: Ansible uses an inventory file to specify the hosts information such as IP address or domainname, user details etc.. on which the automation tasks have to be executed. The inventory file can be either static or dynamic include host groups.

5. Describe Infrastructure As Code (IaC) And How Ansible Aligns With This Concept.

Infrastructure as Code (IaC) is the way of process used for managing and provisioning the infrastructure using code instead of manual workflow process. Ansible follows this approach allowing the users to describe and manage infrastructure in a code-like manner.

6. Explain Ansible Galaxy, modules, And Plugins In The Context Of Ansible Automation.

Ansible Galaxy is a platform providing the features of sharing and downloading Ansible roles. Modules are task executional units, and plugins helps in enhancing Ansible’s functionality by extending its capabilities.

7. What Are Ansible Tasks, And How Do They Contribute To The Automation Process?

Ansible tasks are individual work units within a playbook coming with defined actions that to be performed on remote hosts, contributing to the overall automation process.

8. What Makes Ansible Stand Out From Other Configuration Management Tools?

Ansible’s agentless architecture and its simplicity in use (YAML syntax), and ease of setup contribute to its standout features among other Configuration Management tools.

9.Briefly Explain Ansible’s Architecture Through Outlining Its Different Components.

The control node communicates with managed nodes through SSH protocol executing tasks defined in playbooks. Ansible consists of a control node, managed nodes, inventory, modules, and plugins.

10. What Is The Foundational Programming Language Of Ansible?

Ansible is built on top of Python, enhancing its simplicity for clear playbooks and versatility in creating robust modules. Python’s wide range of adoption provided good community support, making Ansible an effective and flexible automation tool.

11. What are handlers in Ansible, and how are they used in playbooks?

Handlers in Ansible are tasks that are triggered by other tasks, usually used to respond for the changes that require start , stop , reload or restart the service actions. They are defined in the playbook and executed as per need.

12. Explain The Concept Of Ansible Roles And Their Significance In Playbook Organization.

Ansible roles are a way of organizing package related tasks, files, and variables providing a structured approach for playbook organization for effecient reusability.

13. How Do You Set Up a Basic Ansible Playbook to Install a Package On a Group Of Servers?

To set up a basic Ansible playbook for installing a package on a group of servers, you should start firstly by creating a YAML file, typically name something like install_package.yml. Within this file, specify the hosts you want to target, specify the tasks, and include the package installation. Here’s a simplified example:

Here I used the apt module to install the packages in ubuntu os , try on using respective package manager module with respective to the OS.

- name: Install Package Playbook
  hosts: your_server_group
  become: true  # This allows running tasks with elevated privileges (sudo)
  tasks:
  - Install the desired package
     apt:
        name: your_package_name 
        state: present  # You can use 'latest' to ensure the latest version


14. What Command Will You Use To Run An Ansible Playbook With a Specific Inventory File?

I would use the `ansible-playbook` command by specifying the playbook file and the inventory file with the `-i` option. The command will looks as follows:

ansible-playbook -i /path/to/your/inventory/file   myplaybook.yml

Replace “/path/to/your/inventory/file” with the actual path to your inventory file and “myplaybook.yml” with your Ansible playbook YAML file name. In this command the inventory file specified using the -i option.

15. Can You Provide An Example Of Using Ansible To Check The Status Of a Service On Multiple Servers?

For checking the status of a service on multiple servers using Ansible, you can create a playbook with tasks on using Ansible’s service module. A simple example is listed here:

- name: Check Service Status
  hosts: your_server_group
  become: true  # This allows running tasks with elevated privileges (sudo)

  tasks:
    - name: Check status of the 'your_service_name' service
       service_facts:
         name: your_service_name  # Replace with the actual service name

    - name: Display the service status
       debug:
         var: ansible_facts.services['your_service_name'].state

Replace ‘your_server_group’ with the appropriate group name of servers from your inventory and ‘your_service_name’ with the actual service name you want to check. This playbook uses Ansible’s service_facts module to gather facts/information about the specified service and then it displays its status using the debug module. To run this playbook run the following command on replacing with your apropriative inventory and playbook file name.

ansible-playbook -i /path/to/your/inventory/file your_playbook.yml

Intermediate Ansible Interview Questions

16. How Do You Set Up a Jump Host In Ansible To Access Servers Without Direct Access?

A jump host or proxy host an intermediary server that is used to access other servers in a network that are not directly not reachable from the ansible control machine. It acts as a gateway for providing secure access to target servers especially in environments with restricted network access.

Setting up a jump host in Ansible involves 2 ways either through configuring Proxy Jump option in the SSH configuration or using the ansible_ssh_common_args variable in the inventory file. Here’s a brief guide on how to set up a jump host:

Method : Using the ProxyJump Option

i. Edit Your SSH Config File:

Open or create your SSH config file on the Ansible control machine:

nano ~/.ssh/config

ii. Add Jump Host Configuration:

Specify the jump host details in the SSH config file

Host   jump_host
    HostName   jump_host_ip
    User   jump_host_user
    IdentityFile   /path/to/your/private/key
#Replace jump_host, jump_host_ip, jump_host_user, and 
#/path/to/your/private/key with your specific jump host information.


iii. On using Jump Host in Ansible Playbooks:

In your Ansible playbook, specify the jump host using the ansible_ssh_common_args variable:

- name: Your Playbook
  hosts: your_target_hosts
  vars:
    ansible_ssh_common_args: '-o ProxyJump=jump_host'
  tasks:
    # Your tasks here

17. Can You Automate Password Input In An Ansible Playbook Using Encrypted Files?

Yes, Ansible helps in allowing you to automate password input in playbooks using encrypted files, specifically using Ansible Vault. Ansible Vault provides a secured way for encrypting sensitive data such as passwords, so that they can be stored safely for usage in your playbooks.

18. What Is The Role Of Callback Plugins In Ansible, And How Can They Be Used?

Callback plugins in Ansible play a vital role in customizing output and behavior of ansible. They are mostly used for logging, notifications, or any post-playbook actions, allowing for impressive Ansible functionality.

19. Explain Ansible Inventory And Discuss Its Various Types.

Ansible Inventory is a list of managed nodes. It can be static that is manually defined or dynamic that is generated by scripts. Dynamic inventories will fetch information from external sources like cloud providers.

20. Define Ansible Vault And Its Significance in Playbook Security.

Ansible Vault is a tool for encrypting sensitive data in Ansible playbooks, providing secure storage through usage of secrets such as passwords or API keys.

21. How Can You Implement Looping Over a List Of Hosts In a Group In Ansible Playbooks?

In Ansible playbooks, loop over a list of hosts in a group is performed by using the `with_items` or `loop` keyword directly in tasks. This allows you to iterate through the list of hosts and perform actions on each member of the group. The Jinja2 templating engine is then used within these tasks for providing the dynamic content based on playbook variables.

22. What Is The Ad-hoc Command In Ansible, And When Is It Typically Used?

In Ansible, an ad-hoc command is a fast, one liner task that you perform directly from the command line. This command helps for quick fixes or checks on remote systems.

For example, to check free disk space on a group of servers ( lets the name be group1 ) , you can use the ad-hoc command:

ansible group1  -m shell -a 'df -h'

23. Demonstrate The Installation Of Nginx using An Ansible Playbook.

For the installation of Nginx using Ansible playbook, Firstly create a playbook with tasks to update the package cache, install Nginx, and start the service. Then run the playbook with `ansible-playbook` command, specifying your inventory file and playbook name for a streamline installation process on targeted hosts. Here the playbook for this installation of Nginx is provided for Ubuntu/debian target nodes.

- name: Install Nginx
   hosts: web_servers
   become: true  # To execute tasks with sudo privileges
   tasks:
   - name: Update package cache
      apt:
        update_cache: yes  # For Ubuntu/Debian systems
   - name: Install Nginx
      apt:
        name: nginx
        state: present
   - name: Start Nginx service
      service:
        name: nginx
        state: started
        enabled: yes  # Ensures Nginx starts on boot

24. How Can You Programmatically Access A Variable Name Within An Ansible Playbook?

To access a variable name programmatically within an Ansible playbook, setup the `set_fact` module with a task like:

- name: Extract variable name
   set_fact:
    var_name: "{{ my_variable | dict2items | selectattr('value', 'eq', my_value) | map(attribute='key') | first }}"

This task sets `var_name` based on the variable name corresponding to the specified value (`my_value`). Try on adjusting `my_variable` and `my_value` accordingly.

25. Highlight The Key Differences Between Ansible And Puppet In Terms Of Architecture And Approach.

The Ansible is agentless automation tool uses YAML syntax for wrting of scripts following a push based model whereas Puppet is agent-based automation tool , uses its own DSL ( Domain Specific Language ) works on following a pull-based model.

26. What Is Ansible Tower, And What Features Does It Provide For Managing Ansible Workflows And Playbooks?

Ansible Tower is a web-based User Interface that improves Ansible’s capabilities. It comes up with providing the features such as role-based access control, job scheduling, and a centralized dashboard for efficient management and monitoring of playbooks.

27. Explain The Process Of Generating Encrypted Passwords For a User Module In Ansible.

By using Ansible-vault we are generating encrypted passwords for a user module in Ansible.

Example:

ansible-vault encrypt_string --vault-id @prompt --name 'ansible_become_pass' 'mypassword'

This command will prompt for a vault password interactively and encrypts the string ‘mypassword’ with the specified variable name ‘ansible_become_pass’.

28. Generate An Encrypted Password For a User module Using The `password_hash` Filter.

To generate an encrypted password for a user module in Ansible using the `password_hash` filter, use the following command:

ansible all -i inventory -m debug -a "msg={{ 'your_password' | password_hash('sha512', 'my_salt') }}" --vault-id @prompt




Try on replacing ‘your_password’ with the actual password and ‘my_salt’ with your chosen salt value. This command will prompt for a vault password and outputs the encrypted password suitable for using in an Ansible playbook.

29. Differentiate Between Dot Notation And Array Notation When Working With Variables In Ansible.

Dot notation is useful for accessing variables directly with provides cleaner readability (e.g., `{{ variable.key }}`), while array notation is used for dynamic variable names when dealing with special characters and spaces (e.g., `{{ variable[item] }}`).

30. In Ansible, How Can Callback Plugins Be Configured To Modify The Default Behavior, And What Role Do They Play In Optimizing Automation Workflows?

Callback plugins in Ansible are configured through the ansible.cfg file or command-line options for modifying the default behavior. They play a crucial role in optimizing automation workflows by enhancing personalized adjustments to logging, notifications, and result processing during the period of playbook execution.

Advanced Ansible Interview Questions

31. How Does The Ansible Synchronize Module Work?

The synchronize module of Ansible is used for efficiently copying files between the local and remote systems. It ensures that only the changes between the source and destination are transferred, optimizing the file synchronization process.

32. How Does The Ansible firewalld Module Work?

The firewalld module in Ansible is used for design and management of firewall rules on Linux systems on using firewalld daemon. It allows in addition or removal of rules and services providing a flexible way of controlling the configuration of firewall.

33. How Is The Ansible set_fact Module Different From vars, vars_file, Or include_var?

While vars, vars_file, or include_var are used for static variable assignments, the set_fact module in Ansible dynamically sets variables during playbook execution. This dynamic nature provides flexibility by allowing the creation of variables based on the playbook’s state.

34. How Can We Delegate tasks In Ansible?

Delegating tasks in Ansible involves using the `delegate_to` parameter within a task. This allows specific tasks to be executed on a different host than the one defined in the play. It’s useful for scenarios where certain tasks need to run on a designated host.

35. What Is Ansible Registry?

Ansible registry is a mechanism to store variables persistently, enabling data to be passed between different parts of a playbook or even between plays. It provides a way to share data without the need for complex variable passing, enhancing the playbook’s modularity.

36. What Features Does The Ansible Tower Provide?

Ansible Tower offers a web-based user interface with providing functionalites such as role-based access control, job scheduling, and a centralized dashboard for visualization of playbooks run. It provides an enterprise-level solution for monitoring and management of Ansible workflows.

37. How Is Ansible Used In a Continuous Delivery Pipeline? Explain.

Ansible plays role in integration of Continuous Delivery pipeline on automating various stages including testing, deployment, and provisioning of infrastructure. Playbooks can also be used for triggering at different points in the pipeline for ensuring consistency and efficiency in the delivery process.

38. How Can You Create a LAMP stack And Deploy a Webpage By Using Ansible?

In the creation of a LAMP stack and deploy a webpage, Ansible playbooks are used for the installation and configurations of softwares such as Apache, MySQL, PHP and deploy their webpage files. Each component will be configured with assignment of specific tasks, resulting in a fully functional LAMP stack.

39. How Can You Speed Up The Management Process Inside EC2?

Management inside EC2 can be accelerated by utilizing dynamic EC2 inventory scripts. These scripts automatically fetch information about EC2 instances, allowing for dynamic and efficient management of hosts in an Ansible environment.

40. Is It Possible To Increase The Ansible Reboot Module Timeout?

Yes, the Ansible reboot module timeout can be adjusted using the `reboot_timeout` parameter. This parameter allows users to specify a longer timeout if hosts require more time to complete the reboot process.

Ansible Scenario-Based Interview Questions

41. Can We Manage Windows Nano Server Using Ansible?

Yes, Ansible supports managing Windows Nano Server using the WinRM connection plugin. This allows Ansible to communicate with Windows hosts, enabling automation in Windows environments.

42. How Can You Speed Up Management Inside EC2?

Management inside EC2 can be accelerated by leveraging dynamic EC2 inventory scripts. These scripts automatically fetch information about EC2 instances, ensuring dynamic and efficient management of hosts in an Ansible environment.

43. Is It Possible To Increase The Ansible reboot Module Timeout To More Than 600 Seconds?

Yes, On adjusting the `reboot_timeout` parameter , it is possible to increase the Ansible reboot module timeout in the playbook. This parameter allows users to set a longer timeout if hosts require more time to complete the reboot process.

44. Explain How You Will Copy Files Recursively Onto a Target Host.

On using the `ansible.builtin.copy` module with the `recurse` parameter setting to true , you copy the files recursively onto the target host. It helps in ensuring the copy operation with inclusion of all files and subdirectories.

45. How Can You Access a List Of Ansible Variables?

A list of Ansible variables can be accessable within playbooks on using Jinja2 templating syntax. For instance, you can access a variable named `my_ansible_variable` as ` {{ my_ansible_variable }}` inside the playbook.

46. What Is The Difference Between a Play And a Playbook?

A Play is a set of tasks applied to a specific specified group of hosts where as Playbook is set of Plays. Plays are the individual units within a playbook that define what tasks should be executed on a specific set of hosts.

47. Can You Build Your Own Modules With Ansible?

Yes, On using Python programing ,Ansible helps in allowing users to create their own custom modules. This provides flexibility in allowing you to extend the Ansible’s functionality by writing modules tailored to specific use cases.

48. Explain Module Utilities In Ansible.

Module Utilities in Ansible are helper functions and libraries provided by Ansible for use within custom modules. They assist in common tasks such as parameter validation, result reporting, and handling complex data structures.

49. How Would You handle The Scenario Where a Playbook Task Fails, And You Need To Proceed With The Next Task?

To handle the failures of tasks and proceed for the next task, you can use the `ignore_errors` parameter in the task definition. This helps in ensuring the Ansible continuity with the playbook execution even if a particular task get fails.

50. In a Scenario Where You Need To Install Different Packages Based On The Target System’s Operating System, How Would You Approach This Using Ansible?

You can use the conditional statements in Ansible playbooks for checking the target system’s operating system and installing different packages on it accordingly. For example, on using `ansible.builtin.when` condition we can install packages based on OS types.

hosts: group_name
- name: Install packages based on OS type
   hosts: your_target_hosts
   become: true
- tasks:
   - name: Install packages for Debian-based systems (e.g., Ubuntu)
      apt:
        name: "{{ item }}"
        state: present
      loop:
       - package1_for_debian
       - package2_for_debian
      when: "ansible_distribution == 'Debian' or ansible_distribution == 'Ubuntu'"
   - name: Install packages for Red Hat-based systems (e.g., CentOS)
      yum:
        name: "{{ item }}"
        state: present
      loop:
      - package1_for_redhat
      - package2_for_redhat
      when: "ansible_distribution == 'RedHat' or ansible_distribution == 'CentOS'"
   - name: Install common packages for all systems
      package:
        name: "{{ item }}"
        state: present
      loop:
      - common_package1
      - common_package2

Conclusion

In this article, we have gone through covering most of the Ansible Interview Questions. We discussed the interview questions by classifying them into sections based on the complexity level and depth of Ansible concepts. Beginning from the fundamentals and diving into Intermediate-level, Advanced, and Scenario based Concepts, to keep your understanding with the flow while moving to the complexity level. In the field of DevOps, The role of the Ansible Automation tool is significant in configuring multiple nodes effectively through remote mode. Ansible brought Agentless configuration with a push mechanism bringing Agility with quicker software updates, Application configurations, and file modifications in the Target Environments (Testing or Production Environments ). It Finally made its contribution making the Software Development Life Cycle with Effective workflow with Automation.

Once you get a thorough understanding of Ansible with the preparation of these Interview Questions, you can move forward with confidence to expose insights into learning with effective DevOps practices. This article is enough for your Ansible in-depth preparation for giving Interviews on the Ansible tool.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads