Professional Documents
Culture Documents
Ansible
Ansible
1. What is an inventory file used for and default inventory host location?
Purpose: An inventory file contains a list of managed nodes (hosts) that Ansible
can connect to and work with. It defines how Ansible groups hosts together for
targeted actions.
Default Location: /etc/ansible/hosts
2. What is ansible configuration file used for and its default path?
Purpose: The Ansible configuration file lets you customize Ansible's behavior, such
as inventory locations, default modules to use, connection settings, and more.
Default Path: /etc/ansible/ansible.cfg
Rerun from the failed task: Use Ansible's --start-at-task option to restart the
playbook at the point of failure.
External Scripting: Write a shell script or use a workflow management tool to
monitor Ansible runs and trigger reruns if needed.
Error Handling: Utilize Ansible's error handling mechanisms (rescue, block) within
your playbook to gracefully manage failures and potentially retry or self-
remediate.
19. What type of connection does Ansible establish with Linux and Windows nodes?
Linux: Primarily SSH (Secure Shell) by default.
Windows: WinRM (Windows Remote Management) for remote PowerShell execution.
23. Please write below a sample inventory file with host, group & group of groups
syntax in it.
Ini, TOML
# Simple 'hosts' file, can be INI or YAML format
[webservers]
webhost1.example.com
webhost2.example.com
[databases]
dbhost1.example.com
25. What are ad-hoc commands used for & write below the syntax of an ad-hoc
command?
Purpose: Ad-hoc commands execute single, quick tasks across managed nodes. It's
great for one-off actions without creating full playbooks.
Syntax: ansible <group or host pattern> -m <module_name> -a "<module arguments>"
26. Write below ad-hoc command to gather fact variables on all the hosts from the
inventory file?
Bash
ansible all -m setup
27. What format does ansible ad-hoc command return the output?
Ansible ad-hoc commands typically return output in JSON format by default.
copy: Copy files between the control node and managed nodes.
file: Manage file properties (state, permissions, ownership).
lineinfile: Modify single lines within files.
apt/yum: Manage packages on Debian/RedHat based Linux systems.
user: Manage user accounts.
group: Manage groups.
service: Manage services (start, stop, restart).
shell/command: Execute arbitrary shell commands on managed nodes.
template: Generate files from templates (powered by Jinja2).
synchronize: Use rsync for efficient file transfer.
30. How to list all the Ansible core modules from the command line.
Bash
ansible-doc -t module -l
31. How to display all the options/attributes for the apt module from the command
line.
Use the ansible-doc command:
Bash
ansible-doc apt
Use code with caution.
This will provide detailed information on the apt module, including available
options, explanations, and examples.
32. How can you check mandatory options for any module from the command line?
The ansible-doc output will indicate if a module's options are mandatory. Look for
the following:
YAML
---
- hosts: all # Target all hosts in inventory
gather_facts: yes # Gather facts before tasks
become: yes # Execute tasks with elevated privileges
tasks:
# Your tasks go here
35. Write down any two tasks from a playbook with their proper format and names.
YAML
- name: Update system packages
apt:
name: "*" # Install all available updates
state: latest
36. What is the difference between sudo and become modules and their purpose?
Both are used for privilege escalation within Ansible, but they have key
differences:
sudo:
Runs commands as the 'sudo' user.
Useful if your Ansible user has general sudo permissions.
become:
Offers greater flexibility for different privilege escalation methods (sudo, su,
etc.).
Allows you to become a user other than root if needed.
37. Write down playbook syntax of starting ntp service on webserver and dbservers
host group at once.
YAML
- hosts: webservers:dbservers # Target multiple groups
become: yes
tasks:
- name: Start NTP service
service:
name: ntpd
state: started
enabled: yes
YAML
- vars_prompt:
- name: "db_password"
prompt: "Enter the database password"
private: yes # Don't display the input on screen
Troubleshooting issues.
Understanding the value of variables at specific points.
40. How to store the output of any task into a variable from a playbook?
Use the register keyword:
YAML
- name: Get disk usage
shell: df -h
register: disk_usage
41. What are handlers used for in Ansible and how are they different from tasks?
Handlers: Special tasks that execute only when they're notified by other tasks.
Triggers: Handlers are triggered when a task changes the state of the system (e.g.,
install a package, modify a file).
Differences from tasks:
Handlers normally run at the end of a play, not immediately.
They run only if they've been notified.
42. Conditional execution in Ansible is used for what purpose and write down its
syntax with a small description?
Purpose: Conditionals (when) allow you to control whether tasks execute based on
specific conditions (like the presence of a file, a variable's value, etc.).
Syntax
YAML
- name: Install Apache if it's not present
apt:
name: apache2
state: latest
when: ansible_facts['packages']['apache2'] is not defined
Bash
ansible-galaxy init <role_name>
48. Write down all the places where we can define variables according to their
precedence.
Ansible has a complex variable precedence order. Here's a general overview from
lowest to highest priority:
50. Setup module gets executed after executing any ad-hoc command. (True or False)
True. The setup module is a special case. While ad-hoc commands usually target a
single task, ansible <pattern> -m setup automatically runs the setup module to
gather facts.
53. Fact variables are generated by Ansible, and we do not need to create fact
variables.
True. The setup module automatically gathers facts about managed nodes, generating
variables available for use in your playbooks.
55. Ansible works on a Master and client relationship, where ansible control server
package is installed on master, and ansible client package is installed on all the
clients.
False. Ansible is agentless. You primarily need Python and SSH access (or WinRM for
Windows) on managed nodes.
57. All the templates in Ansible roles have to be defined in the main.yml file
inside the templates directory.
False. While you can use main.yml in the templates directory, an Ansible role can
have multiple template files.
58. All the roles uploaded to the Ansible Galaxy website are written and owned by
Ansible Inc (the organization).
False. Ansible Galaxy is a community hub; anyone can contribute and share Ansible
roles.
59. Ansible can only get installed on Linux machines but can manage Linux and
Windows nodes.
False. Ansible can be installed on control nodes running Linux, macOS, or even
Windows (via WSL- Windows Subsystem for Linux).
60. Write an Ansible task that can copy the file to a remote location with the
ownership of Jboss?
YAML
- name: Copy file with Jboss ownership
copy:
src: /local/path/to/file.txt
dest: /remote/path/on/managed/nodes/
owner: Jboss
group: Jboss
63. Write a playbook for the installation of Apache on Ubuntu and CentOS?
YAML
---
- name: Install Apache
hosts: all
tasks:
- name: Install Apache on Debian/Ubuntu systems
apt:
name: apache2
state: latest
when: ansible_os_family == 'Debian'
66. If we want system information of a machine, how will we get the data with
Ansible like we use facter in Puppet?
The setup Module: Run ansible <host_pattern> -m setup to gather facts about remote
systems. Fact variables hold information like OS details, hostname, IP addresses,
and more. They are the Ansible equivalent of Facter.
Dedicated LDAP Roles: Find prebuilt roles on Ansible Galaxy to install and
configure LDAP servers (search for roles tailored to your specific LDAP
implementation).
Tasks: Use Ansible modules like package, template, and service to install the LDAP
server package, configure it with templates, and manage the service.
Hybrid: Combine a role with some custom tasks for fine-grain configuration.
70. How Ansible works... and what are the playbooks written other than the basic
playbooks?
Core: Ansible connects to managed nodes using SSH (Linux) or WinRM (Windows) and
pushes small programs (modules) to execute tasks.
Advanced Playbooks: While you start with basic tasks, Ansible can be used for:
Complex Deployments: Rolling updates, blue/green deployments, etc.
CI/CD Integration: Part of automated deployment pipelines.
Network device configuration: Managing switches, routers, etc.
Virtually anything! Ansible's flexibility lets you tackle a vast range of
automation scenarios.
Create a Jenkins job that triggers when a new build artifact is available (e.g.,
polling your source code repository).
Configure a build step to generate your code artifact.
Ansible Playbook:
YAML
---
- name: Install Apache and deploy sample website
hosts: webservers
tasks:
- name: Install Apache (Debian/Ubuntu)
apt:
name: apache2
state: latest
when: ansible_os_family == 'Debian'
YAML
- name: Get hostname
hostname:
name: my_hostname
register: hostname_output
Variables values
Existence of files
Output of previous tasks
YAML
- name: Create AMI
hosts: localhost
connection: local
gather_facts: false
tasks:
- name: Create AMI
amazon.aws.ec2_ami:
instance_id: your_instance_id
name: my_ami_{{ ansible_date_time.iso8601 }}
wait: yes
Python: Most Ansible modules are written in Python. You'll need to understand how
to structure the module and handle arguments.
Plugins: Ansible provides a plugin system where you can develop modules in other
languages, though Python is most common.
83. How can you do provisioning with Ansible?
Ansible is excellent for provisioning new servers or instances:
Cloud Modules: Utilize Ansible's cloud modules (e.g., for AWS, Azure, GCP) to
provision instances.
Installation Tasks: Include tasks to install necessary packages, configure
software, etc.
Idempotency: Ansible helps ensure your provisioning playbooks are safe to re-run
for consistent setups.
Bash:
Quick-and-dirty scripts
Procedural – good for linear tasks
Python:
More structured, libraries and modules
Handles complex logic and data manipulation
Ansible (and similar):
Declarative – focus on desired state
Modules and idempotency simplify configuration
Great for larger-scale orchestration and standardization
85. How can you update a single table in a database with Ansible?
Ansible has database modules:
YAML
- name: Update a database table
mysql_db:
login_user: dbuser
login_password: dbpassword
name: mydatabase
state: present
sql: "UPDATE mytable SET column1='new_value' WHERE id=123"
86. What types of roles did you use in your playbook? Explain.
88. Write a playbook for installing AppDynamics and configuring the agents for the
same?
I'd need more specifics, but here's the general outline:
Assumptions:
YAML
- name: Install and configure AppDynamics
hosts: my_servers
vars:
appd_agent_version: ...
appd_controller_host: ...
# ...other configuration params
tasks:
- name: Download AppDynamics agent
get_url:
url: https://download.appdynamics.com/agent/...{{ appd_agent_version }}...
dest: /tmp/appd_agent.zip
Important:
Replace placeholders with accurate values.
May need additional tasks (dependencies, firewall rules, agent start, etc.).
Task – a call to a specific Ansible module Module – the actual unit of code
executed by Ansible on your own host or a remote host. Modules are indexed by
category (database, file, network, …) and also referred to as task plugins.
Play – One or more tasks executed on a given host(s)
Playbook – One or more plays. Each play can be executed on the same or different
hosts
Role – Ansible roles allows you to group resources based on certain
functionality/service such that they can be easily reused. In a role, you have
directories for variables, defaults, files, templates, handlers, tasks, and
metadata. You can then use the role by simply specifying it in your playbook.
Variables -
In the play = vars:
In the play = vars_files:
On the command line = -e key=value
Using vars_prompt: to request values from user while running playbook
Ansible vault
(1a) Create encrypted file:
$ ansible-vault create <FILENAME>
$ ansible-vault create --vault-password-file=.secret_file <FILENAME>
(2a) Enter and confirm new vault password
(1b) Or encrypt and existing file(s):
$ ansible-vault encrypt <FILE1> <FILE2> ...
$ ansible-vault encrypt --output=NEW_FILE <OLDFILE>
(2b) Enter and confirm new vault password
(3) View file:
$ ansible-vault view <FILENAME>
(4) Edit file:
$ ansible-vault edit <FILENAME>
(5) Change password:
$ ansible-vault rekey <FILENAME1> <FILENAME2>
$ ansible-vault rekey --new-vault-password-file=.secret_file <FILENAME>
(6) Decrypt file:
$ ansible-vault decrypt <FILENAME> --output=<FILENAME>