Software Training Institute in Chennai with 100% Placements – SLA Institute

Easy way to IT Job

Share on your Social Media

Top 40 Ansible Interview Questions and Answers

Published On: December 16, 2024

With the increasing demand for Ansible, businesses are actively looking for experts who understand this potent tool. Because of this, we have put up a list of the top 40 Ansible interview questions and answers, covering everything from fundamentals to more complex subjects. Learn more with our Ansible course syllabus

Ansible Interview Questions for Freshers

1. What is Ansible?

An open-source tool for IT automation called Ansible assists with provisioning, application deployment, configuration management, orchestration, enhancing compliance and security, automating everyday chores, and patching systems. 

2. Describe the operations of Ansible.

Ansible employs a language that is readable by humans and is written in Python. 

It operates by:

  • Getting in touch with nodes (or hosts).
  • Launching modules, which are little programs.
  • Putting these modules into practice.
  • When the modules are complete, remove them.

3. What are the key features of Ansible for developers?

Ansible is made to be user-friendly and straightforward. There aren’t many moving parts, and security and dependability are key features.

  • For developers, system administrators, and IT specialists, Ansible is a useful tool.
  • Ansible is not the same as Terraform, which is used for setting up infrastructure. Automating IT processes like provisioning and deployment is the main goal of Ansible.  

4. Define CI/CD and how they relate to Ansible.

The combined techniques of continuous integration (CI) and continuous delivery (CD), or less frequently, continuous deployment, are known as CI/CD or CICD in software engineering. 

Each engineer in the CI loads a standard set combination, typically once a day, creating many daily combinations. The best CI/CD process tool is Ansible, which offers a reliable infrastructure for supplying a specific location and submitting a request to it.

5. How can you use encrypted files to automatically enter the password in the playbook?

You can use encrypted files, such as Ansible Vault, to automate the password entry in a playbook. 

  • You can use the include_vars module in your playbook to include the encrypted file and decode the password after encrypting it and storing it in a vault-encrypted file. 
  • Sensitive information can be safely stored and used in your playbooks without being exposed to plain text by using.

6. What does Ansible’s Callback_plugin mean?

In the Ansible environment, a callback is a piece of code that calls a specific event using the get function while permitting notifications. This is another kind of developer-related feature that makes it possible for low-level extensions to load without any issues from a number of different locations.

7. Explain the Ansible Playbook and Roles.

Although they are both tools for planning and carrying out automation tasks, Ansible Playbooks and Ansible Roles have distinct functions. 

Ansible Playbook

A playbook is a set of instructions that must be followed in a certain order for a specified inventory. Playbooks are useful for implementing sophisticated applications and can be applied to:

  • Set up the management.
  • Install on several machines.
  • Start activities either synchronously or asynchronously.  

Ansible Roles

A role is a collection of files and actions that set up a host for a certain role. Roles can be reused, altered, and customized and are not dependent on one another. Roles are helpful for:

  • Code organization and packaging.
  • Splitting a playbook up into several files.
  • Making the process of writing intricate playbooks simpler.

Explore our DevOps course syllabus to learn the fundamentals.

8. What is the purpose of Ansible?

Ansible is a platform for IT automation that may be used for many different activities, such as:

  • Configuration management lowers the possibility of unforeseen modifications, automates deployment, and aids in the administration of IT infrastructure.
  • Application deployment: Simplifies and deploys applications by using pre-packaged components.
  • Orchestration: Manages orchestrated workflows and automates procedures such as rolling updates and system configuration modifications using a declarative language.
  • Security and compliance: Provides integrated security features to protect encryption, authentication techniques, and communication protocols.
  • Cloud provisioning: Makes it easier to allocate cloud resources, such as storage, networking components, and virtual PCs.
  • Network automation: Automating network components is known as network automation.
  • Disaster recovery automation: This process automates disaster recovery.
  • Complex workflow automation: Coordinates intricate processes 

9. Define Ansible Tower.

Ansible offers a web-based tool called Ansible Tower that lets you: 

  • Centralize and manage all of your IT infrastructure via a visual dashboard.
  • Show all of the activity occurring in your Ansible environment in real-time.
  • Organize and automate functions like job scheduling and role-based access control (RBAC).
  • Keep an eye on every setup.

10. Can you use Ansible to produce reusable content?

Yes, you can generate reusable content with Ansible in the form of roles and playbooks.

In Ansible, content can be reused in the following ways:

  • Dynamic reuse: In a play’s tasks section, use an include_* task. You can use include_role or include_tasks.
  • Static reuse: In a play’s tasks section, use an import_* task. You can use import_role or import_tasks, for instance.
  • Organize roles: Roles can be arranged according to your needs and application. For instance, you may have application-specific roles that configure particular areas of the website and common roles that apply to all systems.
  • Share roles: Ansible Galaxy allows you to share roles with other users in collections.  

