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

Write a rolling deploy playbook: 2 servers at a time, removed from the load balancer during the update.

AdvancedHands-onWrite-an-Ansible-playbook tasks
Answer
- hosts: web
  become: true
  serial: 2
  max_fail_percentage: 0
  pre_tasks:
    - name: Deregister from target group
      community.aws.elb_target:
        target_group_arn: "{{ tg_arn }}"
        target_id: "{{ ec2_id }}"
        state: absent
      delegate_to: localhost
      become: false

  tasks:
    - name: Deploy new release
      ansible.builtin.unarchive:
        src: "https://artifacts.example.com/app-{{ version }}.tgz"
        dest: /opt/app
        remote_src: true
      notify: Restart app
    - ansible.builtin.meta: flush_handlers
    - name: Wait for health
      ansible.builtin.uri:
        url: "http://localhost:8080/health"
        status_code: 200
      register: h
      retries: 20
      delay: 3
      until: h.status == 200

  post_tasks:
    - name: Register back
      community.aws.elb_target:
        target_group_arn: "{{ tg_arn }}"
        target_id: "{{ ec2_id }}"
        state: present
      delegate_to: localhost
      become: false

  handlers:
    - name: Restart app
      ansible.builtin.systemd: { name: app, state: restarted }

Key trick → serial: 2 processes hosts in batches, max_fail_percentage: 0 stops the rollout on the first failure, and flush_handlers restarts the app before the health check instead of at the end of the play.

All Real-World Interview questions Roadmap: Interview readiness

More on Write-an-Ansible-playbook tasks