Courseiva

CCNA Automation, Orchestration, and Scripting Questions

37 of 112 questions · Page 2/2 · Automation, Orchestration, and Scripting · Answers revealed

76
Multi-Selectmedium

A Linux administrator is writing a Bash script that must safely process a list of filenames, some of which may contain spaces or special characters. The script reads each line from a file into a variable and then iterates over the entries. Which TWO practices should the administrator follow to avoid word-splitting and globbing issues? (Choose two.)

Select 2 answers
A.Disable globbing by running set -f at the start of the script and never re-enable it.
B.Quote the variable expansion, for example "$filename", whenever it is used in commands.
C.Set the IFS variable to a newline character globally at the top of the script before any commands run.
D.Use IFS= read -r line inside a while loop to read each line without stripping leading or trailing whitespace and without interpreting backslashes.
E.Use the eval command to expand the variable so that spaces are handled automatically.
AnswersB, D

Quoting the variable expansion prevents the shell from performing word splitting and pathname expansion on the value. If a filename contains spaces or wildcard characters, an unquoted expansion would break it into multiple arguments or expand globs, causing the command to operate on the wrong files. Quoting preserves the value as a single argument.

Why this answer

To safely handle filenames with spaces or special characters, the script should quote variable expansions so the shell treats each value as a single argument, and read lines with IFS= read -r to preserve whitespace and backslashes. These two practices together prevent word splitting and globbing from corrupting the data during iteration.

Exam trap

The trap here is believing that globally changing IFS or using eval will solve quoting problems, when scoped quoting and IFS= read -r are the correct targeted techniques.

77
Multi-Selecthard

A Linux administrator is reviewing an Ansible playbook that manages a fleet of servers. The playbook must run a task only on hosts in the group webservers and must notify a handler when a configuration file changes. Which TWO of the following are valid Ansible constructs that the administrator should use? (Choose two.)

Select 2 answers
A.serial: 1
B.notify: restart nginx
C.hosts: webservers
D.when: ansible_os_family == "Debian"
E.become: yes
AnswersB, C

The notify keyword on a task triggers a handler by name when the task reports a changed state. Pairing it with a handler named restart nginx, defined in the handlers section, ensures the service is restarted only when the configuration file actually changes, which is the intended behavior.

Why this answer

The hosts directive scopes the play to the webservers inventory group, and the notify keyword on a task causes a named handler to run when that task changes state. Together they ensure the play runs only on the intended hosts and that a service restart handler fires only when the configuration file is modified.

Exam trap

The trap here is assuming that become or when are required for targeting and notification, when in fact hosts and notify are the keywords that directly implement those behaviors.

78
MCQmedium

A Linux administrator is writing a bash script that accepts command-line options: -a for all, -f for file, and -o for output. Which of the following correctly uses getopts to parse these options?

A.while getopts "-a -f -o" opt; do ... done
B.while getopts "a:f:o" opt; do case $opt in a) ...;; f) ...;; o) ...;; esac; done
C.getopts "afo" opt; case $opt in a) ...;; f) ...;; o) ...;; esac
D.while getopts "afo" opt; do case $opt in a) ...;; f) ...;; o) ...;; esac; done
AnswerD

Correct. The option string 'afo' defines three boolean options without arguments.

Why this answer

getopts uses a string of option characters; a colon after an option indicates it requires an argument. The correct usage is 'a:f:o' where a and f require arguments, but the stem doesn't specify arguments. Assuming -a and -f don't require arguments, the string should be 'afo'.

79
MCQhard

A Linux administrator is debugging a Bash script that uses a function to set a global counter. The function increments the variable, but after the function returns, the counter retains its original value. The script does not use subshells or pipelines around the function call. Which of the following is the MOST likely cause?

A.The counter variable was exported with export, which makes it read-only inside functions.
B.The function was defined with the function keyword instead of the POSIX name() syntax, which isolates its variables.
C.The script lacks a shebang line, so Bash runs it in POSIX mode where functions cannot modify global variables.
D.The variable was declared with the local keyword inside the function, creating a function-scoped copy that shadows the global variable.
AnswerD

When a variable is declared with local inside a function, Bash creates a new variable scoped to that function. Any modifications affect only the local copy, and when the function returns, the local variable is destroyed, leaving the global variable unchanged. Removing the local declaration or using a different variable name resolves the issue.

Why this answer

The local keyword inside a function creates a function-scoped variable that shadows any global variable of the same name. Assignments inside the function affect only the local copy, which disappears when the function returns, so the global counter appears unchanged. Removing the local declaration allows the function to modify the global variable directly.

Exam trap

The trap here is attributing the behavior to function definition syntax or export, when the actual cause is the local keyword creating a shadowed, function-scoped variable.

80
MCQmedium

A container is running and a technician needs to execute an interactive shell inside it. The container was started with 'docker run -d --name myapp myimage'. Which command will achieve this?

A.docker exec -it myapp /bin/bash
B.docker attach myapp
C.docker run -it --name myapp myimage /bin/bash
D.docker logs -f myapp
AnswerA

docker exec runs a new process inside an already-running container, and the -it flags allocate an interactive TTY plus stdin, giving a shell. Because the container was started detached with -d and named myapp, this satisfies the stem's requirement without restarting or replacing it.

Why this answer