11. Define Ansible Galaxy.

This program creates a simple index structure and is connected with Ansible. Users can find and share pertinent stuff on the Galaxy website. You can use this link to download the roles from the website: 

$ ansible-galaxy enter username.role_name

12. How do we use a YAML file in Ansible, and what is it?

With a few rules akin to those of JSON or XML, YAML files are just like any other structured text file. Because it is easier to read than other forms, Ansible utilizes this syntax in playbooks.

13. Which protocol is used by Ansible to connect to Windows and Linux?

SSH is the protocol used by Linux.

WinRM is the protocol that is utilized in Windows.

14. In what contexts are tags used?

Tags are characteristics that establish the games, roles, functions, and physical structure. It is better to use a portion of the playbook rather than the entire one if a thorough one is required. Here’s where tags come in handy.

15. Describe the Ansible tasks.

An Ansible action is called a task. It assists by violating the rule against installing small files or blocks of code. The procedure can be carried out automatically with the help of these blocks.

Example: Installing software or a software update.

Command: Enter

Command: update 

16. What does idempotency mean?

Ansible’s idempotency feature makes sure that only the required modifications can be made. Although one or more tasks can be completed more than once, nothing that has previously been corrected or is functioning correctly will be replaced. 

The generated attribute can be used to use it in Ansible. A directory will only be created if it doesn’t already exist, for instance, if the task is to create one on the server. 

Both software teams and users are guaranteed quality assurance through idempotency.

17. How can the Ansible reboot module be made to run for longer than 600 seconds?

The following syntax can be used to upgrade the Ansible reboot module for more than 600 seconds: 

– name: Restart the Linux system

restart:

restart_the closing time: 1000

18. How can you use Ansible’s Docker modules?

Ansible must be used to install the Python Docker SDK on the host before using Docker modules.

The following can be used to install it with Python 2.7 or Python 3: 

$ pip insert docker.

Python 2.6 will require a version before 2.0. The following methods can be used to install it: 

$ pip install ‘docker-py> = 1.7.0’

19. What makes Ansible and Puppet different from one another?

Scheduling and Management: While the client pulls the configuration from the server in Puppet, the server delivers the configuration to the nodes in Ansible. 

  • To ensure that every node is in a desired condition, the puppet also has an agent that polls every 30 minutes (by default settings). 
  • The free edition of Ansible lacks such capability.

Availability: Puppet has many master nodes, and Ansible has backup secondary nodes. Thus, both make an effort to be very accessible.

Configuration: Due to its client-server architecture and unique declarative language, Puppet DSL, Puppet is thought to be more difficult to set up than Ansible.

Learn more about puppet with our DevOps course in Chennai.

20. Describe the recursive file copying process you will use on a target host.

Although the copy module contains a recursive argument, synchronization is a more effective option for handling enormous volumes of files.

Example

– synchronize:

   src: /first/absolute/path

   dest: /second/absolute/path

   delegate_to: “{{ inventory_hostname }}”

Ansible Interview Questions and Answers for Experienced

21. What is the most effective method for making content redistributable and reusable?

To enable the reuse and redistribution of content, you can utilize Ansible roles. 

  • Ansible roles are a level of abstraction used to arrange playbooks. 
  • Writing down every activity in the playbook, for instance, could result in errors and confusion if we have to complete ten activities on five different systems. 
  • Rather, ten roles are created and called within the playbook.

22. Describe the various types of Ansible modules.

Modules in Ansible are reusable code segments that carry out particular operations on target hosts. They serve as the fundamental components of Ansible playbooks and offer a variety of job automation features.

The various types of Ansible modules are:

  • Core Modules: These cover a wide range of automation and system administration functions and are pre-installed with Ansible.
    • Examples: Ansible.builtin.file, ansible.builtin.copy, ansible.builtin.shell, and ansible.builtin.service.
  • Community Modules: The Ansible community contributes to these modules, which can be used to increase the capabilities of Ansible.
    • They span a wide range of application cases, including databases, network devices, and cloud providers.
  • Custom Modules: To flexibly automate specialized operations that are exclusive to a certain environment, you can construct custom Ansible modules.

23. What are handlers?

Similar to special tasks, handlers only execute when the task includes a “notify” directive. 

tasks:

  – name: install nginx

    apt: pkg=nginx state=installed update_cache=true

    notify:

     – start nginx

 handlers:

   – name: start nginx

     service: name=nginx state=started

In the example above, we are using a `start nginx` handler to start the server after installing NGINX.

24. What distinguishes the array notation of variables from dot notation?

