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.
More on Write-an-Ansible-playbook tasks
Write a playbook that installs and starts Nginx on Ubuntu web servers.BeginnerWrite an inventory with groups, a group of groups, and per-group variables.BeginnerWrite a playbook that deploys a config file from a Jinja2 template and restarts the service only if it changed.BeginnerWrite a role structure for a Node.js app and show what goes in each folder.IntermediateWrite a task that creates multiple users with SSH keys from a list.BeginnerEncrypt a database password with Ansible Vault and use it in a playbook.Beginner