Ansible interview question · Most asked
Write an Ansible playbook that installs Nginx, deploys its configuration, enables the service and restarts it only when the configuration changes.
Hands-on Asked in DevOps Engineer interviews
Summary
Install the package, template the config with validation, notify a restart handler from the template task, and make sure the service is enabled and started. The handler only runs when the template task reports a change, so re-running the playbook with an unchanged config never restarts Nginx.
Longer Answer
Points worth calling out in the interview:
validate: nginx -t -c %schecks the rendered file before it replaces the live one, so a typo can't take the site down.- Use reload rather than restart when Nginx supports it: it applies config without dropping connections.
state: startedplusenabled: truemakes the service idempotent: no restart on every run.become: truebecause package and service changes need root.
Example
- name: Web servers run Nginx
hosts: web
become: true
tasks:
- name: Install Nginx
ansible.builtin.package:
name: nginx
state: present
- name: Deploy nginx.conf
ansible.builtin.template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
owner: root
mode: "0644"
validate: nginx -t -c %s
notify: Reload Nginx
- name: Nginx is enabled and running
ansible.builtin.service:
name: nginx
state: started
enabled: true
handlers:
- name: Reload Nginx
ansible.builtin.service:
name: nginx
state: reloaded
Key Points
- Template task notifies the handler.
- Validate config before installing it.
- Handler runs only on change, once per play.
- Prefer reload over restart for Nginx.
Explanation
What interviewers look for
A correct, idempotent playbook and the reasoning: validation, handler semantics and reload vs restart.
More Ansible questions
- Explain Ansible's architecture: control node, inventory, modules, playbooks, roles and handlers.
- What is idempotency in Ansible, and how do you keep your own tasks idempotent?
- How do you manage secrets with Ansible Vault?
- How do you structure reusable Ansible roles for several environments?
- Explain serial, delegate_to, when and notify in Ansible.
- How would you automate TLS certificate installation and renewal with Ansible?
- How would you configure 100 Linux servers consistently with Ansible?
- How do Ansible and Terraform work together in one delivery pipeline?