Courseiva

CCNA Implement advanced Ansible automation Questions

63 questions · Implement advanced Ansible automation · All types, answers revealed

1
MCQmedium

A role contains a handler. The playbook includes the role and also defines a task that notifies the same handler. When the playbook runs, the handler executes only once. Which of the following best explains this behavior?

A.the handler was already triggered by the role and is skipped for the play task
B.handlers are deduplicated by name; multiple notifications trigger the handler only once per play
C.the role's handler uses 'listen' which overrides notifications
D.the playbook's task notifies a different handler with the same name
AnswerB

Handlers are deduplicated by name, so notifications from both the role and the playbook task resolve to the same handler. It runs once per play after all notifying tasks complete, regardless of how many tasks notified it.

Why this answer

Ansible handlers are deduplicated by name within a play. When a handler is notified multiple times—whether from a role or a playbook task—it runs only once at the end of the play, after all tasks have completed. This prevents redundant executions and is a core design feature of Ansible's handler system.

Exam trap

The trap here is that candidates may think handlers are executed immediately upon notification or that multiple notifications cause multiple executions, but Ansible deduplicates by handler name and runs them only once per play, regardless of the number of notifications.

How to eliminate wrong answers

Option A is wrong because handlers are not 'skipped' after being triggered; they are simply queued and executed once regardless of how many times they are notified. Option C is wrong because the 'listen' directive allows multiple handlers to be triggered by a single notification, but it does not override or deduplicate notifications; deduplication is inherent to handler names. Option D is wrong because if the playbook's task notifies a different handler with the same name, it would be the same handler object (since names are unique within a play), and the behavior would still be deduplication, not a separate handler.

2
MCQeasy

An Ansible playbook is designed to run on a group of database servers. The administrator wants to ensure that a task runs only on the primary database server, which is defined in the inventory with a variable 'primary: true'. Which conditional should be used?

A.ignore_errors: yes
B.when: primary
C.run_once: true
D.delegate_to: "{{ primary }}"
AnswerB

Using `when: primary` evaluates the host variable directly as a boolean condition, so the task executes only where the inventory sets `primary: true`. This satisfies the stem's constraint of restricting execution to the primary database server, since Ansible treats the variable's truthiness as the conditional test without requiring an explicit comparison.

Why this answer

The `when` conditional in Ansible evaluates a Jinja2 expression to determine whether a task should execute. By using `when: primary`, the task will run only on hosts where the inventory variable `primary` is defined and evaluates to `true` (a truthy value). This directly meets the requirement to target the primary database server.

Exam trap

The trap here is that candidates confuse `run_once: true` with a conditional that selects a specific host, not realizing `run_once` merely limits execution to a single arbitrary host in the group, not the one defined by a variable like `primary: true`.

How to eliminate wrong answers

Option A is wrong because `ignore_errors: yes` does not control task execution based on a condition; it merely continues playbook execution if the task fails, which is irrelevant to targeting a specific host. Option C is wrong because `run_once: true` ensures a task runs only once across the entire batch of hosts (typically on the first host in the group), but it does not select a specific host based on a variable like `primary: true`; it could run on any host, not necessarily the primary. Option D is wrong because `delegate_to: "{{ primary }}"` attempts to delegate the task to a host named by the variable `primary`, but this is not a conditional; it changes the target host for execution and would fail if `primary` is not a valid hostname or group, and it does not evaluate a boolean variable.

3
Drag & Dropmedium

Drag and drop the steps to configure a network bond (bond0) using nmcli in the correct order.

Drag or tap steps into the slots.

Steps
Order
1Step 1
2Step 2
3Step 3
4Step 4

Why this order

The correct order to configure a network bond using nmcli is: create the bond connection first, then add slave interfaces to it, set the bonding mode (e.g., active-backup), activate the bond, and finally verify the bond status. This sequence ensures that the bond interface exists before adding slaves and that the mode is set before activation so that the bond operates correctly from the start.

4
MCQmedium

A playbook uses serial: 2 and sets any_errors_fatal: true. The first batch of 2 hosts both fail. What happens?

A.The playbook continues with the next batch.
B.The playbook aborts and no further batches run.
C.The playbook marks the batch as unreachable and continues.
D.The playbook retries the failed hosts.
AnswerB

With any_errors_fatal set, a task failure on any host halts the entire play for all hosts. Since both hosts in the first serial batch of two fail, the play aborts immediately, so the remaining batches never execute.

Why this answer

When `any_errors_fatal: true` is set and a batch of hosts fails, Ansible immediately aborts the entire playbook run for all remaining hosts, regardless of the `serial` setting. Since the first batch of 2 hosts both fail, no further batches are executed. This behavior is designed to prevent cascading failures in critical deployments.

Exam trap

In Red Hat RHCE exams, candidates are often tested on the interaction between `serial` and `any_errors_fatal`, trapping those who assume `serial` batches always run independently, forgetting that `any_errors_fatal` forces a global abort on the first failure.

How to eliminate wrong answers

Option A is wrong because `any_errors_fatal: true` overrides the default batch-continue behavior of `serial`; Ansible does not proceed to the next batch after a failure in the current batch. Option C is wrong because the hosts are not marked as unreachable (which would require a connectivity failure, not a task failure), and the playbook does not continue; it aborts. Option D is wrong because `any_errors_fatal: true` does not trigger automatic retries; retry behavior is controlled by `retries` and `until` on individual tasks, not by this directive.

5
Multi-Selecthard

Which two statements about ansible-vault are true? (Select exactly 2.)

Select 2 answers
A.Vault-encrypted files cannot be used with include_vars.
B.Vault can encrypt entire files or individual variables.
C.Vault uses AES-128 encryption by default.
D.Vault passwords can be stored directly in ansible.cfg.
E.Vault supports multiple passwords with vault IDs.
AnswersB, E

ansible-vault encrypts at file level; variable encryption requires specific syntax.

Why this answer

Ansible-vault can encrypt either entire files (e.g., vars files, role defaults) or individual variables within a YAML file using the `!vault` tag. This flexibility allows you to protect sensitive data at the granularity you choose, without requiring separate encrypted files for each secret.

Exam trap

The trap here is that candidates often confuse the encryption algorithm (AES-128 vs AES-256) or assume vault-encrypted files cannot be dynamically included, when in fact include_vars works seamlessly with decryption.

6
MCQhard

An administrator needs to securely pass a database password to a playbook without exposing it in logs or the command line. Which approach is the most secure?

A.Store the password in an Ansible Vault-encrypted variable file and include it.
B.Set the password in a variable and use 'no_log: true' on tasks that use it.
C.Store the password in a host_vars file with restricted file permissions.
D.Prompt for the password and pass it as an extra variable using -e.
AnswerA

Ansible Vault encrypts the variable file at rest with AES-256, so the password is decrypted only in memory during playbook execution and never appears in logs, process listings or command-line arguments. This satisfies the stem's requirement to avoid exposure in logs or on the command line.

Why this answer

Ansible Vault encrypts the variable file at rest, and including it via `vars_files` or `include_vars` decrypts it only in memory during playbook execution. This prevents the password from appearing in logs, the command line, or the process table, meeting the security requirement.

Exam trap

The trap here is that candidates often confuse `no_log: true` with actual encryption, thinking it hides the secret from all exposure, when in fact it only suppresses output and does not protect the secret from being visible in the process table or module internals.

How to eliminate wrong answers

Option B is wrong because `no_log: true` only hides the task output from logs, but the password is still passed in plaintext to the module and could be exposed via the process table or debug output if the module itself logs it. Option C is wrong because `host_vars` files with restricted file permissions still store the password in plaintext on disk, and any user with read access to the file or a backup can retrieve it. Option D is wrong because passing the password as an extra variable with `-e` exposes it in the command line, which is visible in the process list and shell history, and it may also appear in logs if the playbook uses `--log-level` or `ANSIBLE_LOG_PATH`.

7
Multi-Selecteasy

Which TWO of the following are advantages of using 'ansible-pull' over 'ansible-playbook'?

Select 2 answers
A.It can be used in environments where a central control node is not desired.
B.It eliminates the need for an inventory file.
C.Nodes can self-configure by pulling playbooks from a git repository.
D.It supports a different syntax for playbooks that is more efficient.
E.It reduces load on the control node because it runs locally on each node.
AnswersA, C

ansible-pull runs locally on each managed node, fetching playbooks from git rather than receiving them from a central controller. This satisfies the stem's constraint of operating without a central control node, which ansible-playbook cannot do since it requires a controller to push tasks.

Why this answer

Option A is correct because ansible-pull is designed for decentralized setups: each managed host runs the ansible-pull command itself, fetching and executing a playbook from a git repository, so no persistent central control node is required to push configurations. Option C is correct because ansible-pull's core behavior is exactly that nodes self-configure by cloning or updating a playbook from a git repository (via the -U/--url option) and then running it locally with ansible-playbook under the hood. Option B is not a real advantage: ansible-pull still relies on an inventory (typically localhost or a local inventory file) to determine targets, so it does not eliminate inventory usage.

Option D is false because ansible-pull uses the same YAML playbook syntax as ansible-playbook; there is no separate, more efficient syntax. Option E is misleading: although execution happens locally, ansible-pull does not inherently reduce control-node load as a designed advantage, and the question asks for advantages over ansible-playbook, which is not established by this option.

Exam trap

The trap here is that candidates often confuse 'eliminating the need for a control node' with 'eliminating the need for inventory,' or incorrectly assume that running locally automatically reduces load, when in fact the load is redistributed rather than reduced.

8
MCQeasy

A playbook uses the copy module to deploy a configuration file. The file should be templated with variables, but the engineer mistakenly uses the 'src' parameter with a static file instead of 'content' or a template module. What is the most likely outcome?

A.The module automatically renders the Jinja2 template before copying.
B.The file is copied without variable substitution, resulting in literal Jinja2 syntax in the destination.
C.The playbook fails because the source file contains undefined variables.
D.The task is skipped because copy cannot handle variables.
AnswerB