Dot notation functions properly unless we run into a few unique situations, like

  • if the variable begins or ends with an underscore, a colon(:), a dot (.), or any other known public attribute.
  • if Python dictionary attributes and methods conflict.
  • Dynamic variable composition is possible with array notation.

25. How can a template be used to loop over a list of hosts in a group?

To accomplish this, use the template’s “$groups” dictionary as follows:

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

{{ host }}

{% endfor %}

We must confirm that the facts have been filled in if we also need to access them. A play that communicates with db_servers, for example:

– hosts: db_servers

tasks:

– debug: msg=”Something to debug”

This can now be utilized in a template in the following way:

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

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

{% endfor %}.

26. How Can a Jump Host Be Configured in Ansible to Reach Servers Without Direct Access?

An intermediary server known as a jump host or proxy host is used to connect to other servers in a network that are not immediately accessible from the Ansible control system. In settings where network access is restricted, it serves as a gateway to offer safe access to target servers.

There are two ways to set up a jump host in Ansible: either use the ansible_ssh_common_args variable in the inventory file or configure the Proxy Jump option in the SSH configuration. 

Here’s a quick tutorial on configuring a jump host:

Method: Using the ProxyJump Option

Edit Your SSH Config File:

On the Ansible control system, open or create your SSH configuration file:

nano ~/.ssh/config

Add Jump Host Configuration:

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.

On using Jump Host in Ansible Playbooks:

Set the jump host in your Ansible playbook by 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

Learn from anywhere with our Ansible online course program.

27. Use an Ansible playbook to demonstrate how to install Nginx.

  • First, establish a playbook with tasks to install Nginx, update the package cache, and launch the service to install Nginx using an Ansible playbook. 
  • Next, execute the playbook using the `ansible-playbook` command, providing the name of the playbook and your inventory file to expedite the installation process on the designated hosts. 

Here is the playbook for installing Nginx on target nodes running Ubuntu or Debian.

– 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

28. How can you set up Ansible on a CentOS computer?

It only takes two easy steps to complete: 

Step 1: Create the EPEL repository.

The Fedora team’s EPEL (Extra Enterprise Linux Packages) project is a free and open-source community repository that offers top-notch Linux distribution software packages, such as Scientific Linux, CentOS, and RHEL (Red Hat Enterprise Linux).

Since the default repositories do not contain the Ansible package, we will use the following command to enable the EPEL repository:

sudo rpm -ivh http://dl.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm

All of the necessary packages for installing Ansible will be downloaded. 

Step 2: Install Ansible

Your EPEL repository has now been added; all you need to do is use the following command to install Ansible: 

yum insert ansible -y

That’s it! It only takes a minute and involves two steps!

Use the following command to see which version of Ansible is installed on your system:

ansible -version

29. How can a playbook contain confidential data?

Sensitive information is concealed from those who wish to view the result by using the following command to store verbose output.

– Name: secret function

shell: / user / drum / do_somthing -value = {{secret value}}

no_log: True

Additionally, the no_log attribute may be used at any point during the game. 

– strangers: all

no_log: True

30. Explain what infrastructure as a code (IaC) is.

The method of administering and utilizing data servers, storage systems, system configuration, and network infrastructure is known as infrastructure as code (IaC).

System administrators and the IT support staff must make minute-by-minute configuration changes in traditional configuration management systems. However, IAC handles system configuration and automatically manages infrastructure changes, managing and storing all configuration data in a conventional file system.

Because everything is automated and handled using the IAC technique, we don’t need to put in a lot of work. The IAC approach can be applied using tools such as Ansible.

31. How can a loop that iterates across a set of hosts in a list be put into a template?

The “with_items” loop construct can be used to cycle over each host in a group and carry out a predetermined task. Let’s look at a playbook example. 

– name: Perform a task on multiple hosts

 hosts: host_group

 tasks:

   – name: task_name

     //perform a task here

     with_items: “{{ groups[host_group] }}”

This makes it simple to carry out any task across several hosts.

32. How is a functional holder written?

Let’s say you wish to design a handle that only restarts the service when it is already running.

As may be seen below, tasks can inform common subjects, and holders can “listen” to those topics. 

Configuring numerous handles is made considerably simpler by this feature. Additionally, it distinguishes the holders from their names, which facilitates the sharing of handles between roles and playbooks:

– Name: Check to restart

shell: check_is_started.sh

register: result

listen: Restart processes

– Name: Restart in terms of step 2

service: name = service status = restarted

when: result

listen: Restart processes

33. What features are available in Ansible Tower?

