Ansible Automation Ansible Modules & Task Execution 2 — Questions and Answers
Question 1: What keyword is used to conditionally execute a task based on a variable or fact?
- when (Correct answer)
- if
- condition
- only_if
Correct answer: when
The 'when' keyword accepts a Jinja2 expression and skips the task if the expression evaluates to false.
Question 2: Which task keyword allows you to loop over a list of items?
- loop (Correct answer)
- with_items
- iterate
- foreach
Correct answer: loop
The 'loop' keyword (introduced in Ansible 2.5) is the modern replacement for with_items and iterates tasks over a list.
Question 3: What does the 'register' keyword do in an Ansible task?
- Saves the task's output/return values into a variable for later use (Correct answer)
- Registers the host with an inventory service
- Logs the task result to a file
- Marks the task as idempotent
Correct answer: Saves the task's output/return values into a variable for later use
The register keyword captures a task's result (stdout, rc, changed status, etc.) into a named variable accessible in subsequent tasks.
Question 4: How do you reference the current loop item's value inside a task that uses 'loop'?
- {{ item }} (Correct answer)
- {{ loop.item }}
- {{ current }}
- {{ loop_var }}
Correct answer: {{ item }}
Inside a loop, the current iteration's value is always available as the special variable {{ item }}.
Question 5: What does setting 'ignore_errors: yes' on a task do?
- Allows the playbook to continue even if the task fails (Correct answer)
- Silently skips the task on failure
- Retries the task on failure
- Marks the task result as always changed
Correct answer: Allows the playbook to continue even if the task fails
ignore_errors: yes tells Ansible to record the failure but continue executing subsequent tasks instead of stopping the play.
Question 6: What is the purpose of 'failed_when' in a task?
- Define a custom condition under which the task is considered failed (Correct answer)
- Catch and handle task failures
- Skip the task when it would fail
- Retry a task until it stops failing
Correct answer: Define a custom condition under which the task is considered failed
failed_when overrides Ansible's default failure detection with a custom Jinja2 expression, letting you define exactly what constitutes failure.
What keyword is used to conditionally execute a task based on a variable or fact?