The copy module's src parameter transfers the file verbatim, so Jinja2 placeholders such as {{ variable }} remain unrendered. Variable substitution only occurs through the template module or the content parameter, satisfying the stem's templating requirement.

Why this answer

The copy module with the 'src' parameter copies a file without any processing of Jinja2 templates. It does not perform variable substitution. Therefore, if the source file contains Jinja2 syntax (e.g., {{ variable }}), it will be copied literally to the destination.

The correct answer is B. Option A is incorrect because the copy module does not automatically render templates. Option C is incorrect because the playbook will not fail due to undefined variables; it simply copies the file as-is.

Option D is incorrect because the task will execute and copy the file, not skip.

9
MCQhard

Refer to the exhibit. The playbook fails because the httpd package is not found. Which is the most likely cause?

A.The inventory does not define 'webservers' group.
B.The role path is incorrectly configured in ansible.cfg.
C.The target host does not have the necessary repositories enabled.
D.The 'yum' module should use 'name=httpd' instead of YAML syntax.
AnswerC

Missing or disabled repositories leave the package manager unable to resolve the httpd package name, so the task fails at dependency resolution rather than at installation. Enabling the correct RHEL subscription or custom repository on the managed host restores package availability, satisfying the stem's constraint that the package simply cannot be found.

Why this answer

The error indicates the package is not available. This is typically due to missing or incorrect repository configuration. The playbook itself and role syntax are valid.

10
MCQhard

A company uses Ansible Vault to encrypt sensitive data in playbooks. They have multiple environments (dev, test, prod) and use a separate vault password file for each environment. The passwords are stored in files named 'vault-pass-dev', 'vault-pass-test', and 'vault-pass-prod'. To run a playbook against the test environment, they use the command 'ansible-playbook site.yml -i test -e @test-vars.yml --vault-id test@vault-pass-test'. This runs successfully from the command line. However, when they define the same vault-id in an Ansible Tower credential and attempt to run the job, the job fails with 'ERROR! Decryption failed (no vault secrets would be found that could decrypt the vault encrypted file)' for a vault-encrypted variable file that was encrypted with a different vault ID (e.g., 'dev'). The team expects that Tower would use the provided vault credential to decrypt all vault-encrypted files. Which change should be made to ensure correct decryption in Tower?

A.Add multiple vault credentials to the job template, one for each vault ID used in the project.
B.Enter all vault passwords separated by commas in the 'VAULT PASSWORD' field of a single credential.
C.Re-encrypt all files with the same vault ID (e.g., 'default') to simplify the setup.
D.Change the vault password file to contain the password for the vault ID that was used to encrypt the file.
AnswerA

Tower matches each vault credential to a single vault ID, so a test credential cannot decrypt dev-encrypted files. Adding one credential per vault ID lets Tower supply every required secret, satisfying the multi-environment decryption constraint that the CLI handled via repeated --vault-id flags.

Why this answer

In Ansible Tower, each vault credential is associated with a single vault ID and password. To decrypt files encrypted with different vault IDs, you must attach multiple vault credentials to the job template, each corresponding to a vault ID used in the project. This allows Tower to try each credential until decryption succeeds.

The command-line success with a single vault-id works because only files encrypted with that ID are decrypted; files with other IDs would fail unless multiple --vault-id options are provided.

Exam trap

EX294 often tests the misconception that a single vault credential can decrypt all vault-encrypted files regardless of vault ID, leading candidates to overlook the need for multiple credentials.

How to eliminate wrong answers

Option B is wrong because the VAULT PASSWORD field in a single credential accepts only one password, not a comma-separated list; multiple passwords require multiple credentials. Option C is wrong because re-encrypting all files with the same vault ID reduces security and does not address the requirement to support multiple environments with separate passwords. Option D is wrong because changing the vault password file to contain the password for the file's vault ID would only work if that file is the only one, but the project uses multiple vault IDs; it does not solve the need for multiple credentials.

11
MCQeasy

An administrator wants to run a playbook with a different user for a specific host. Which variable should be set?

A.ansible_user
B.ansible_user_id
C.ansible_ssh_user
D.ansible_remote_user
AnswerA

Correct variable to set SSH user.

Why this answer

Ansible_user sets the remote user for SSH connections to the target host. Option B (ansible_user_id) is a fact variable that returns the UID of the user running the task on the remote host, not the connection user. Option C (ansible_ssh_user) is a deprecated alias for ansible_user.

Option D (ansible_remote_user) is also a deprecated alias.

12
MCQmedium

An Ansible playbook includes a role that defines default variables in 'defaults/main.yml' and role variables in 'vars/main.yml'. A playbook sets the same variable in the play's 'vars' section. Which variable value takes precedence?

A.Role defaults
B.Inventory group vars
C.Role vars
D.Play vars
AnswerD

Play vars outrank both role defaults and role vars in Ansible's precedence order, sitting above role vars/main.yml and far above defaults/main.yml. Because the play explicitly sets the variable, that value overrides the role's defaults and vars, satisfying the stem's precedence question.

Why this answer

