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

Members can save this page, take notes and track progress. See membership · Sign in

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 %s checks 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: started plus enabled: true makes the service idempotent: no restart on every run.
  • become: true because 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

← All Ansible questions

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake