Lesson 15 / 26
register, Tags and Blocks
Capture results, run selected tasks with tags and handle errors with blocks.
Results, selection, recovery
register: stores a task's result in a variable (stdout, return code, changed status) for later tasks. Tags label tasks so you can run or skip subsets with --tags and --skip-tags. A block: groups tasks, and rescue: / always: sections give try/catch/finally behaviour for recoverable failures. Use changed_when: and failed_when: to tell Ansible what counts as a change or failure for command-style tasks.
Registered output, run
Running only the info tag shows the registered stdout of a harmless command.
ansible-playbook -i inventory.ini vars.yml --tags info
Output:
"out.stdout": "hello"
A block with rescue
If the risky task fails, the rescue task runs and the play continues. (Illustrative; not run here.)
- name: Deploy with rollback
block:
- name: Switch to new release
ansible.builtin.command: /opt/app/switch_release.sh {{ release }}
rescue:
- name: Roll back to previous release
ansible.builtin.command: /opt/app/switch_release.sh {{ previous_release }}
always:
- name: Record the attempt
ansible.builtin.debug:
msg: "deploy attempt finished"Quick check: What does `--tags info` do?
- Runs only tasks tagged info
- Deletes tasks tagged info
- Skips tasks tagged info
- Encrypts tags
Answer
Runs only tasks tagged info — Tag selection narrows a run to chosen tasks.