In Ansible, variable precedence is hierarchical, and play vars (set directly in the play's `vars` section) have a higher priority than role defaults and role vars. Specifically, play vars override role vars, which in turn override role defaults. Therefore, when the same variable is defined in all three locations, the play vars value takes precedence.

Exam trap

Red Hat often tests the misconception that role vars override play vars because they are defined inside the role, but the actual precedence places play vars above role vars, so candidates must memorize the full variable precedence order to avoid this trap.

How to eliminate wrong answers

Option A is wrong because role defaults have the lowest precedence among the listed options; they are meant to be easily overridden by any other variable source. Option B is wrong because inventory group vars have a lower precedence than play vars; they are overridden by play vars when both define the same variable. Option C is wrong because role vars have a higher precedence than role defaults but are still overridden by play vars, which sit higher in the variable precedence order.

13
MCQhard

An Ansible playbook uses a rolling update strategy with serial: 1. After the first host is updated, the playbook stops and shows 'PLAY RECAP' with only one host. What is the most likely reason?

A.the playbook has a 'failed_when' condition that stops execution
B.the inventory contains only one host
C.the play uses 'delegate_to' incorrectly
D.the playbook does not have any task that triggers the next batch, and 'serial' only controls concurrency, not retry
AnswerB

Correct. If the inventory contains only one host, the playbook will run on that host and then finish, producing a PLAY RECAP with exactly one host. This is the most likely reason given the behavior described.

Why this answer

The `serial: 1` directive in Ansible limits concurrency to one host at a time, but the playbook will still process all hosts in the inventory. If the playbook stops after the first host and shows PLAY RECAP with only one host, the most likely reason is that the inventory contains only one host. With a single host, the play executes on that host and then finishes.

Option B accurately identifies this scenario.

Exam trap

In the Red Hat RHCE exam, examinees may overthink the behavior of 'serial' and forget to check the inventory size. The trap is assuming 'serial: 1' somehow stops the playbook, whereas the real cause is often a single-host inventory.

How to eliminate wrong answers

Option A is wrong because a `failed_when` condition would cause the playbook to fail on a specific task, but it would not stop the playbook after the first host unless combined with `any_errors_fatal` or `max_fail_percentage`; even then, the 'PLAY RECAP' would show the failed host, not just one host. Option B is wrong because if the inventory contained only one host, the playbook would still run and show a 'PLAY RECAP' with that single host, which is expected behavior, not a reason for stopping after the first host in a multi-host scenario. Option C is wrong because incorrect `delegate_to` usage might cause tasks to run on the wrong host or fail, but it would not cause the playbook to stop after the first host and show a 'PLAY RECAP' with only one host; it would either fail or complete on all hosts.

14
MCQeasy

A playbook uses the 'block' feature to group tasks and includes a 'rescue' section. If a task inside the block fails, what happens?

A.The rescue tasks run, and then the entire playbook fails.
B.The rescue tasks run, and the play continues with the next task after the block.
C.The rescue tasks are ignored and the play fails immediately.
D.The block is re-executed after rescue.
AnswerB

When a task inside a block fails, Ansible executes the rescue section, then continues the play with tasks following the block. The failure is handled rather than aborting the run, so subsequent plays and tasks proceed normally.

Why this answer

In Ansible, when a task inside a `block` fails, the `rescue` section is executed to handle the failure. After the rescue tasks complete successfully, the play continues with the next task after the block, not from the beginning of the block. This behavior allows for error recovery without terminating the entire play.

Exam trap

The trap here is that candidates often confuse `rescue` with a retry mechanism, thinking it re-executes the block, or they assume that any failure in the block immediately fails the entire play, ignoring the rescue capability.

How to eliminate wrong answers

Option A is wrong because after the rescue tasks run, the play does not fail; it continues with the next task after the block, unless the rescue tasks themselves fail. Option C is wrong because the rescue tasks are not ignored; they are specifically designed to run when a task in the block fails, and the play does not fail immediately unless the rescue tasks also fail. Option D is wrong because the block is not re-executed after rescue; the rescue section runs once, and then execution proceeds to the task after the block.

15
Multi-Selectmedium

Which three of the following are valid methods to pass variables to an Ansible playbook at runtime? (Choose three.)

Select 3 answers
A.Using '--extra-vars' command line option.
B.Using '--ask-vault-pass' and storing variables in encrypted files.
C.Using 'environment' directive in the playbook.
D.Using 'vars_prompt' in the playbook.
E.Using '-e @file' to load variables from a JSON file.
AnswersA, D, E

Correct: This directly passes variables or file paths.

Why this answer

The `--extra-vars` (or `-e`) command-line option allows you to pass variables directly to an Ansible playbook at runtime. This overrides any previously defined variables and can accept key=value pairs or load from JSON/YAML files, making it the primary method for runtime variable injection.

Exam trap

The trap here is confusing variable injection methods with authentication or environment configuration; candidates often mistake `--ask-vault-pass` or `environment` for runtime variable passing, when they serve entirely different purposes in Ansible's architecture.

16
MCQeasy

An organization has a set of common tasks used in many playbooks. The tasks are updated frequently. What is the most maintainable way to share them?

A.Create a role and store it in a local directory referenced by ansible.cfg.
B.Copy the task files into each project repository.
C.Package the tasks into a collection and install it via ansible-galaxy.
D.Use include_tasks with a relative path from each playbook.
AnswerC

Collections bundle roles, modules and plugins with versioning, so frequently updated shared tasks can be distributed and pinned via ansible-galaxy. This satisfies the maintainability constraint by centralising updates rather than duplicating task files across playbooks.

Why this answer

Ansible Collections provide a centralized, versioned, and distributable way to package and share tasks, roles, modules, and plugins. Using `ansible-galaxy collection install` allows teams to manage updates from a single source (e.g., Automation Hub or a private Galaxy server), ensuring all playbooks use the latest version without manual file copying or path dependencies.

Exam trap

Red Hat often tests the misconception that local file paths or roles are sufficient for sharing tasks, but the EX294 exam emphasizes centralized, version-controlled distribution via Collections as the most maintainable approach for frequently updated shared content.

How to eliminate wrong answers

Option A is wrong because storing a role in a local directory referenced by `ansible.cfg` (via `roles_path`) ties the tasks to a specific filesystem location, making it difficult to version, distribute, or update across multiple control nodes or CI/CD pipelines. Option B is wrong because copying task files into each project repository leads to duplication, version drift, and increased maintenance overhead when tasks are updated frequently. Option D is wrong because using `include_tasks` with a relative path creates tight coupling to the playbook's directory structure, breaking if the playbook is moved or executed from a different working directory, and offers no versioning or distribution mechanism.

17
MCQeasy

An administrator wants to reuse a set of tasks that configure a firewall across multiple playbooks. Which Ansible feature should be used to achieve this?

A.Create a role for firewall configuration.
B.Add the tasks to the inventory file under a group.
C.Define the tasks in a vars file and include it.
D.Define the tasks as handlers and notify them.
AnswerA

Roles bundle tasks, handlers, defaults and templates into a reusable, structured unit that playbooks can invoke via the roles keyword or include_role. This satisfies the requirement to reuse firewall configuration tasks across multiple playbooks without duplication.

Why this answer

A role is the correct Ansible feature for reusing a set of tasks across multiple playbooks. Roles provide a structured, self-contained directory layout for tasks, handlers, variables, templates, and files, allowing the firewall configuration logic to be packaged once and referenced in any playbook via the `roles:` directive or `import_role`/`include_role` modules.

Exam trap

The trap here is confusing roles with other reusable components like variables or handlers, leading candidates to think that storing tasks in a vars file or using handlers can achieve the same cross-playbook reuse.

How to eliminate wrong answers

Option B is wrong because the inventory file defines hosts and groups, not reusable task logic; adding tasks to an inventory file is syntactically invalid and would not execute them. Option C is wrong because vars files store variables, not tasks; including a vars file with `include_vars` cannot run tasks. Option D is wrong because handlers are special tasks triggered by notifiers only when a change occurs, not designed for general-purpose reuse across playbooks.

18
MCQeasy

Refer to the exhibit. What is the purpose of the 'failed_when' condition?

A.It fails the task only if the return code is non-zero and the error does not indicate 'not installed'.
B.It ensures the task never fails regardless of return code.
C.It fails the task only if the package is installed.
D.It fails the task if the package is not installed.
AnswerA

The failed_when condition overrides Ansible's default failure detection, so the task fails only when the return code is non-zero and the error output does not contain 'not installed'. This prevents a benign absence from being treated as a genuine failure.

Why this answer

The 'failed_when' condition in Ansible allows you to define custom failure criteria for a task. In the exhibit, the condition 'failed_when: result.rc != 0 and "not installed" not in result.stderr' means the task will only be marked as failed if the return code is non-zero AND the error message does not contain the string 'not installed'. This is useful when a command returns a non-zero exit code for expected reasons (e.g., package not found), and you want to treat that as a non-failure.

Exam trap

The trap here is that candidates assume 'failed_when' always causes failure when the condition is true, but they overlook that the condition is a logical AND of two parts, and the second part ('not installed' not in stderr) is a negative check that prevents failure when the expected error message appears.

How to eliminate wrong answers

Option B is wrong because 'failed_when' does not ensure the task never fails; it only defines custom failure conditions, and if the condition evaluates to false, the task may still fail based on the default behavior (non-zero return code). Option C is wrong because the condition does not check whether the package is installed; it checks the return code and the presence of 'not installed' in stderr, not the package installation status itself. Option D is wrong because the condition does not fail the task if the package is not installed; it actually prevents failure when the error indicates 'not installed', so it would not fail in that case.

19
MCQhard

Refer to the exhibit. After the playbook run fails on the 'Verify config' task, what happens to the 'restart service' handler?

A.The handler runs immediately after the failed task.
B.The handler is not executed because the playbook failed before the end of the play.
C.The handler runs on the next playbook run.
D.The handler is executed because it was notified before the failure.
AnswerB

Handlers are deferred until the end of the play, so a failed task aborts the play before that point and the notify never triggers execution. The restart service handler therefore does not run, satisfying the stem's failure-before-end-of-play condition.

Why this answer

Handlers are notified but only run at the end of the play if notified. However, if a subsequent task fails, the playbook stops, and handlers are not executed unless the 'force_handlers' option is set.

20
MCQmedium

A playbook uses the `ansible.builtin.uri` module to interact with a REST API. The API requires a Bearer token that is stored in an encrypted variable file. The playbook must ensure the token is not exposed in logs. Which approach best meets the requirement?

A.Set `ANSIBLE_DEBUG` to false in the environment.
B.Set `no_log: true` on the task that uses the `uri` module.
C.Encrypt the variable file with `ansible-vault` and reference it in the playbook.
D.Use `vars_prompt` to ask for the token at runtime.
AnswerB

The no_log directive prevents the task's output, including any sensitive data like tokens, from being logged or displayed. When set to true on the uri task, Ansible will not show the module arguments or results, which could contain the Bearer token. This is the standard way to protect secrets from being exposed in logs or console output during playbook execution.

Why this answer

To prevent a sensitive token from appearing in logs, the task that uses the token must have no_log set to true. This suppresses all output from that task, including module arguments and results. While vault encrypts the token at rest, it does not prevent logging during execution.

Therefore, no_log is the necessary control in this scenario.

Exam trap

The trap here is assuming that encrypting the variable file with ansible-vault automatically prevents the token from being logged.

21
MCQeasy

An automation engineer wants to run a playbook only on hosts that belong to both the 'webservers' group and the 'production' group. Which inventory grouping method achieves this?

A.webservers:&production
B.webservers:production
C.webservers:!production
D.webservers+,production
AnswerA

The :& intersection pattern targets hosts present in both groups simultaneously, matching the requirement to run only where webservers and production overlap. Other patterns like :! or union would include hosts outside the intended set.

Why this answer

In Ansible, the '&' operator is used to intersect groups. 'webservers:&production' targets hosts that are in both the 'webservers' and 'production' groups. Option B is wrong because 'webservers:production' uses ':' which is a union operator, meaning hosts in either group. Option C is wrong because 'webservers:!production' uses '!' to exclude hosts in production.

Option D is wrong because 'webservers+,production' is not a valid inventory pattern; Ansible does not support '+' for group intersection.

22
MCQeasy

A developer reports that a role's behavior is not as expected. They set a variable in the playbook's vars section, but the role still uses the value from its vars/main.yml. Which of the following explains this issue?

A.vars defined in the playbook have higher precedence than those in roles/vars/main.yml
B.vars defined in group_vars override both play and role vars
C.the playbook must use include_vars after the role to override
D.vars defined in roles/vars/main.yml have higher precedence than those in the playbook's vars section
AnswerD

Correct: role vars override play vars.

Why this answer

In Ansible, variable precedence is hierarchical, and role defaults (roles/role_name/defaults/main.yml) have the lowest precedence, while role vars (roles/role_name/vars/main.yml) have a higher precedence than playbook-level vars. Since the developer set the variable in the playbook's vars section, but the role still uses the value from its vars/main.yml, this indicates that vars defined in roles/vars/main.yml override those in the playbook's vars section, making option D correct.

Exam trap

The trap here is that candidates often confuse role defaults (defaults/main.yml) with role vars (vars/main.yml), assuming both are easily overridden by playbook vars. In Red Hat Ansible Automation Platform, role vars have higher precedence than playbook vars, making them effectively 'hardcoded' unless overridden by even higher precedence sources like extra vars or set_facts.

How to eliminate wrong answers

Option A is wrong because vars defined in the playbook have lower precedence than those in roles/vars/main.yml, not higher. Option B is wrong because group_vars have a lower precedence than both play vars and role vars, so they cannot override both; in fact, role vars override group_vars. Option C is wrong because include_vars is used to load variables from a file at runtime, but it does not change the inherent precedence; the role's vars/main.yml would still take precedence over playbook vars regardless of when include_vars is used.

23
MCQmedium

An organization uses separate network hops that require different SSH usernames for different inventory groups. Which Ansible configuration approach ensures each group uses the correct SSH user without duplicating playbooks?

A.Create a group_vars directory with a file named after the group containing ansible_user.
B.Specify the SSH user in the inventory file for each host.
C.Set the ansible_user variable in ansible.cfg.
D.Define ansible_user in the playbook using vars.
AnswerA

Group variables are loaded automatically for hosts in the matching group, so placing ansible_user in group_vars/<group>.yml supplies the correct SSH username per inventory group. One playbook then runs against all groups without hard-coded credentials or duplication.

Why this answer

Group variables in Ansible are defined in group_vars/<group_name>.yml, and variables set there apply to all hosts in that group. Placing ansible_user in a group-specific file ensures each inventory group uses its correct SSH username without duplicating playbook logic. This is the idiomatic Ansible way to scope connection variables per group.

Exam trap

The trap is thinking ansible.cfg or playbook vars can scope connection settings per group; the exam tests whether you know that group_vars is the correct precedence layer for group-specific SSH users.

How to eliminate wrong answers

Option B is wrong because setting ansible_user per host in the inventory works but duplicates configuration and does not scale when groups share a user. Option C is wrong because ansible.cfg sets global defaults and cannot vary ansible_user per inventory group. Option D is wrong because defining ansible_user in playbook vars applies to the play, not per group, and would require conditional logic or multiple plays.

24
MCQmedium

An Ansible playbook uses async and poll to run a long-running task. The task reports 'async task did not complete within the requested time'. Which of the following is the most likely cause?

A.the poll interval is set too long
B.the async timeout value is set too short for the task duration
C.the async task requires become: yes
D.the host is unreachable
AnswerB

With async, the controller waits up to the poll interval for completion; if the task exceeds the configured async timeout, Ansible reports that it did not complete in time. Extending the timeout or increasing poll resolves this.

Why this answer

The error 'async task did not complete within the requested time' indicates that the async timeout value (set via the async parameter) is too short for the actual task duration. The poll interval does not affect the timeout; it only controls how often Ansible checks the task status. Option B is correct because increasing the async value allows the task more time to complete.

25
MCQhard

Refer to the exhibit. The playbook copies all .conf files from the control node to host1. If the playbook runs again on the same host without any changes, which task status is expected?

A.The task will fail because the destination directory already contains files.
B.All items will show 'ok' because files are identical.
C.The task will be skipped because the files already exist.
D.All items will show 'changed'.
AnswerB

The copy module compares checksums, so identical .conf files on host1 produce no transfer and report 'ok'. This satisfies the stem's constraint of a second run with no changes, where idempotence means unchanged state yields 'ok' rather than 'changed'.

Why this answer

Ansible's `copy` module is idempotent: when the source and destination files are identical (same content and checksum), the module reports `ok` rather than `changed`. On a second run with no source changes, all items in the loop will show `ok` because Ansible compares checksums and determines no copy is needed. This is the core idempotency guarantee of Ansible modules.

Exam trap

The trap is assuming that re-running a copy task always reports `changed` or `skipped` — candidates forget that Ansible's checksum-based idempotency produces `ok` for identical files.

How to eliminate wrong answers

Option A is wrong because the `copy` module overwrites destination files by default and does not fail when files already exist — it simply compares and skips if identical. Option C is wrong because the task is not skipped; `skipped` status only occurs when a `when` condition evaluates to false or the module explicitly skips, not when files are unchanged. Option D is wrong because `changed` would only appear if the file content differed from the source; identical files produce `ok`, not `changed`.

26
MCQmedium

A playbook uses a loop over a list of packages to ensure they are installed. However, the playbook runs slowly because each package is processed individually. Which optimization technique should be used to improve performance?

A.Pass the entire list to the package module's 'name' parameter instead of looping.
B.Use with_items instead of loop; with_items is faster.
C.Set the async parameter on the looped task to run packages in parallel.
D.Use the serial keyword at the play level to increase parallelism.
AnswerA

Passing the whole list to the package module's name parameter lets Ansible invoke the underlying package manager once for all packages, rather than spawning a separate module execution per item. This removes per-iteration overhead, directly addressing the slow loop described in the stem.

Why this answer

Ansible's package modules (such as yum, apt, or dnf) accept a list of packages in the 'name' parameter. Passing the entire list in a single task eliminates the overhead of multiple task executions, SSH connection reuse, and module setup/teardown that occur with each iteration in a loop. This reduces the number of Ansible task runs from N to 1, significantly improving performance.

Exam trap

The trap here is that candidates often confuse task-level parallelism (which Ansible does not natively support for loops) with host-level parallelism (controlled by 'serial' or 'strategy'), leading them to select options that seem to increase parallelism but do not apply to a single-host loop.

How to eliminate wrong answers

Option B is wrong because 'with_items' is a legacy loop syntax that is functionally equivalent to 'loop' and does not provide any performance advantage; both still execute the task once per item. Option C is wrong because setting 'async' on a looped task does not run packages in parallel; it only allows the task to run in the background with polling, but each iteration still runs sequentially. Option D is wrong because the 'serial' keyword controls the number of hosts processed at a time in a play, not the parallelism of tasks within a single host; it does not affect how a loop over packages is executed on a given host.

27
MCQhard

An administrator is writing a playbook that must execute a task only when a file exists on the remote host. They use the `stat` module to check the file and register the result. Which conditional expression should be used to run a subsequent task based on the file's existence?

A.`when: stat_result.exists`
B.`when: stat_result.stat.is_exists`
C.`when: stat_result.is_exists`
D.`when: stat_result.stat.exists`
AnswerD

The `stat` module registers a variable that contains a `stat` key, which is a dictionary with keys such as `exists`, `isreg`, etc. Therefore, the correct conditional to check if the file exists is `stat_result.stat.exists`. This is the standard way to use the result of the `stat` module.

Why this answer

The `stat` module returns a dictionary where the `stat` key contains the file status information. The correct way to check if the file exists is to reference `stat_result.stat.exists`. This ensures the conditional evaluates correctly based on the module's output.

Exam trap

The trap here is forgetting that the `stat` module nests its results under a `stat` key; many mistakenly use `stat_result.exists` directly.

28
MCQmedium

A playbook uses a variable named `db_port` that must be defined by the user at runtime, but should fall back to 5432 if the user does not provide it. Which approach ensures this behavior without failing the play when the variable is undefined?

A.Use the `default` filter: `{{ db_port | default(5432) }}`.
B.Define `db_port` in `group_vars/all.yml` with a value of 5432.
C.Reference `db_port` directly and set `ignore_errors: true` on the task.
D.Use `vars_prompt` to ask for `db_port` with a `default` keyword set to 5432.
AnswerA

The `default` filter returns the specified fallback value when the variable is undefined, which directly satisfies the requirement. It does not error on undefined variables, so the play continues. Using it in a template or module argument such as `port: "{{ db_port | default(5432) }}"` provides a safe default. This is the idiomatic Ansible way to handle optional variables with fallback values.

Why this answer

The `default` filter is the correct mechanism because it supplies a fallback only when the variable is undefined, allowing user-provided values to take precedence. It avoids interactive prompts and precedence conflicts, and it works in any templated context. The other options either force a value, require interaction, or fail to provide a value at all.

Exam trap

The trap here is assuming that defining a variable in group_vars or using vars_prompt with a default is equivalent to a runtime fallback filter.

29
MCQmedium

A playbook includes a role that has a task notifying a handler defined within the role. Another task in the play, outside the role, also notifies the same handler by name. After running the playbook, the administrator notices that the handler runs only once. What is the reason for this behavior?

A.Handlers are executed immediately when notified, so the first notification triggers it and the second is ignored.
B.Handlers are executed only once per play, even if notified multiple times.
C.The handler runs only if the notifying task reports a changed status, and both tasks reported 'ok'.
D.The handler is scoped to the role and cannot be notified from outside the role.
AnswerB

Ansible handlers are designed to run only once at the end of a play, regardless of how many times they are notified. This prevents redundant service restarts. Even if multiple tasks notify the same handler, it will execute a single time after all tasks complete, unless explicitly flushed.

Why this answer

Handlers in Ansible are run once per play at the end, even if notified multiple times. This is by design to avoid multiple restarts of a service. The handler's scope is not limited to the role; it can be notified from anywhere in the play.

The correct explanation is that handlers are deduplicated and executed once.

Exam trap

The trap here is thinking that handlers run immediately upon notification or that they are scoped to roles. In fact, they are queued and run once at the end of the play.

30
MCQeasy

A playbook must execute a task on a host that is not part of the inventory, such as a temporary cloud instance. The task should run on that host without modifying the inventory file. Which directive should be used?

A.add_host
B.local_action
C.delegate_to
D.include_vars
AnswerA

The add_host module dynamically adds a host to the in-memory inventory during playbook execution. It allows you to target a host that is not in the static inventory, and subsequent plays can use it. This meets the requirement without editing the inventory file.

Why this answer

The add_host module is designed to add hosts to the in-memory inventory at runtime, enabling tasks to run on hosts not present in the static inventory. Other directives like delegate_to, local_action, and include_vars serve different purposes and do not add hosts.

Exam trap

The trap here is confusing delegate_to with add_host. delegate_to requires the host to already exist in the inventory, while add_host creates the host entry dynamically.

31
Multi-Selecthard

An automation engineer is using Ansible to manage a fleet of servers. They need to ensure that certain tasks run only on hosts that match specific criteria. Which two of the following are valid ways to limit task execution based on host facts? (Choose two.)

Select 2 answers
A.Use the 'group_by' module to create dynamic groups based on facts, then target those groups in subsequent plays.
B.Use the 'tags' keyword to tag tasks with fact values, then run the playbook with --tags to filter.
C.Use the 'delegate_to' directive with a fact-based expression to delegate tasks to matching hosts.
D.Use the 'when' conditional with a fact variable, such as when: ansible_facts['os_family'] == 'RedHat'.
E.Use the 'run_once' keyword with a fact-based condition to run the task only on the first matching host.
AnswersA, D

The group_by module creates new inventory groups based on facts, such as os_family. You can then write plays that target these dynamic groups. This is a valid approach to limit task execution to hosts matching specific fact criteria, though it requires a separate play or playbook run.

Why this answer

The 'when' conditional and the 'group_by' module are both valid methods to limit task execution based on host facts. The 'when' clause evaluates facts per host, while 'group_by' dynamically creates groups that can be targeted in subsequent plays. Tags, delegate_to, and run_once do not provide fact-based filtering of hosts.

Exam trap

The trap here is assuming that tags or run_once can be used for fact-based filtering. Tags are static, and run_once ignores facts, so they cannot select hosts based on facts.

32
Multi-Selecthard

Which TWO of the following are correct about Ansible Vault?

Select 2 answers
A.vault encryption is irreversible
B.vault encrypted files cannot be edited in place
C.the vault password can be provided via the '--vault-password-file' option
D.vault can encrypt only specific variable values within a file
E.the vault id can be specified to use multiple vault passwords
AnswersC, E

Correct: this is a common way to automate vault decryption.

Why this answer

The `--vault-password-file` option allows Ansible to read the vault password from a file, which is a standard method for providing the password non-interactively, especially in automation scripts or CI/CD pipelines. This avoids the need for manual password entry and supports secure password management.

Exam trap

In the RHCE exam, candidates often assume vault encryption is irreversible or that it can encrypt only specific values within a file, confusing it with `ansible-vault encrypt_string` which encrypts a single string, not partial file encryption.

33
MCQmedium

A playbook uses the 'block' and 'rescue' keywords to handle errors. The block contains three tasks. The first task fails. What happens next?

A.The rescue section runs and retries the failed task.
B.The rescue section runs immediately after the failure.
C.The playbook fails with an error message.
D.The remaining tasks in the block run, then the rescue section runs.
AnswerB

Ansible aborts the remaining tasks inside the block as soon as one fails, then transfers execution to the rescue section, which runs immediately. The rescue handles the error, allowing the playbook to continue rather than halting.

Why this answer

In Ansible, when a task inside a `block` fails, the `rescue` section is executed immediately after the failure, without running any remaining tasks in the block. This is analogous to a try-catch mechanism in programming: the block is the 'try', and the rescue is the 'catch'. Option B correctly describes this behavior.

Exam trap

The trap here is that candidates often confuse `block`/`rescue` with a simple retry mechanism or assume that all tasks in the block must complete before error handling, but Ansible's behavior is to immediately jump to rescue on the first failure.

How to eliminate wrong answers

Option A is wrong because the rescue section does not retry the failed task; it runs a separate set of tasks to handle the error, and retry logic would require a `until` loop or `retries` parameter on the task itself. Option C is wrong because the playbook does not fail immediately; the rescue section is designed to catch the error and continue execution, preventing a playbook failure unless the rescue itself fails. Option D is wrong because the remaining tasks in the block are skipped once a task fails; the rescue runs immediately, not after the block completes.

34
Multi-Selectmedium

Which THREE of the following are valid attributes of the ansible.builtin.service module?

Select 3 answers
A.state
B.enabled
C.pattern
D.name
E.runlevel
AnswersA, B, D

Correct: state controls whether the service is started/stopped.

Why this answer

The `state` attribute is a core parameter of the `ansible.builtin.service` module, used to define the desired service status (e.g., `started`, `stopped`, `restarted`, `reloaded`). This directly controls the service's runtime state on the target system.

Exam trap

The trap here is that candidates confuse module-specific parameters (like `pattern` for `systemd` or `runlevel` for legacy init scripts) with the generic `service` module, which only supports `state`, `enabled`, `name`, and a few others like `arguments` and `use`.

35
Multi-Selecteasy

Which two statements about Ansible roles are correct? (Select exactly 2.)

Select 2 answers
A.Roles must have a meta/main.yml file.
B.Roles are a type of playbook.
C.Roles can include tasks, handlers, variables, and defaults.
D.Roles cannot be used with include_role.
E.Roles can be installed from Galaxy.
AnswersC, E

A role's directory structure defines separate subdirectories for tasks, handlers, variables and defaults, each loaded automatically during role execution. This satisfies the stem's requirement for a correct structural statement, distinguishing roles from loose playbooks that must declare such content inline.

Why this answer

Option C is correct because an Ansible role is a structured directory layout that can bundle tasks (tasks/main.yml), handlers (handlers/main.yml), variables (vars/main.yml), and defaults (defaults/main.yml) along with files, templates, and meta, allowing reusable automation content. Option E is correct because roles can be installed from Ansible Galaxy using the ansible-galaxy role install command (e.g., ansible-galaxy install geerlingguy.nginx), which fetches roles from Galaxy or a configured requirements file. Option A is not required: meta/main.yml is optional and only needed when declaring role dependencies or Galaxy metadata.

Option B is inaccurate because a role is a reusable content structure invoked by a playbook via roles or include_role/import_role, not itself a playbook. Option D is false because include_role is specifically used to dynamically include roles at runtime.

Exam trap

EX294 often tests the misconception that roles require a meta/main.yml file or that they are a type of playbook, when in fact meta is optional and roles are separate reusable components invoked by playbooks.

36
MCQmedium

An Ansible automation team is designing a playbook to manage network devices. They need to ensure that the playbook can handle transient network failures by retrying failed tasks a specific number of times with a delay between retries. Which approach should they use?

A.Set `max_fail_percentage` in the play to 0 and use `ignore_errors: yes` with a rescue block.
B.Use the `throttle` keyword to limit concurrent tasks and rely on idempotency.
C.Set `serial: 1` on the play to ensure only one host is processed at a time and rely on idempotency.
D.Use the `until` loop with `retries` and `delay` parameters on the task.
AnswerD

The until loop repeats a task until its condition succeeds, with retries setting the maximum attempts and delay setting the pause between them. This directly handles transient network failures by retrying failed tasks as specified.

Why this answer

The `until` loop with `retries` and `delay` parameters is the correct approach because it allows a task to be retried a specified number of times with a configurable pause between attempts, directly addressing transient network failures. This is a built-in Ansible feature for handling intermittent issues without additional error-handling constructs.

Exam trap

The trap here is that candidates confuse concurrency controls (`serial`, `throttle`) or error-handling directives (`ignore_errors`, `max_fail_percentage`) with the retry mechanism, which is specifically implemented via the `until` loop with `retries` and `delay` parameters.

How to eliminate wrong answers

Option A is wrong because `max_fail_percentage` controls the percentage of hosts that can fail before the play aborts, not task retries; combining `ignore_errors: yes` with a rescue block would suppress errors but not implement retry logic. Option B is wrong because the `throttle` keyword limits the number of concurrent task executions, which is unrelated to retrying failed tasks. Option C is wrong because `serial: 1` processes hosts one at a time to control rolling updates or concurrency, not to retry tasks on failure.

37
MCQhard

A playbook uses an Ansible collection that includes a custom module. The module's documentation is missing. What is the best way to locate the module's source code?

A.Run ansible-doc <module name>.
B.Search the Ansible Galaxy website.
C.Navigate to the collection's plugin directory on the control node.
D.Look in the roles directory.
AnswerC

Ansible installs collections under the control node's collection path, with each module stored as a Python file inside the collection's plugins/modules directory. Reading that file reveals the actual implementation, which is the only reliable source when the module's generated documentation is absent.

Why this answer

Ansible collections store custom modules in the 'plugins/modules' directory within the collection's installation path on the control node. Navigating to that directory allows you to view the module's source code directly, which is the most reliable way to locate it when documentation is missing.

Exam trap

EX294 often tests the assumption that ansible-doc always works, even when documentation is missing, leading candidates to choose that option instead of locating the source file.

How to eliminate wrong answers

Option A is wrong because ansible-doc relies on documentation strings within the module; if documentation is missing, ansible-doc may not display useful information or may fail. Option B is wrong because searching Ansible Galaxy might find the collection, but it does not guarantee access to the specific module's source code, especially if the collection is private or not published. Option D is wrong because the roles directory contains roles, not collection modules; custom modules from collections are not stored there.

38
MCQeasy

An administrator wants to reuse a set of tasks across multiple playbooks. Which Ansible approach is most appropriate?

A.Encrypting the tasks with Ansible Vault.
B.Creating a role with tasks in tasks/main.yml.
C.Using ansible-doc to document the tasks.
D.Writing a custom module in Python.
AnswerB

A role packages tasks in tasks/main.yml so any playbook can invoke the same reusable unit through the roles keyword, avoiding duplicated task definitions. This satisfies the requirement to reuse one task set across multiple playbooks without copying content.

Why this answer

Roles are the standard Ansible mechanism for packaging and reusing tasks, variables, handlers, and other automation content across multiple playbooks. By placing tasks in a role's `tasks/main.yml`, the administrator can reference that role in any playbook using the `roles:` directive, enabling clean, modular reuse without duplication.

Exam trap

The trap here is that candidates may confuse Ansible Vault's encryption capability with code reuse, or think that writing a custom module is a simpler way to bundle tasks, when in fact roles are the explicit, built-in solution for task reuse in Ansible.

How to eliminate wrong answers

Option A is wrong because Ansible Vault encrypts sensitive data (e.g., passwords, keys) but does not provide a mechanism to reuse tasks across playbooks; it is a security feature, not a code reuse feature. Option C is wrong because `ansible-doc` is a command-line tool that displays documentation for installed modules and plugins; it does not enable task reuse or packaging. Option D is wrong because writing a custom Python module extends Ansible's capabilities with new, atomic actions, but it is not the intended or most appropriate way to reuse a set of tasks; roles are designed specifically for that purpose.

39
Matchingmedium

Match each Ansible fact variable to its description.

Drag a concept onto its matching description — or click a concept then click the description.

Concepts
Matches

Fully qualified domain name

OS family (e.g., RedHat)

Total memory in MB

Number of CPU cores

Default IPv4 interface info

Why these pairings

The correct matches are: ansible_distribution -> OS distribution name, ansible_os_family -> OS family, ansible_architecture -> CPU architecture. Common confusions include mistaking memory units (MB vs GB) and hostname vs IP address.

40
MCQeasy

Refer to the exhibit. An administrator wants to view the decrypted value of 'db_password' without modifying the file. Which command should be used?

A.ansible-vault rekey file.yml
B.ansible-vault decrypt file.yml
C.ansible-vault view file.yml
D.ansible-vault edit file.yml
AnswerC

ansible-vault view decrypts and displays the file contents to standard output without altering the encrypted file on disk, satisfying the requirement to read db_password without modification. The edit subcommand would decrypt and re-encrypt, risking changes.

Why this answer

The `ansible-vault view` command decrypts the file in memory and displays its contents to stdout without modifying the encrypted file on disk. This is the correct choice because the administrator only needs to see the decrypted value of 'db_password' and does not want to change the file.

Exam trap

The trap here is that candidates often confuse `ansible-vault view` with `ansible-vault decrypt`, mistakenly thinking they must permanently decrypt the file to see its contents, when `view` provides a read-only decrypted output without altering the file.

How to eliminate wrong answers

Option A is wrong because `ansible-vault rekey` changes the vault password used to encrypt the file, not decrypt or display its contents. Option B is wrong because `ansible-vault decrypt` permanently decrypts the file and writes the plaintext to disk, which modifies the file. Option D is wrong because `ansible-vault edit` decrypts the file, opens it in an editor, and re-encrypts it upon saving, which modifies the file even if no changes are made.

41
MCQeasy

An administrator needs to run a playbook that applies a configuration only to hosts that have a specific fact, `ansible_processor_vcpus`, greater than 4. The playbook should skip hosts that do not meet this condition. Which approach should be used?

A.Set `gather_facts: no` and use a custom fact to check vCPU count.
B.Use the `serial` keyword to limit execution to hosts with more than 4 vCPUs.
C.Create a dynamic inventory script that only includes hosts with more than 4 vCPUs.
D.Add a `when` condition to each task: `when: ansible_processor_vcpus > 4`.
AnswerD

Using a when condition on tasks that checks ansible_processor_vcpus > 4 is the straightforward way to conditionally execute tasks based on a fact. Ansible gathers facts by default, so ansible_processor_vcpus is available. This ensures that only hosts with more than 4 vCPUs run the configuration tasks, while others skip them.

Why this answer

The most direct method to conditionally run tasks based on a fact is to use a when condition on the tasks. Since Ansible gathers facts by default, ansible_processor_vcpus is available, and the condition will evaluate correctly per host. This ensures that only hosts with more than 4 vCPUs execute the configuration, while others skip it.

Exam trap

The trap here is thinking that the serial keyword can filter hosts based on facts, when it only controls batch size.

42
MCQhard

A playbook uses a task with 'delegate_to: localhost' to generate a report file. The task must run only once, even if the play targets multiple hosts. Which keyword should be added to the task to ensure it executes only on the first host?

A.throttle: 1
B.run_once: true
C.any_errors_fatal: true
D.serial: 1
AnswerB

run_once: true forces the task to execute only on the first host in the play, and any results are applied to all hosts. Combined with delegate_to: localhost, the task runs once on the control node, producing a single report. This avoids redundant execution when the play targets many hosts.

Why this answer

The run_once keyword ensures the task is executed only on the first host in the play, regardless of how many hosts are targeted. When combined with delegate_to: localhost, the task runs once on the control node, generating a single report. Other keywords like serial, throttle, or any_errors_fatal affect batching, concurrency, or error handling, not single execution.

Exam trap

The trap here is confusing serial, which controls play batching, with run_once, which controls task execution frequency. serial does not prevent a task from running on every host.

43
Multi-Selecthard

Which THREE of the following are valid uses of the 'ansible.builtin.include_role' module?

Select 3 answers
A.Pass variables to the included role using the 'vars' keyword.
B.Include a role from a collection by specifying 'namespace.collection.role_name'.
C.Dynamically set the role name using a variable without the 'name' parameter.
D.Conditionally include a role based on a variable.
E.Apply tags to all tasks within the included role.
AnswersA, B, D

Variables can be passed to the role via the 'vars' parameter.

Why this answer

The 'ansible.builtin.include_role' module supports the 'vars' keyword to pass variables directly to the included role. This allows you to override or supply role variables at the point of inclusion, which is a common pattern for reusing roles with different configurations.

Exam trap

The trap here is that candidates often confuse 'include_role' with 'import_role', assuming that tags applied to the include statement will automatically apply to all tasks inside the role, but in Ansible, tags on a dynamic include only affect the include task itself, not the included tasks.

44
MCQmedium

An automation engineer must ensure that a task in a playbook runs only once across all hosts in the play, even though the play targets 50 web servers. The task creates a shared DNS record on an external service. Which approach should be used?

A.Set `serial: 1` on the play.
B.Use `delegate_to: localhost` on the task.
C.Add `run_once: true` to the task.
D.Add `throttle: 1` to the task.
AnswerC

The `run_once` directive forces a task to execute on a single host in the current batch, and the results are applied to all hosts in the play. This ensures the DNS record is created only once, preventing duplicate entries and unnecessary API calls when scaling across many servers.

Why this answer

The `run_once` directive ensures that a task is executed only on the first host in the play, and the results are applied to all hosts. This is ideal for actions that should not be repeated per host, such as creating a shared resource. Other options either still execute per host or only control concurrency.

Exam trap

The trap here is assuming that `delegate_to: localhost` prevents multiple executions, when it actually runs the task once per host on the control node.

45
MCQeasy

An administrator needs to securely store a database password used across multiple roles in a shared repository. Which approach is recommended?

A.Use ansible-vault to encrypt the password string and store it in a file, then include_vars.
B.Use a lookup plugin to fetch from a secrets manager.
C.Store the password in an environment variable on the controller.
D.Hardcode the password in the playbook and use .gitignore.
AnswerA

ansible-vault encrypts the password string at rest, and include_vars loads the decrypted variable into playbooks at runtime, so multiple roles in the shared repository reference one protected secret. This satisfies secure storage without exposing plaintext credentials in version control.

Why this answer

Ansible-vault encrypts sensitive data at rest using AES-256, and the encrypted file can be safely stored in a shared repository. The `include_vars` module then decrypts the file at runtime when the vault password is provided, allowing multiple roles to access the password without exposing it in plaintext.

Exam trap

The trap here is that candidates may confuse 'secure storage in a repository' with external secrets managers (Option B), but the question explicitly limits the context to a shared repository, making ansible-vault the correct built-in solution.

How to eliminate wrong answers

Option B is wrong because while a lookup plugin to fetch from a secrets manager is a valid approach, the question specifies a 'shared repository' (e.g., Git), not an external secrets management service; the recommended approach for repository-based storage is ansible-vault. Option C is wrong because storing the password in an environment variable on the controller is insecure—environment variables can be leaked via process listings, logs, or debugging tools, and they are not encrypted at rest. Option D is wrong because hardcoding the password in the playbook and using .gitignore does not prevent the password from being visible in the playbook file itself, and .gitignore only prevents accidental commits, not exposure to anyone with access to the file system.

46
MCQhard

Refer to the exhibit. The playbook fails with an error about the package list. What is the issue?

A.The variable 'packages' is not accessible because it is defined in a vars_file.
B.The variable 'packages' is being converted to a string by the Jinja2 template, resulting in a list literal string.
C.The 'yum' module requires the 'name' parameter to be a comma-separated string, not a list.
D.The 'yum' module should use 'pkg' instead of 'name'.
AnswerB

Using "{{ packages }}" produces a string representation of the list. The correct approach is to use `name: "{{ item }}"` with a loop or pass the list directly without quotes.

Why this answer

The yum module expects a list of strings or a comma-separated string. The variable 'packages' is a list, but when used with 'name: "{{ packages }}"', Jinja2 converts it to a string representation like "['httpd', 'mariadb-server', 'php']". The yum module does not accept that format; it needs a proper list or comma-separated string.

47
Multi-Selectmedium

Which three methods can be used to pass variables to an Ansible playbook? (Select exactly 3.)

Select 3 answers
A.In the ansible.cfg file.
B.In the role's vars/main.yml.
C.In the playbook's vars_files directive.
D.In the inventory file variables.
E.Using the --extra-vars command line option.
AnswersC, D, E

vars_files includes YAML/JSON files with variables.

Why this answer

The `vars_files` directive in a playbook allows you to specify external YAML or JSON files containing variables, which are then merged into the play's variable scope at runtime. This is a standard method for passing variables to a playbook, as it separates variable definitions from the playbook logic.

Exam trap

The trap here is that candidates often confuse role-level variable files (like `vars/main.yml`) with playbook-level variable passing methods, or mistakenly think that `ansible.cfg` can hold variables, when in fact it only holds configuration directives.

48
MCQhard

A playbook uses the 'include_tasks' module to dynamically include tasks based on a variable. The playbook runs successfully on some hosts but fails on others with a 'template error' message. What is the most likely cause?

A.The included task file does not exist on the control node.
B.The variable used in the 'include_tasks' path has a Jinja2 template error.
C.The included task file has incorrect permissions.
D.The included tasks contain a syntax error.
AnswerB

A Jinja2 template error in the variable used to build the include_tasks path renders an invalid filename on some hosts, causing the failure. This satisfies the scenario where the same playbook succeeds elsewhere because that variable resolves cleanly.

Why this answer

The 'include_tasks' module dynamically resolves the path to a task file using a variable. If that variable contains a Jinja2 template error (e.g., undefined variable, syntax mistake, or filter misuse), Ansible will fail with a 'template error' message during the variable expansion phase, before the task file is even loaded. This explains why the error occurs only on hosts where the variable's value or context triggers the template failure.

Exam trap

The trap here is that candidates often confuse the source of the template error, assuming it comes from the content of the included tasks (option D) rather than from the variable used in the include path itself, which is evaluated before the included file is even accessed.

How to eliminate wrong answers

Option A is wrong because if the included task file does not exist on the control node, Ansible would produce a 'file not found' or 'could not find or access' error, not a 'template error'. Option C is wrong because file permissions on the control node affect whether Ansible can read the file, but a permissions issue would result in a 'permission denied' error, not a Jinja2 template error. Option D is wrong because a syntax error inside the included tasks would cause a playbook failure when those tasks are parsed or executed, but the error message would be a YAML or Ansible syntax error, not a 'template error' from the include path resolution.

49
Multi-Selectmedium

Which TWO statements about Ansible collections are correct?

Select 2 answers
A.Collections cannot be versioned.
B.Collections provide a way to package and distribute Ansible content.
C.Collections replace the need for inventory files.
D.Collections can only contain modules and roles.
E.Collections can be published to Ansible Galaxy or Automation Hub.
AnswersB, E

Collections bundle roles, modules, plugins and playbooks into a single distributable unit, replacing the older role-only packaging model. This packaging capability directly satisfies the stem's requirement that collections distribute Ansible content in a portable, versioned form.

Why this answer

Option B is correct because Ansible collections are the standard packaging format for distributing Ansible content, bundling modules, roles, plugins, playbooks, and documentation into a single installable unit that can be shared via namespaces. Option E is correct because collections can be published to and installed from public Ansible Galaxy or Red Hat Automation Hub (and private Automation Hub), typically using commands like 'ansible-galaxy collection install' with a namespace.collection name. Option A is incorrect because collections are versioned using semantic versioning (e.g., 1.2.0) in their galaxy.yml and requirements files.

Option C is incorrect because inventory files define managed hosts and remain necessary; collections do not replace them. Option D is incorrect because collections can contain many content types beyond modules and roles, including plugins, module utilities, and documentation.

Exam trap

Red Hat often tests the misconception that collections are limited to modules and roles, but the trap here is that collections can also include plugins, playbooks, and documentation, making option D a common distractor.

50
MCQhard

A company has a large infrastructure with over 1000 servers. They run a playbook that configures NTP on all servers. The playbook takes over 30 minutes due to sequential execution. The team wants to reduce execution time. Which approach should they take?

A.Use serial: 10 to batch hosts.
B.Set forks: 50 and strategy: free.
C.Use include_tasks to parallelize tasks.
D.Use ansible-pull on each server.
AnswerB

Raising forks lets Ansible run the play across 50 hosts concurrently instead of sequentially, and the free strategy lets each host proceed independently rather than waiting at task barriers. Together these cut wall-clock time across the 1000-server fleet.

Why this answer

Ansible's default forks value is 5, meaning only five hosts are configured concurrently, which explains the 30-minute runtime across 1000 servers. Raising forks to 50 increases parallelism, and the free strategy lets each host proceed through tasks independently without waiting for all hosts to finish each task, further reducing wall-clock time.

Exam trap

The trap is choosing serial thinking it means 'more parallel'; serial actually throttles batch size, and the exam expects you to know forks and strategy are the real parallelism levers.

How to eliminate wrong answers

Option A is wrong because serial: 10 limits execution to batches of 10 hosts, which reduces parallelism and would make the playbook slower, not faster. Option C is wrong because include_tasks is a static/dynamic task inclusion mechanism; it does not parallelize execution across hosts. Option D is wrong because ansible-pull inverts the model to have each host pull its own configuration, which changes the architecture but does not directly address the sequential execution bottleneck in the existing push-based playbook.

51
MCQeasy

A team wants to ensure that a sensitive variable, such as a database password, is not printed when ansible-playbook runs with -v (verbose). What is the best method to achieve this?

A.Set the password as an environment variable on the control node.
B.Store the password in a file with 0600 permissions and use lookup('file', ...).
C.Use the 'no_log: true' directive on the task.
D.Use the 'ansible-vault encrypt_string' command and reference the variable from a vault file.
AnswerC

The no_log: true directive suppresses a task's output, including variable values, from verbose ansible-playbook runs. Applying it to the task handling the database password prevents that sensitive value being printed at -v, directly meeting the stem's requirement.

Why this answer

The `no_log: true` directive explicitly prevents Ansible from printing the value of any variable used in that task to the console, even when verbosity is increased with `-v`. This is the most direct and secure method to ensure sensitive data like passwords are not exposed in output logs, as it overrides the default logging behavior at the task level.

Exam trap

Red Hat often tests the misconception that encrypting data at rest (e.g., with vault or file permissions) is sufficient to prevent exposure during execution, but the real risk is runtime output in verbose logs, which only `no_log: true` addresses.

How to eliminate wrong answers

Option A is wrong because setting the password as an environment variable on the control node does not prevent Ansible from printing its value when the task uses it; the variable's content will still be displayed in verbose output unless explicitly suppressed. Option B is wrong because using `lookup('file', ...)` to read a password from a file with 0600 permissions only protects the file at rest, but the variable's value will still be printed in verbose output when the task runs. Option D is wrong because `ansible-vault encrypt_string` encrypts the variable at rest, but when the variable is decrypted and used in a task, its value will still be printed in verbose output unless `no_log: true` is also applied.

52
MCQmedium

Refer to the exhibit. An Ansible playbook contains the following block structure. If the task inside the block fails, which of the following describes the execution order of the rescue and always sections?

A.Only always runs.
B.Only rescue runs.
C.Rescue runs, then always.
D.Always runs, then rescue.
AnswerC

When a task inside a block fails, Ansible transfers control to the rescue section, executing its tasks to handle the error. After rescue completes, the always section runs regardless of success or failure, ensuring cleanup tasks execute. This matches Ansible's documented block error-handling flow, satisfying the stem's requirement to describe execution order.

Why this answer

In Ansible, when a task inside a block fails, the rescue section executes to handle the failure, and then the always section runs unconditionally. This ensures that cleanup or finalization tasks are performed regardless of success or failure. Therefore, the correct execution order is rescue first, then always.

Exam trap

The trap here is that candidates often confuse the order of rescue and always, mistakenly thinking always runs first or that only one of them executes, when in fact rescue runs before always on failure.

How to eliminate wrong answers

Option A is wrong because the always section runs unconditionally, but the rescue section also runs when a task fails, so it is not the only section executed. Option B is wrong because the always section always runs after rescue, so rescue does not run alone. Option D is wrong because the always section runs after rescue, not before; the order is rescue then always, not always then rescue.

53
MCQhard

An Ansible playbook that deploys a web application includes a task that uses the `uri` module to call an external API. The task occasionally fails due to API rate limiting. Which combination of keywords should be added to the task to automatically retry up to 5 times with a 30-second delay between attempts, and only fail if all retries are exhausted?

A.`register: result`, `until: status == 200`, `retries: 5`, `delay: 30`
B.`register: result`, `until: result.status == 200`, `retries: 5`, `delay: 30`
C.`until: result.status == 200`, `retries: 5`, `delay: 30`
D.`register: result`, `retries: 5`, `delay: 30`
AnswerB

The `until` keyword loops the task until `result.status == 200`, satisfying the rate-limit constraint by re-polling the API. `retries: 5` caps attempts, while `delay: 30` inserts the required 30-second pause between them. `register` captures each response so the condition can be evaluated, and the task fails only once retries are exhausted.

Why this answer

It combines `register` to capture the API response, `until` to check that `result.status` equals 200 (the HTTP success code), `retries: 5` to attempt the task up to five times, and `delay: 30` to wait 30 seconds between retries. This ensures the task only fails after all five retries are exhausted, which is the exact behavior needed to handle transient API rate limiting.

Exam trap

Red Hat often tests the requirement that `register` must be used with `until` to reference the captured result, and that `retries`/`delay` are meaningless without `until` — candidates frequently omit `register` or forget to prefix the variable with `result.` in the condition.

How to eliminate wrong answers

Option A is wrong because it uses `status == 200` instead of `result.status == 200`; without referencing the registered variable, Ansible would look for a nonexistent `status` fact, causing a syntax or logic error. Option C is wrong because it omits `register: result`, so the `until` condition has no captured variable to check, leading to an undefined variable error. Option D is wrong because it lacks the `until` keyword entirely, meaning the task will not retry based on a condition; `retries` and `delay` alone only apply when `until` is present, so the task would run once and fail immediately.

54
MCQmedium

An administrator needs to run a playbook in check mode to preview changes on managed hosts, but a critical task using the `command` module must always execute regardless of check mode. Which task directive should be applied to that specific task?

A.`always_run: yes`
B.`ignore_errors: yes`
C.`run_once: true`
D.`check_mode: no`
AnswerD

Setting `check_mode: no` forces the task to run normally even when the playbook is executed with `--check`, overriding the global check mode for that task. This is the correct directive to ensure the command executes regardless of the playbook's check mode setting, allowing critical operations to proceed while other tasks are only simulated.

Why this answer

The `check_mode: no` task directive overrides the playbook-level check mode for that specific task, forcing it to execute normally even when `--check` is used. This is essential for tasks that must always run, such as those that gather facts or perform critical operations that should not be simulated.

Exam trap

The trap here is assuming that `always_run` still works in modern Ansible; it was deprecated and removed, so the correct directive is `check_mode: no`.

55
MCQmedium

A new technician runs a playbook that uses the yum module to install packages. The playbook fails with 'No package matching' for a custom package. The package is available on a third-party repository. Which step should the technician take?

A.Use the rpm_key module to import the GPG key.
B.Add the repository using the yum_repository module.
C.Use command: yum install directly.
D.Update the package cache using yum update.
AnswerB

The yum module resolves packages only from repositories already configured on the managed host. A third-party repository must first be defined, so the yum_repository module adds the repo definition before the install task runs, allowing the custom package to be found.

Why this answer

The yum module requires that the repository providing the package is already configured on the target system. Since the custom package is on a third-party repository, the technician must first add that repository using the yum_repository module. This module creates the necessary .repo file in /etc/yum.repos.d/, making the package available for installation via the yum module.

Exam trap

The trap here is that candidates may confuse the need to add a repository with other common tasks like importing GPG keys or updating the cache, assuming the package is simply not found due to stale metadata rather than a missing repository source.

How to eliminate wrong answers

Option A is wrong because importing a GPG key (rpm_key) is used to verify package signatures, not to add a repository or make packages available; the package is not found because the repository is missing, not because of a key issue. Option C is wrong because using command: yum install bypasses Ansible's idempotency and module benefits, and is not a best practice for package management in Ansible playbooks. Option D is wrong because updating the package cache (yum update) only refreshes metadata for already-configured repositories; it does not add a new third-party repository.

56
MCQhard

A company uses dynamic inventory from a cloud provider. The playbook needs to run tasks only on instances with a specific tag. The ansible_ec2_tags variable is not available. What is the most efficient method to filter hosts?

A.Use the hostvars lookup to check tags.
B.Use the ec2_instance_facts module inside the playbook to gather facts and filter.
C.Use a static inventory file with hosts pre-filtered.
D.Use the amazon.aws.aws_ec2 inventory plugin with compose and keyed_groups.
AnswerD

Pre-filters hosts at inventory time, most efficient.

Why this answer

The `amazon.aws.aws_ec2` inventory plugin can dynamically filter EC2 instances by tag using `keyed_groups` and `compose` at inventory build time, avoiding runtime overhead. This is the most efficient method as it pre-filters hosts before the playbook runs, unlike runtime fact gathering or lookups.

Exam trap

The trap here is that candidates often confuse runtime fact gathering (like `ec2_instance_info`) with inventory plugin filtering, not realizing that pre-filtering at inventory build time is far more efficient and aligns with Ansible's dynamic inventory best practices.

How to eliminate wrong answers

Option A is wrong because `hostvars` is a runtime lookup that requires the host to already be in the inventory, and it does not filter hosts; it only retrieves variables for hosts that are already present. Option B is wrong because `ec2_instance_facts` (now `amazon.aws.ec2_instance_info`) gathers facts at runtime on all hosts, which is inefficient and contradicts the goal of filtering hosts before task execution. Option C is wrong because a static inventory file defeats the purpose of dynamic inventory from a cloud provider, requiring manual updates and not scaling with dynamic environments.

57
MCQmedium

A playbook uses 'vars_prompt' to ask for a confirmation before proceeding with destructive changes. However, when the playbook is run from a CI/CD pipeline, it hangs indefinitely. What is the best way to handle this?

A.Remove the prompt and always proceed.
B.Set ANSIBLE_STDOUT_CALLBACK=unixy to avoid interactive prompts.
C.Encrypt the confirmation in vault and include it.
D.Use --check mode to simulate.
E.Pass the variable via --extra-vars and modify the prompt to be conditional with 'when: variable is not defined'.
AnswerE

Correct: This allows non-interactive input from CI/CD and only prompts when variable is missing.

Why this answer

Passing the variable via --extra-vars and making the prompt conditional with 'when: variable is not defined' allows the pipeline to provide the variable non-interactively. Option A is unsafe. Option B's --check mode does not solve prompts.

Option C is unrelated. Option D encrypts data but does not handle prompts. Therefore, E is best.

58
MCQmedium

A playbook uses the 'block' and 'rescue' keywords. If a task in the block fails, but the rescue tasks also fail, what happens?

A.The play fails.
B.The play continues to the next task.
C.The block is re-executed.
D.The rescue tasks are retried.
AnswerA

When a block task fails, rescue tasks run; if those rescue tasks also fail, the error remains unhandled, so the play aborts with a failed status for the host rather than continuing to subsequent tasks.

Why this answer

When a task in a block fails, the rescue tasks execute. If the rescue tasks also fail, the entire play fails (the failure propagates). Option B is incorrect because the play does not continue; it fails.

Option C is incorrect because the block is not re-executed; rescue only runs once. Option D is incorrect because rescue tasks are not retried after failure.

59
MCQhard

An Ansible playbook uses a custom filter plugin located in the `filter_plugins/` directory next to the playbook. The filter is not being applied, and the playbook fails with an error that the filter is undefined. What is the most likely reason?

A.The filter plugin must be written in Python and have a `.py` extension.
B.The `filter_plugins` directory must be specified in `ansible.cfg` using `filter_plugins = ./filter_plugins`.
C.The filter plugin file must define a `FilterModule` class with a `filters` method.
D.The filter plugin must be placed in a `library` directory instead of `filter_plugins`.
AnswerC

Ansible filter plugins must define a class named `FilterModule` that contains a `filters` method returning a dictionary of filter names to callables. If this structure is missing, the filter will not be registered and will appear undefined. This is the most common reason for such errors.

Why this answer

Filter plugins require a specific structure: a `FilterModule` class with a `filters` method that returns a dictionary mapping filter names to functions. Without this, Ansible cannot register the filter, leading to an undefined filter error. The directory location and file extension are correct, so the structure is the likely culprit.

Exam trap

The trap here is assuming that placing the plugin in the correct directory is enough, when the internal class and method structure is critical for registration.

60
MCQmedium

A playbook uses import_playbook to include other playbooks. The main playbook is run with --check mode. Which statement is true?

A.Only the main playbook runs in check mode; imported ones run normally.
B.All imported playbooks are skipped because import happens at parse time.
C.import_playbook does not support check mode.
D.Imported playbooks are also run in check mode.
AnswerD

Import_playbook merges tasks at parse time, so check mode affects all tasks.

Why this answer

When a playbook uses `import_playbook`, the imported playbooks are statically included at parse time, meaning they become part of the main playbook's play structure. The `--check` mode flag applies to the entire playbook execution, so all imported playbooks also run in check mode. Option D is correct because Ansible propagates the check mode flag to all imported plays.

Exam trap

The trap here is that candidates confuse `import_playbook` (static inclusion) with dynamic includes like `include_tasks`, which do not inherit check mode in the same way, leading them to think imported playbooks are skipped or run normally.

How to eliminate wrong answers

Option A is wrong because `--check` mode is not limited to the main playbook; it applies globally to all plays, including those imported via `import_playbook`. Option B is wrong because `import_playbook` does not cause imported playbooks to be skipped in check mode; they are included at parse time and run with the same check mode flag. Option C is wrong because `import_playbook` fully supports check mode; there is no restriction that prevents imported playbooks from running in check mode.

61
MCQeasy

An Ansible playbook contains many tasks. An administrator wants to run only a subset of tasks by passing '--tags ' at the command line. Which of the following must be added to the tasks?

A.a 'name' with specific naming convention
B.a 'block' statement
C.a 'tags' directive on each task
D.a 'when' condition
AnswerC

The --tags flag matches tasks carrying a tags directive, so each task to be selectively run must declare one. Without tags on the tasks, ansible-playbook cannot identify which subset to execute and runs none of the tagged selection.

Why this answer

The 'tags' directive is the only mechanism in Ansible that allows tasks to be selectively included or excluded when running a playbook with the '--tags' command-line option. By adding a 'tags' attribute to a task (e.g., 'tags: install'), the administrator can target that task specifically, and Ansible's task execution engine filters tasks based on the provided tags at runtime.

Exam trap

The trap here is that candidates often confuse the 'name' field with a functional identifier, assuming it can be used for filtering, when in reality only the 'tags' directive controls task selection with '--tags'.

How to eliminate wrong answers

Option A is wrong because the 'name' field in a task is purely for documentation and display purposes; it does not influence task selection via '--tags'. Option B is wrong because a 'block' statement groups tasks for error handling or conditional execution but does not provide tag-based filtering; blocks themselves can have tags, but the question asks what must be added to each task, and a block is not required. Option D is wrong because a 'when' condition controls whether a task runs based on variables or facts, not on command-line tag selection, and cannot be used with '--tags'.

62
MCQhard

You are managing a large infrastructure of 500 Linux servers. The servers are divided into groups: 'web', 'app', and 'db'. Each group has specific configuration requirements. You have developed a set of Ansible roles to manage these configurations. Recently, you noticed that when you run the playbook against all servers, the 'web' role is applied to 'app' servers due to a variable misconfiguration. The playbook uses include_role with a variable that determines which role to apply. The variable is defined in group_vars/all.yml as 'server_role: web'. However, each group should have its own role: 'web' for web servers, 'app' for app servers, 'db' for db servers. The playbook includes the role based on '{{ server_role }}'. What is the best course of action to fix this issue without modifying the playbook structure?

A.Change the variable in group_vars/all.yml to a list and use 'include_role' with loop.
B.Add a 'when' condition to the include_role task to check the group name.
C.Define the server_role variable in group_vars/web.yml, group_vars/app.yml, and group_vars/db.yml with the appropriate values.
D.Define the server_role in host_vars for each server.
AnswerC

Defining `server_role` in each group's `group_vars` file exploits Ansible's variable precedence: group-specific variables override the `group_vars/all.yml` default, so each host resolves `{{ server_role }}` to its own group's role. This satisfies the constraint of fixing the misconfiguration without altering the playbook's `include_role` structure.

Why this answer

Ansible's variable precedence dictates that group_vars/<group_name>.yml files override group_vars/all.yml for hosts in that group. By defining `server_role` per group file (web, app, db), each server gets the correct role without modifying the playbook structure. This leverages Ansible's built-in group variable inheritance to resolve the misconfiguration cleanly.

Exam trap

The trap here is that candidates may think a `when` condition or modifying the playbook is necessary, but the question tests understanding of Ansible's variable precedence and the correct use of group_vars to override all.yml without altering the playbook structure.

How to eliminate wrong answers

Option A is wrong because changing `server_role` to a list and looping `include_role` would apply multiple roles to each server, not fix the single-role misassignment; it also unnecessarily complicates the playbook. Option B is wrong because adding a `when` condition requires modifying the playbook structure, which the question explicitly forbids, and it would not leverage Ansible's variable precedence. Option D is wrong because defining `server_role` in `host_vars` for each of 500 servers is impractical and violates the DRY principle; group_vars is the correct scope for group-specific variables.

63
MCQmedium

An Ansible playbook runs tasks on a group of web servers. During a rolling update, the playbook should ensure that no more than 2 servers are taken out of service at the same time. Which play keyword should be used?

A.forks: 2
B.max_fail_percentage: 2
C.throttle: 2
D.serial: 2
AnswerD

The serial keyword controls how many hosts Ansible targets per batch, so serial: 2 limits the rolling update to two servers at a time. This satisfies the constraint that no more than two servers leave service simultaneously.

Why this answer

The `serial` keyword controls the batch size of hosts that Ansible executes a play against. Setting `serial: 2` ensures that only 2 web servers are processed at a time, which is exactly what is needed for a rolling update where no more than 2 servers should be taken out of service simultaneously.

Exam trap

The trap here is confusing `serial` (which controls batch size of hosts) with `forks` (which controls parallelism of task execution), leading candidates to pick `forks: 2` thinking it limits concurrency, when in fact it only limits the number of parallel task processes, not the number of hosts taken out of service simultaneously.

How to eliminate wrong answers

Option A is wrong because `forks: 2` sets the number of parallel processes Ansible uses to execute tasks across all hosts, but it does not limit the batch size of hosts that are taken out of service; with forks, all hosts can still be targeted in parallel up to the fork limit, which could take more than 2 servers out of service at once. Option B is wrong because `max_fail_percentage: 2` defines the maximum percentage of hosts that can fail before the playbook aborts, not the number of hosts processed concurrently. Option C is wrong because `throttle: 2` limits the number of concurrent task executions across a play or role, but it applies to individual tasks rather than controlling the batch size of hosts in a rolling update scenario.

Ready to test yourself?

Try a timed practice session using only Implement advanced Ansible automation questions.