Interview Prep/Real-World Interview/Write-an-Ansible-playbook tasks

Write a playbook that deploys a config file from a Jinja2 template and restarts the service only if it changed.

BeginnerHands-onWrite-an-Ansible-playbook tasks
Answer
- hosts: web
  become: true
  vars:
    worker_connections: 2048
  tasks:
    - name: Deploy nginx.conf
      ansible.builtin.template:
        src: templates/nginx.conf.j2
        dest: /etc/nginx/nginx.conf
        owner: root
        mode: "0644"
        validate: nginx -t -c %s
      notify: Reload nginx

  handlers:
    - name: Reload nginx
      ansible.builtin.service:
        name: nginx
        state: reloaded
events { worker_connections {{ worker_connections }}; }

Key trick → A handler runs once at the end of the play, and only if a notifying task reported changed. validate: tests the rendered file before it replaces the live one, so a bad template can't break Nginx.

All Real-World Interview questions Roadmap: Interview readiness

More on Write-an-Ansible-playbook tasks