'docker exec -it myapp /bin/bash' attaches a new interactive TTY session to the already-running container named myapp and launches /bin/bash inside it. The -i flag keeps STDIN open and -t allocates a pseudo-TTY, which is required for an interactive shell. Because the container is already running, exec is the correct tool rather than run.

Exam trap

The trap is confusing 'docker exec' (enter a running container) with 'docker attach' (connect to PID 1's stdio) or 'docker run' (create a new container) — candidates often pick attach or run when the container is already running.

How to eliminate wrong answers

Option B is wrong because 'docker attach' connects to the container's existing PID 1 STDIN/STDOUT — it does not spawn a new shell, and detaching can accidentally stop the container. Option C is wrong because 'docker run -it --name myapp myimage /bin/bash' attempts to create a new container with a duplicate name (myapp already exists), which fails, and it would start a new container rather than enter the running one. Option D is wrong because 'docker logs -f' only streams the container's log output; it provides no shell access.

81
MCQmedium

An administrator is writing a Bash script that must run a cleanup function when the script exits, whether it finishes normally or is interrupted. Which construct guarantees the function runs in both cases?

A.cleanup &
B.set -e; cleanup
C.alias cleanup='rm -rf /tmp/work'
D.trap 'cleanup' EXIT
AnswerD

The EXIT pseudo-signal fires whenever the shell terminates, including normal completion, explicit exit, and receipt of a termination signal that the shell handles. Registering cleanup with trap therefore guarantees the function runs on both paths, making it the standard idiom for resource teardown in scripts.

Why this answer

The trap facility lets a script associate a handler with a signal or with the EXIT pseudo-signal, which the shell raises on every termination path. Using trap 'cleanup' EXIT ensures the teardown function executes after normal completion and after interrupts, unlike aliases, backgrounding, or plain sequential execution, which have no exit semantics.

Exam trap

The trap here is confusing set -e, which controls when the shell aborts, with trap on EXIT, which actually runs cleanup at termination.

82
MCQmedium

A Linux administrator is writing a Bash automation script that must continue processing the remaining entries in a loop even when an individual command returns a non-zero exit status. The script currently starts with `#!/bin/bash` and uses `set -e` for safety elsewhere. Which construct should the administrator use to run a command whose failure must be tolerated inside the loop?

A.Append `|| true` to the command so its non-zero exit status is masked.
B.Run the loop body inside a subshell wrapped with `set +e` before and after the command.
C.Prefix the command with `env -i` to isolate its environment and prevent exit propagation.
D.Redirect the command's stderr to `/dev/null` to prevent the shell from seeing the failure.
AnswerA

Under `set -e`, a failing command terminates the script unless its status is consumed by a conditional or an OR list. Appending `|| true` converts the failure into a successful status, allowing the loop to continue while other commands remain protected. This is the idiomatic, minimal fix for selectively tolerating a known-failing command without disabling error handling globally.

Why this answer

With `set -e` active, any simple command returning non-zero aborts the script unless its status is part of a condition or OR list. Appending `|| true` makes the overall list succeed, so the loop advances while errexit remains enabled for everything else. This preserves the safety net for unforeseen failures while deliberately tolerating the one command expected to fail.

Exam trap

The trap here is assuming that suppressing a command's error output also prevents `set -e` from acting on its exit status.

83
MCQmedium

A Linux administrator is writing a Bash script that must read a file line by line and preserve leading whitespace in each line. The script currently uses `for line in $(cat file.txt)`. Which construct should replace the current loop to preserve whitespace and avoid word splitting?

A.while IFS= read -r line; do ... done < file.txt
B.cat file.txt | while read -r line; do ... done
C.for line in "$(cat file.txt)"; do ... done
D.while read line; do ... done < <(cat file.txt)
AnswerA

This is correct because setting IFS= for the read built-in disables field splitting, and the -r flag prevents backslash interpretation, so leading and trailing whitespace and backslashes in each line are preserved. Redirecting the file into the loop keeps the read in the current shell, unlike piping, which would run it in a subshell.

Why this answer

Reading a file line by line while preserving whitespace requires disabling field splitting with IFS= and preventing backslash processing with read -r, and the input must be redirected into the loop rather than piped so the loop runs in the current shell. The quoted command substitution approach collapses the file into one value, and the default read behavior strips leading whitespace.

Exam trap

The trap here is assuming that quoting a command substitution in a for loop preserves line structure and whitespace, when it actually collapses the entire file into one argument.

84
MCQmedium

A Linux administrator is writing a systemd unit file at /etc/systemd/system/backup.service that must execute /usr/local/bin/backup.sh only after the network is fully reachable and the /mnt/archive mount is active. The unit currently has no ordering directives. Which directive should be added to the [Unit] section to satisfy this requirement?

A.Wants=network-online.target local-fs.target
B.Requires=network-online.target local-fs.target
C.After=network-online.target local-fs.target
D.BindsTo=network-online.target local-fs.target
AnswerC

After= establishes ordering only: backup.service is queued to start after the listed targets finish activating, so the network is reachable and local filesystems including /mnt/archive are mounted first. This is exactly the ordering guarantee the scenario demands, and systemd will not begin the unit until those targets are active.

Why this answer

Ordering in systemd is expressed with After= and Before=, which control when a unit is queued relative to others without creating a dependency. To guarantee the backup script runs only once the network is up and /mnt/archive is mounted, the [Unit] section needs After=network-online.target local-fs.target. Dependency keywords such as Requires, Wants, and BindsTo pull units in or tie lifecycles together but never enforce start ordering on their own.

Exam trap

The trap here is assuming that Requires= or Wants= also controls start order, when systemd keeps dependency and ordering semantics completely separate.

85
MCQmedium

A Linux administrator needs to schedule a script at /opt/scripts/report.sh to run every Monday at 02:30 for the user svcacct, without editing the system-wide /etc/crontab. Which cron entry correctly accomplishes this when placed in svcacct's crontab via crontab -e?

A.2 30 * * 1 /opt/scripts/report.sh
B.30 2 * * 0 /opt/scripts/report.sh
C.30 2 1 * * /opt/scripts/report.sh
D.30 2 * * 1 /opt/scripts/report.sh
AnswerD

The five fields are minute, hour, day of month, month, and day of week. 30 2 * * 1 means minute 30, hour 2, any day of month, any month, and day-of-week 1, which is Monday, matching the requested Monday 02:30 schedule. Being in the user's crontab, it runs as svcacct automatically.

Why this answer

Cron's five fields are minute, hour, day of month, month, and day of week, in that order. The requirement of Monday at 02:30 maps to minute 30, hour 2, wildcard day of month, wildcard month, and day-of-week 1 for Monday. Placing the entry in svcacct's own crontab via crontab -e means it executes as that user without needing a username field or touching /etc/crontab.

Exam trap

The trap here is confusing the order of the minute and hour fields, or forgetting that cron day-of-week uses 0 or 7 for Sunday and 1 for Monday.

86
MCQeasy

A DevOps engineer needs to run a Docker container in the background with port mapping from host port 8080 to container port 80, and name the container 'webapp'. Which command accomplishes this?

A.docker start -d -p 8080:80 --name webapp nginx
B.docker create -d -p 8080:80 --name webapp nginx
C.docker run -d -p 8080:80 --name webapp nginx
D.docker compose up -d -p 8080:80 --name webapp nginx
AnswerC

The -d flag detaches the container to run in the background, -p 8080:80 maps host port 8080 to container port 80, and --name webapp assigns the required container name. The nginx image supplies the container workload, satisfying every constraint in the stem.

Why this answer

`docker run` is the command that creates AND starts a container in one step, and the `-d` flag detaches it to run in the background. The `-p 8080:80` flag maps host port 8080 to container port 80, and `--name webapp` assigns the container name. This is the canonical single-command way to launch a named, port-mapped, background container from the nginx image.

Exam trap

XK0-006 often tests the confusion between `docker run`, `docker create`, and `docker start` — candidates pick `create` or `start` thinking they launch a container, but only `run` both creates and starts it with the required flags.

How to eliminate wrong answers

Option A is wrong because `docker start` only starts an existing, already-created container — it does not accept `-p`, `--name`, or an image argument, so this syntax is invalid. Option B is wrong because `docker create` only creates the container without starting it, so it would not be running in the background as required. Option D is wrong because `docker compose up` operates on a compose file and does not accept `-p` port mapping or `--name` flags in that form — those are `docker run` options.

87
Multi-Selectmedium

A cloud engineer is using Ansible to manage configuration across multiple servers. The engineer needs to store variable data that is specific to each host and sensitive database passwords. Which two Ansible features should be used for these purposes? (Choose two.)

Select 2 answers
A.group_vars
B.ansible_facts
C.roles
D.Ansible Vault
E.host_vars
AnswersD, E

Ansible Vault encrypts sensitive variable files, such as the database passwords, using AES-256, so secrets remain unreadable at rest while still being decrypted at playbook runtime. This directly satisfies the stem's requirement to store sensitive credentials securely alongside host-specific data.

Why this answer

Option E, host_vars, is correct because host-specific variable data is stored in host_vars files (e.g., host_vars/<hostname>.yml), which Ansible automatically loads for the matching inventory host, making it the proper place for per-host values. Option D, Ansible Vault, is correct because it encrypts sensitive data such as database passwords, allowing vault-encrypted variables or files to be decrypted at runtime with the vault password, keeping secrets protected at rest. Option A, group_vars, applies variables to whole inventory groups rather than individual hosts, so it does not satisfy the host-specific requirement.

Option B, ansible_facts, holds automatically discovered system information gathered by setup, not user-defined sensitive credentials. Option C, roles, is a structural way to bundle tasks, handlers, and defaults for reuse, not a mechanism for storing host-specific or encrypted secret data.

Exam trap

The trap is selecting group_vars for host-specific data or forgetting that Ansible Vault is the only option for encrypting secrets; candidates must map 'per-host' to host_vars and 'sensitive' to Vault.

88
MCQmedium

A Linux administrator is writing a Bash script to back up a directory. The script must continue running even if a particular command fails, but the administrator wants to log the error and take corrective action. Which of the following should be used to handle the error condition?

A.Use `trap` to catch the ERR signal and exit the script.
B.Run the command in a subshell and ignore its exit status.
C.Check the exit status of the command using `$?` and conditionally execute recovery steps.
D.Use `set -e` at the beginning of the script.
AnswerC

After running a command, `$?` holds its exit status. By checking `$?` immediately, the script can detect failure, log the error, and run corrective actions without terminating. This allows the script to continue and meets the requirement of logging and handling the error. It is the standard way to implement custom error handling in Bash.

Why this answer

The requirement is to continue after a failure while logging and taking corrective action. Checking `$?` immediately after a command allows the script to branch based on success or failure, enabling custom error handling without terminating the script. This approach is flexible and standard for scenarios where fail-fast is not desired.

Other methods either exit prematurely or fail to provide error handling.

Exam trap

The trap here is assuming that `set -e` is always the best way to handle errors, but it forces an exit and prevents custom recovery logic.

89
MCQeasy

A Bash script contains the following code: if [[ $# -eq 0 ]]; then echo 'No arguments'; fi. What does this code check?

A.Whether the first argument is empty
B.Whether the script was called with no arguments
C.Whether the script has any syntax errors
D.Whether the script is running as root
AnswerB

The `$#` variable holds the argument count passed to the script, and `-eq 0` tests whether it equals zero. When no arguments are supplied, the condition succeeds and prints 'No arguments', directly satisfying the scenario's requirement to detect an invocation with an empty argument list.

Why this answer

In Bash, $# is a special parameter that expands to the number of positional parameters (arguments) passed to the script. The test [[ $# -eq 0 ]] evaluates to true when zero arguments were supplied, so the script echoes 'No arguments' when called without any arguments.

Exam trap

The trap is confusing $# (argument count) with $1 (first argument) or $? (exit status); candidates must memorize that $# specifically returns the number of positional parameters.

How to eliminate wrong answers

Option A is wrong because checking whether the first argument is empty would use [[ -z $1 ]] or [[ -z "$1" ]], not $#. Option C is wrong because syntax errors are detected by the Bash parser at runtime or with bash -n, not by $#. Option D is wrong because checking for root privileges uses $EUID or $UID (e.g., [[ $EUID -ne 0 ]]), not $#.

90
MCQeasy

A Linux administrator needs a scheduled job on a production server to run the backup script /usr/local/bin/backup.sh every day at 02:30, and the job must run as the root user regardless of who is logged in. Which single entry in /etc/crontab accomplishes this?

A.@daily root /usr/local/bin/backup.sh
B.2 30 * * * root /usr/local/bin/backup.sh
C.30 2 * * * /usr/local/bin/backup.sh root
D.30 2 * * * root /usr/local/bin/backup.sh
AnswerD

The system crontab /etc/crontab uses a six-field format where field five is the user account that runs the command, followed by the command itself. Placing root in that field and the absolute path to backup.sh after it makes the job run daily at 02:30 as root, independent of any interactive login session.

Why this answer

System-wide cron entries in /etc/crontab carry an extra user field between the five time/date fields and the command, which is what allows a job to run as root without a login. The schedule fields must be ordered minute, hour, day-of-month, month, day-of-week, so 30 2 * * * is 02:30 and root names the executing account.

Exam trap

The trap here is forgetting that /etc/crontab needs a sixth user field while a per-user crontab edited with crontab -e must not contain one.

91
MCQeasy

A Linux administrator needs to run a recurring backup script located at /usr/local/bin/backup.sh every day at 02:30. The system uses systemd and the administrator wants the job scheduled through a systemd timer rather than cron. Which combination of unit files must be created and enabled?

A.A single .service unit containing OnCalendar=*-*-* 02:30:00 in its [Service] section, then enable and start that unit.
B.A .timer unit with OnCalendar=*-*-* 02:30:00 and a matching .service unit, then enable and start the .timer unit.
C.A .timer unit with OnCalendar=*-*-* 02:30:00 and a matching .service unit, then enable and start the .service unit.
D.A .timer unit with OnBootSec=02:30 and a matching .service unit, then enable and start the .timer unit.
AnswerB

A systemd timer is driven by the OnCalendar= expression, and systemd activates the same-named .service unit when the timer elapses. Enabling and starting the .timer unit registers the schedule with systemd. The .service unit contains the ExecStart= line that actually invokes /usr/local/bin/backup.sh, so this pairing correctly delivers a daily 02:30 execution.

Why this answer

A systemd timer requires two cooperating units: a .timer unit that defines the schedule via OnCalendar= and a same-named .service unit that defines what to execute. To activate the schedule you enable and start the .timer unit, not the service. At each matching calendar point systemd triggers the associated service, which runs the ExecStart= command pointing at the backup script.

Exam trap

The trap here is assuming the .service unit must be enabled to make the schedule work, when it is actually the .timer unit that must be enabled and started.

92
MCQmedium

An Ansible playbook is being written to install the Nginx web server on a group of Ubuntu servers. Which module should be used in the playbook to install the package?

A.apt
B.command
C.package
D.yum
AnswerA

The apt module drives Ubuntu's native package manager, satisfying the stem's requirement to install Nginx on Debian-based hosts. It handles repository metadata, dependency resolution and idempotent state checks directly, unlike generic command or shell modules that would bypass package management and lose idempotence.

Why this answer

The apt module is used for package management on Debian/Ubuntu systems.

93
MCQeasy

A developer wants to view the logs from a running Docker container named 'myapp'. Which docker command should be used?

A.docker logs myapp
B.docker ps myapp
C.docker exec myapp logs
D.docker inspect myapp
AnswerA

docker logs retrieves stdout and stderr captured from the container's main process, and naming the container filters output to that instance. This satisfies the requirement to view logs from the running container 'myapp' without attaching to or executing inside it.

Why this answer

The 'docker logs' command is specifically designed to fetch the logs from a container's stdout/stderr. Running 'docker logs myapp' will display the logs generated by the container named 'myapp'. This is the standard and correct way to view container logs.

Exam trap

The trap is confusing 'docker logs' with 'docker exec' or 'docker inspect'; candidates might think they need to enter the container to view logs, but Docker provides a direct command for that.

How to eliminate wrong answers

Option B is wrong because 'docker ps' lists running containers and does not accept a container name as an argument to show logs; it only shows container metadata. Option C is wrong because 'docker exec' is used to run a command inside a running container, and 'logs' is not a valid command inside the container; it would attempt to execute a binary named 'logs'. Option D is wrong because 'docker inspect' returns low-level JSON metadata about the container (e.g., configuration, network settings) but does not display the application logs.

94
MCQmedium

A Kubernetes administrator needs to expose a deployment named 'webapp' as a service accessible externally on port 80. Which kubectl command should be used?

A.kubectl port-forward deployment/webapp 80:80
B.kubectl run webapp --port=80
C.kubectl expose deployment webapp --type=NodePort --port=80
D.kubectl create service clusterip webapp --port=80
AnswerC

NodePort opens a static port on every cluster node, routing external traffic to the deployment's pods, which satisfies the external-access requirement. However, it exposes the service on a high port (30000–32767) rather than port 80 directly, so clients must target the assigned node port unless a load balancer or ingress maps port 80.

Why this answer

The kubectl expose deployment command creates a Service from an existing Deployment. Specifying --type=NodePort makes the service externally reachable on each node's IP at a high port, and --port=80 sets the service port to 80. This is the standard imperative way to expose a deployment externally without writing a YAML manifest.

Exam trap

The trap is confusing port-forward (a temporary local tunnel) with expose (a persistent Service) — candidates often pick port-forward thinking it provides external access, but it only works from the machine running kubectl.

How to eliminate wrong answers

Option A is wrong because kubectl port-forward only creates a temporary local tunnel from the administrator's machine to the pod; it does not expose the service externally to other clients. Option B is wrong because kubectl run creates a new pod or deployment, not a service, and would conflict with the existing 'webapp' deployment. Option D is wrong because ClusterIP services are only reachable inside the cluster, not externally, so they do not satisfy the external-access requirement.

95
MCQhard

An administrator needs to deploy a set of microservices using Docker Compose. The services require configuration values that vary between development and production environments. Which approach allows the administrator to override values without modifying the docker-compose.yml file?

A.Define multiple services in one docker-compose.yml and use profiles.
B.Use environment variables in the Dockerfile and pass them via docker run -e.
C.Use the extends keyword in docker-compose.yml.
D.Use multiple compose files with the -f flag: docker-compose -f docker-compose.yml -f docker-compose.prod.yml up.
AnswerD

Layering multiple Compose files with the `-f` flag merges them at runtime, with later files overriding earlier values. This satisfies the requirement to vary configuration between development and production without editing `docker-compose.yml`, since the base file stays untouched and environment-specific overrides live in a separate file.

Why this answer

Docker Compose supports merging multiple compose files via the -f flag, where later files override or extend values from earlier ones. Running docker-compose -f docker-compose.yml -f docker-compose.prod.yml up applies the base configuration and then overlays production-specific values without editing the original file.

Exam trap

The trap is selecting extends or profiles for environment-specific overrides; candidates must remember that multi-file merging with -f is the canonical Docker Compose pattern for layering environment configurations.

How to eliminate wrong answers

Option A is wrong because profiles are used to selectively enable/disable groups of services within a single compose file, not to override configuration values between environments. Option B is wrong because environment variables in the Dockerfile and docker run -e apply to individual containers, not to Compose-managed multi-service deployments, and they do not override compose file values. Option C is wrong because the extends keyword allows a service to inherit configuration from another service or file, but it is designed for reuse within a single project, not for environment-specific overrides across multiple files.

96
MCQhard

A Linux administrator uses Ansible to configure a fleet of web servers. A playbook task must copy a template file and then restart the nginx service only when the template content actually changes, avoiding needless restarts on every run. Which task construct enforces that behavior?

A.A template task with notify pointing to a handler that restarts nginx
B.A copy task with force: no followed by a shell task that runs systemctl restart nginx
C.A template task with a when clause that checks whether the nginx process is running
D.A template task followed by a service task with state: restarted and no conditional
AnswerA

The template module reports changed status only when the rendered file differs from the destination, and notify queues the named handler exclusively on that change. Handlers run once at the end of the play, so nginx restarts only after an actual template modification, which is exactly the idempotent behavior the scenario requires.

Why this answer

Ansible handlers are triggered only when a task reports a changed result, and the template module reports changed precisely when the rendered output differs from the file on the managed host. Wiring notify to a handler that restarts nginx therefore produces a restart only on genuine configuration changes, keeping repeated playbook runs idempotent and quiet.

Exam trap

The trap here is reaching for an unconditional service restart or a when condition, when only a notify-handler pair reacts to the change status of the template task.

97
MCQmedium

A developer is writing a Bash script that needs to parse command-line options with arguments, such as -f filename and -v. Which built-in command should be used to handle these options?

A.getopt
B.getopts
C.case
D.shift
AnswerB

getopts is the shell built-in that parses short options, handling flags and their arguments, and exposes each via OPTARG and OPTIND. It satisfies the requirement to process -f filename and -v without external utilities or manual argument shifting.

Why this answer

getopts is the standard Bash built-in for parsing short options with or without arguments.

98
MCQeasy

Which Dockerfile instruction sets the command to run when the container starts, but allows the user to override it when using docker run?

A.RUN
B.STARTUP
C.ENTRYPOINT
D.CMD
AnswerD

CMD sets the default command executed when the container starts, but it is overridden when arguments are supplied to docker run. ENTRYPOINT, by contrast, is not overridden this way, so CMD matches the stated requirement.

Why this answer

CMD provides defaults for an executing container. If CMD is used, it can be overridden by command-line arguments to docker run. ENTRYPOINT, on the other hand, is not easily overridden without --entrypoint.

99
MCQeasy

A Docker container needs persistent storage that survives container restarts. Which of the following is the recommended method to achieve this?

A.Use a Docker volume
B.Store data inside the container filesystem
C.Use a bind mount only for configuration files
D.Set the container to always restart
AnswerA

Docker volumes store data outside the container's writable layer, in a host-managed directory, so it persists independently of the container lifecycle. This directly satisfies the requirement that storage survives restarts, unlike bind mounts tied to host paths or data written inside the container, which is destroyed on removal.

Why this answer

Docker volumes are the recommended mechanism for persistent data because they are managed by Docker, stored outside the container's writable layer (typically under /var/lib/docker/volumes), and survive container removal and restarts. They can be named, shared between containers, and backed up or migrated independently of the container lifecycle. This directly satisfies the requirement for storage that persists across restarts.

Exam trap

The trap is thinking that a restart policy or storing data in the container layer provides persistence; candidates must recognize that only volumes (or bind mounts) decouple data from the container lifecycle, and volumes are the recommended default.

How to eliminate wrong answers

Option B is wrong because data written to the container's writable layer is ephemeral — it is destroyed when the container is removed, and even on restart it is tied to that specific container instance, so it is not a reliable persistence method. Option C is wrong because bind mounts are not limited to configuration files; while they can persist data, the question asks for the recommended method, and volumes are preferred for persistent application data due to better portability and management. Option D is wrong because setting a restart policy only controls whether the container restarts after exit; it does nothing to preserve data written inside the container's filesystem.

100
MCQeasy

A Linux administrator needs to automate the deployment of a configuration file to fifty servers. The administrator wants to run a single command from a control node that copies the file to all servers in parallel and reports any failures. Which of the following tools is designed specifically for this task?

A.Ansible with an ad-hoc command using the copy module and a hosts inventory.
B.A for loop in a Bash script that calls scp for each hostname in a list.
C.A cron job on each target server that pulls the configuration file from a central web server every hour.
D.rsync run from the control node with a comma-separated list of remote hosts in a single invocation.
AnswerA

Ansible is an agentless automation tool that uses an inventory of hosts and modules such as copy to push files to many servers simultaneously. An ad-hoc command like ansible all -m copy -a 'src=... dest=...' runs against all inventory hosts in parallel and reports per-host results, matching the requirement exactly.

Why this answer

Ansible is purpose-built for agentless automation across many hosts. With an inventory and the copy module, a single ad-hoc command pushes the configuration file to all servers in parallel and returns per-host success or failure, which precisely matches the administrator's need for one command with consolidated reporting.

Exam trap

The trap here is assuming that a shell loop with scp or a single rsync invocation provides parallel fan-out and reporting, when only a configuration management tool like Ansible does so natively.

101
MCQmedium

A configuration-management playbook run by an administrator must install the nginx package only on hosts whose inventory group is webservers, and must restart the nginx service whenever the package installation changes the system. The administrator is using Ansible. Which pair of task attributes achieves both the conditional execution and the conditional restart?

A.Use when: "inventory_hostname == 'webservers'" on the install task and a notify: directive referencing a handler that restarts nginx.
B.Use when: "'webservers' in group_names" on the install task and a notify: directive referencing a handler that restarts nginx.
C.Use tags: webservers on the install task and a notify: directive referencing a handler that restarts nginx.
D.Use when: "'webservers' in group_names" on the install task and a changed_when: true attribute that restarts nginx.
AnswerB

The when: conditional evaluates the group_names variable, which contains the inventory groups the host belongs to, so the install task runs only on webservers hosts. The notify: directive queues a handler named in the handlers section, and handlers run only when the notifying task reports a changed state. Together they deliver conditional installation plus restart-on-change.

Why this answer

Ansible conditionals evaluate Jinja2 expressions against host facts and magic variables. group_names is a list of the inventory groups containing the current host, so testing membership restricts the install to webservers hosts. The notify: attribute links a task to a handler; handlers are deferred and fire only when the notifying task returns changed, which is exactly the behavior needed to restart nginx solely after a real package change.

Exam trap

The trap here is confusing tags with conditionals; tags gate tasks by command-line selection, while when: evaluates host-specific data during the run.

102
MCQmedium

A Linux administrator is automating user account creation. The script reads a list of usernames from a file and creates each account. The administrator wants the script to continue processing remaining users even if one useradd command fails due to a duplicate username. Which Bash construct should be used to run useradd and handle the failure without aborting the script?

A.set -e; useradd "$user"
B.useradd "$user" || echo "Failed to add $user" >&2
C.useradd "$user" && echo "Failed to add $user" >&2
D.useradd "$user" | echo "Failed to add $user" >&2
AnswerB

The || operator runs the right-hand command only when the left-hand command returns a non-zero exit status. This allows the script to log the failure for a duplicate username and continue with the next iteration, which matches the requirement to keep processing remaining users without aborting the entire script.

Why this answer

The || control operator provides a concise way to execute a fallback command only when the preceding command fails. By pairing useradd with a failure branch, the script can report the duplicate username and proceed to the next iteration, satisfying the requirement to continue processing the remaining users.

Exam trap

The trap here is confusing the short-circuit behavior of && and ||, since && fires on success while || fires on failure.

103
MCQhard

An administrator wants to run a script on multiple remote servers using Ansible. The script requires a variable that differs per host. Where should the administrator define this variable to follow best practices?

A.In the playbook under vars:
B.In host_vars/<hostname>.yml
C.In the inventory file as a variable
D.In group_vars/all.yml
AnswerB

Host-specific variables belong in host_vars/<hostname>.yml, which Ansible loads automatically for that inventory host. This keeps per-host values isolated from group and playbook scope, so the differing variable is applied only to the intended server without overriding other hosts' configuration.

Why this answer

Ansible best practice is to define host-specific variables in host_vars/<hostname>.yml, where the filename matches the inventory hostname. This keeps per-host configuration separate from the playbook and inventory, making it easy to maintain, version-control, and override at the appropriate precedence level. Variables defined here automatically apply only to that host, which is exactly what the scenario requires.

Exam trap

XK0-006 often tests Ansible variable precedence and file layout — candidates pick group_vars/all.yml because it is 'centralised', but that applies to all hosts, not per-host as the question requires.

How to eliminate wrong answers

Option A is wrong because defining the variable under vars: in the playbook applies it to all hosts in the play, not per-host, and hardcodes host-specific data into the playbook. Option C is wrong because defining variables inline in the inventory file works but is discouraged for anything beyond simple cases — it mixes inventory with configuration and is harder to maintain. Option D is wrong because group_vars/all.yml applies to every host in the inventory, which is the opposite of per-host differentiation.

104
MCQeasy

Which Kubernetes resource is used to store non-sensitive configuration data as key-value pairs that can be consumed by pods?

A.Deployment
B.Secret
C.Namespace
D.ConfigMap
AnswerD

ConfigMaps hold non-sensitive configuration as key-value pairs, decoupling configuration from pod images. Pods consume them via environment variables, command-line arguments, or mounted volumes. Sensitive data belongs in Secrets instead, which store base64-encoded values and support encryption at rest.

Why this answer

ConfigMaps are used for non-sensitive configuration data. Secrets are for sensitive data like passwords. Deployments manage replicas of pods.

Namespaces isolate resources.

105
Multi-Selectmedium

An Ansible playbook is being written to manage web servers. Which TWO modules can be used to ensure a package is installed? (Select TWO.)

Select 2 answers
A.copy
B.service
C.apt
D.yum
E.template
AnswersC, D

The apt module manages Debian-family packages via dpkg and APT repositories, so it satisfies the requirement to ensure a package is installed on Debian or Ubuntu web servers. It provides idempotent state=present handling, unlike command or shell, which would re-run unconditionally.

Why this answer

The apt module is for Debian-based systems, and yum is for Red Hat-based systems. Both manage packages.

106
MCQeasy

A user wants to execute a command inside a running Docker container named 'db'. Which command should be used?

A.docker attach db
B.docker start -i db
C.docker run -it db bash
D.docker exec -it db bash
AnswerD

The docker exec command runs a process inside an already-running container, with -it allocating an interactive TTY and bash as the shell. This satisfies the requirement to execute a command within the running 'db' container, unlike docker run which starts a new container.

Why this answer

'docker exec -it db bash' runs a new interactive process (bash) inside the already-running container named 'db', attaching a TTY and keeping stdin open. This is the standard way to get a shell or run a one-off command in a live container without disturbing its main process. It does not restart or replace the container's entrypoint.

Exam trap

The trap is conflating 'docker attach' (attach to PID 1 stdio) with 'docker exec' (spawn a new process), and confusing 'docker run' (new container) with operating on an existing one.

How to eliminate wrong answers

Option A is wrong because 'docker attach db' attaches to the container's existing PID 1 stdio stream, which can disrupt the main process and does not spawn a new shell; detaching can also accidentally stop the container. Option B is wrong because 'docker start -i db' starts a stopped container and attaches interactively to its main process — it does not open a shell inside a running container. Option C is wrong because 'docker run -it db bash' creates and starts a brand-new container from the 'db' image, not the running container named 'db', so it operates on a separate instance.

107
MCQmedium

A Linux administrator maintains a Bash deployment script that runs unattended from cron. The script currently contains `set -e` and `set -u`, but it silently continues past a failing command inside a pipeline such as `tar -czf backup.tgz /srv | tee /var/log/backup.log`. The administrator wants the script to abort whenever any element of that pipeline returns a non-zero status. Which line should be added to the top of the script?

A.set -v
B.set -x
C.set -n
D.set -o pipefail
AnswerD

With pipefail enabled, the exit status of a pipeline becomes the rightmost non-zero status of any command in it, so a failure in tar propagates and set -e terminates the script. This directly addresses the scenario where the pipeline's final command (tee) succeeds and masks the earlier failure, keeping unattended cron runs from continuing on corrupt backups.

Why this answer

Pipelines report only the last command's status by default, so a failing producer such as tar can be masked by a succeeding consumer such as tee. Enabling pipefail makes the pipeline return the first non-zero status encountered, which combines with set -e to abort the unattended script immediately. This preserves the existing error-handling design while closing the pipeline gap.

Exam trap

The trap here is assuming that set -e alone covers every failure, when it ignores all but the final command's status in a pipeline unless pipefail is also enabled.

108
Multi-Selectmedium

A system administrator is writing an Ansible playbook to manage a web server. Which three of the following are valid Ansible modules for system administration? (Choose THREE.)

Select 3 answers
A.service
B.copy
C.useradd
D.apt
E.chmod
AnswersA, B, D

The `service` module manages system daemons on the target host, starting, stopping, enabling or restarting services such as httpd or nginx. It satisfies the stem's requirement for a valid system-administration module by controlling service state declaratively, and it works across systemd, SysV init and other init systems without extra configuration.

Why this answer

apt, service, and copy are standard Ansible modules for package management, service control, and file copying.

109
MCQhard

A Bash script uses getopts to parse command-line options. The options are -a (requires an argument) and -b (flag). Which code correctly implements this and stores the argument for -a in $optarg?

A.while getopts 'a:b' opt; do case $opt in a) arg=$OPTARG ;; b) flag=true ;; esac done
B.while getopts 'ab:' opt; do case $opt in a) arg=$OPTARG ;; b) flag=true ;; esac done
C.while getopts 'a:b' opt; do case $opt in a) arg=$optarg ;; b) flag=true ;; esac done
D.while getopts ':a:b' opt; do case $opt in a) arg=$OPTARG ;; b) flag=true ;; esac done
AnswerA

