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.
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 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.BeginnerWrite a rolling deploy playbook: 2 servers at a time, removed from the load balancer during the update.AdvancedEncrypt a database password with Ansible Vault and use it in a playbook.Beginner