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

Write a playbook that installs and starts Nginx on Ubuntu web servers.

BeginnerHands-onWrite-an-Ansible-playbook tasks
Answer
- name: Install and run nginx
  hosts: web
  become: true
  tasks:
    - name: Install nginx
      ansible.builtin.apt:
        name: nginx
        state: present
        update_cache: true
        cache_valid_time: 3600

    - name: Start and enable nginx
      ansible.builtin.service:
        name: nginx
        state: started
        enabled: true

Run: ansible-playbook -i inventory.ini site.yml --check --diff, then without --check.

Key trick → cache_valid_time stops apt from refreshing on every run, and modules with state: are idempotent, so a second run reports changed=0.

All Real-World Interview questions Roadmap: Interview readiness

More on Write-an-Ansible-playbook tasks