The colon after 'a' in the optstring signals that -a requires an argument, which getopts stores in $OPTARG; 'b' without a colon is a flag. The case statement then assigns $OPTARG to arg, satisfying the requirement.

Why this answer

The getopts built-in parses options and stores the option argument in the shell variable OPTARG (uppercase). The option string 'a:b' indicates that -a requires an argument (colon after a) and -b is a flag (no colon). The loop uses 'opt' as the variable to hold the current option, and the case statement correctly assigns $OPTARG to arg for -a.

This matches option A.

Exam trap

XK0-006 often tests the case sensitivity of OPTARG and the placement of colons in the option string, so candidates must remember that OPTARG is uppercase and that a colon after an option letter indicates it requires an argument.

How to eliminate wrong answers

Option B is wrong because the option string 'ab:' incorrectly specifies that -b requires an argument, not -a. Option C is wrong because it uses lowercase $optarg, but getopts sets the uppercase $OPTARG variable. Option D is wrong because the leading colon in ':a:b' changes error handling behavior (silent mode) and is not needed for the described functionality; it also does not affect the argument storage, but the question asks for correct implementation, and the leading colon is unnecessary and alters error reporting.

110
MCQmedium

A bash script needs to test whether a string variable $NAME is non-empty and equals 'admin'. Which of the following conditionals is correct?