Among the numerous functions of the web-based automation platform Ansible Tower are: 

  • Real-time Job Updates: It displays the automation tasks’ progress. 
  • Integrations with external logging: offers a thorough log of automation performance.
  • Multiple-playbook processes: combines several playbooks to produce intricate routines.
  • RESTful API: Connects to other resources and services
  • Access control based on roles: restricts access according to responsibilities
  • Job scheduling: It arranges jobs.  
  • Graphical inventory management: It uses a graphic to manage inventory.
  • CLI tools: They enable users to manage credentials, plan tasks, and carry out jobs.
  • Self-service features: It offers self-service features.

Ansible is an open-source command-line program for IT automation, and its commercial version is called Ansible Tower. Currently known as the automation controller, Ansible Tower is a part of the Ansible Automation Platform.

Take a review of our cloud computing course syllabus to begin your IT career.

34. Explain ad-hoc commands.

Ad-hoc commands are straightforward, one-line instructions used to carry out a particular action. Ad-hoc instructions are another form of playbook writing. Here is an illustration of an ad-hoc command: 

ansible host -m netscaler -a “nsc_host = nsc.example.com user = ansiuser password = antipasti”

This Ad-hoc command disables the server by gaining access to the NetScaler module.

35. How do you become as adaptable as the group’s initial host?

To get a different host from the initial host, use the following instructions:

{{hostvars [groups [‘webservers’] [0]] [‘ansible_eth0’] [‘ipv4’] [‘address’]}}

The first machine in the webservers group’s host machine name is accessed by this command. Use set_fact or jinja2′ #set’ if you’re using a template for this.

36. What is the Ansible shell’s evolutionary nature?

You need to utilize the ‘env’ test plugin in Ansible to access the available variables.

For instance, you wish to view the administrator’s office space, as indicated by the following command:

# …

vars:

local_home: “{{view (‘env’, ‘Office’)}}”

I

{{ansible_env.SOME_VARIABLE}}

37. In other dynamic fields of employment, how do you set the scene?

The term “location” can be used to set natural variables. It can be configured for an entire playbook or just a particular task. To see how you set it, run the following code: 

environment:

HOW: “{{ansible_env.PATH}}: / thingy / bin”

OTHERS: number

38. How are Ansible projects evaluated?

Three test modes are accessible:

Asserts: It guarantees that your system has arrived at its destination, not only a test mode analogy.

Check Mode: Check mode demonstrates how things will function in the absence of simulation. 

  • As a result, it is easy to see that the project behaves in the way you desire. 
  • Scripts and commands in playbooks and paragraphs are not used in the check mode. 
  • For certain jobs, you must use “check_mode: no” to disable the test mode.

Manually Run: Launch the game and confirm that the system is configured as you want it to be. 

  • Although this test option is simple, there is a higher risk because the outcomes at the test location could not be different in the production region.

39. What is the operation of the Ansible synchronize module?

Ansible synchronize is a Linux module that functions similarly to rsync and may be used in playbooks. There are some restrictions, but the features are similar to rsync, including archive, press, delete, etc.

  • It is necessary to install Rsync on both the source and target systems.
  • To switch the source from localhost to a different port, you must specify delegate_to.
  • Since the remote user can access the files, you must control the user’s permissions.
  • When using sudo, we should always supply the entire home directory. If not, a copy of the files will be made to the home directory of the remote user.
  • Solid link-related Linux rsync limitations also apply here.
  • If the connection fails, -description updates are enforced to prevent a broken state.

Example

– hosts: host-remote tasks:

– name: sync from sync_folder

synchronize:

src: /var/tmp/sync_folder dest: /var/tmp/

Here we copy the files to the folder.

/ var / tmp / sync_folder to the remote / folder / var / tmp folder.

40. What distinguishes the Ansible set_fact module from include_var, vars, or vars_file?

Like the logical realities in the settings module, Ansible’s set_fact function is used to set new variable values host by host. 

The following games in the playbook have these modifications. 

We know the value in advance when using vars, vars_file, or insert_var. If we use set_fact, we can store the agreement after making adjustments over time using specific functions like applying filters or taking small components of some kind. 

An existing database can also be set up by us. Key-pair values are used to assign a set_fact variable, where the value represents the function of the variable word and the key is the variable word itself. The same basic example will be given here.

– set_fact:

one_fact: value1

second_fact: value2

Conclusion

This article contains a detailed discussion of the Ansible interview questions and answers. We hope these interview questions for Ansible will be helpful for you to ace the DevOps tech rounds. Master in DevOps practices through our Ansible course in Chennai

Share on your Social Media

Just a minute!

If you have any questions that you did not find answers for, our counsellors are here to answer them. You can get all your queries answered before deciding to join SLA and move your career forward.

We are excited to get started with you

Give us your information and we will arange for a free call (at your convenience) with one of our counsellors. You can get all your queries answered before deciding to join SLA and move your career forward.