A.if [[ $NAME -ne '' && $NAME -eq 'admin' ]]; then
B.if [[ -n $NAME && $NAME == 'admin' ]]; then
C.if [ $NAME != '' ] && [ $NAME == 'admin' ]; then
D.if [ ! -z $NAME -a $NAME = 'admin' ]; then
AnswerB

The -n test confirms the string is non-empty, and && requires the equality check to also pass. Both conditions must hold for the branch to execute, precisely matching the stem's requirement that $NAME be populated and equal to 'admin'.

Why this answer

In bash, [[ -n $NAME ]] tests if the string is non-empty, and == compares strings. Using double brackets is safer for string comparison.

111
MCQhard

An administrator is writing a Dockerfile. They need to set a default command that can be overridden when running the container. Which instruction should be used?

A.RUN
B.CMD
C.ENTRYPOINT
D.EXPOSE
AnswerB

CMD sets the default executable or arguments for a container, and any command supplied at docker run overrides it. ENTRYPOINT instead fixes the executable and requires --entrypoint to replace, so CMD satisfies the overridable default required here.

Why this answer

CMD provides defaults that can be overridden by command-line arguments, while ENTRYPOINT cannot be easily overridden without --entrypoint.

112
Multi-Selecthard

A DevOps team uses Podman to run containers rootlessly. Which TWO of the following characteristics apply to rootless Podman compared to Docker? (Select TWO).

Select 2 answers
A.It can only run containers as root
B.It requires a running daemon at all times
C.It uses the same CLI syntax as Docker
D.It supports running containers without root privileges
E.It relies on a central registry for all images
AnswersC, D

Podman is designed to be a drop-in replacement for Docker CLI.

Why this answer

Podman does not require a daemon (no central daemon), and it can run containers without root privileges by default using user namespaces.

← PreviousPage 2 of 2 · 112 questions total

Ready to test yourself?

Try a timed practice session using only Automation, Orchestration, and Scripting questions.