CCNA Scripting Containers Questions

75 of 151 questions · Page 2/3 · Scripting Containers topic · Answers revealed

76
MCQmedium

A cloud engineer needs to automate the deployment of a new virtual machine with a specific configuration using Ansible. Which file format is typically used for Ansible playbooks?

B.YAML
C.XML
D.INI
AnswerB

Standard for playbooks.

Why this answer

Ansible playbooks are written in YAML (YAML Ain't Markup Language) because it is human-readable, supports complex data structures like lists and dictionaries, and is designed for configuration management. YAML's indentation-based syntax aligns with Ansible's declarative approach, allowing tasks, variables, and handlers to be defined cleanly without the overhead of brackets or tags.

Exam trap

The trap here is that candidates confuse the file format for playbooks (YAML) with other Ansible file types, such as JSON for dynamic inventory or INI for static inventory, leading them to select a technically valid but incorrect format for the specific question context.

How to eliminate wrong answers

Option A is wrong because JSON, while valid for Ansible inventory files or dynamic inventory scripts, is not the standard format for playbooks; playbooks rely on YAML's readability and support for comments. Option C is wrong because XML is verbose, uses angle-bracket tags, and is not natively supported by Ansible for playbook definitions, making it impractical for automation workflows. Option D is wrong because INI files are used for Ansible inventory configuration (e.g., listing hosts and groups), not for defining the ordered tasks and logic within a playbook.

77
Multi-Selecteasy

Which THREE of the following are valid systemd unit types?

Select 3 answers
A.timer
B.socket
C.system
D.cron
E.service
AnswersA, B, E

Valid unit type.

Why this answer

A is correct because `timer` is a valid systemd unit type used to schedule and trigger other units (typically services) based on time events, similar to cron but integrated with systemd. Timers can be monotonic (relative to system events) or real-time (calendar-based), and they are defined in `.timer` files.

Exam trap

CompTIA often tests the distinction between systemd-native unit types and external scheduling tools like cron, so candidates may mistakenly think `cron` is a systemd unit type because both handle scheduling, but systemd uses `timer` units instead.

78
MCQhard

A Linux administrator is responsible for a critical application that runs as a systemd service on a server. The application occasionally hangs, and the administrator wants to automate the restart if the service becomes unresponsive. The administrator writes a Bash script that checks if the service is active and responsive by pinging a local health endpoint. If the health check fails three consecutive times, the script restarts the service. The script is intended to run every minute via a cron job. However, after implementing the cron job, the service is restarted even when it is functioning correctly, causing unnecessary downtime. The administrator reviews the script and finds the following logic: #!/bin/bash SERVICE="myapp" COUNT_FILE="/tmp/${SERVICE}_failcount" if curl -f http://localhost:8080/health; then echo 0 > "$COUNT_FILE" else FAILS=$(cat "$COUNT_FILE" 2>/dev/null || echo 0) FAILS=$((FAILS + 1)) echo "$FAILS" > "$COUNT_FILE" if [ "$FAILS" -ge 3 ]; then systemctl restart "$SERVICE" echo 0 > "$COUNT_FILE" fi fi What is the most likely cause of the false restarts?

A.The count file is not being written because the script lacks write permissions to /tmp.
B.Multiple instances of the script are running concurrently due to cron timing, causing a race condition on the count file.
C.The script does not reset the count file after a successful health check.
D.The script does not handle the case where the count file does not exist on the first failure.
AnswerB

Without file locking, concurrent runs can overwrite each other's counts, leading to inaccurate failure counts and false restarts.

Why this answer

Option B is correct because the cron job runs the script every minute, but if the health check takes longer than a minute (e.g., due to network latency or a slow endpoint), multiple instances of the script can overlap. Each instance reads, increments, and writes the count file independently, causing a race condition where the fail count can be artificially inflated, leading to a false restart even when the service is healthy.

Exam trap

CompTIA often tests the misconception that a missing file or permission error is the root cause, when in reality the issue is a race condition from overlapping cron job executions.

How to eliminate wrong answers

Option A is wrong because the script writes to /tmp, which is world-writable by default, and the script runs as root (or a user with sufficient privileges) via cron, so permission issues are unlikely; if write permissions were missing, the script would fail entirely, not cause false restarts. Option C is wrong because the script does reset the count file to 0 after a successful health check (the `echo 0 > "$COUNT_FILE"` line), so this is not the cause of false restarts. Option D is wrong because the script handles a missing count file on the first failure by using `cat "$COUNT_FILE" 2>/dev/null || echo 0`, which defaults to 0 if the file does not exist, so this is not a bug.

79
MCQeasy

Based on the exhibit, how often does the healthcheck.sh script run?

A.Every 5 days
B.Every 5 minutes
C.Every 5 hours
D.Every 5 seconds
AnswerB

Correct interpretation.

Why this answer

The cron expression `*/5 * * * *` in the crontab file means the script runs every 5 minutes. The `*/5` in the minute field triggers execution every 5 minutes, while the asterisks in the hour, day, month, and weekday fields mean every hour, every day, every month, and every day of the week, respectively.

Exam trap

CompTIA often tests the distinction between cron fields: candidates confuse the minute field with the hour field, thinking `*/5` means every 5 hours instead of every 5 minutes, especially when the context is a health check that might logically run less frequently.

How to eliminate wrong answers

Option A is wrong because a cron expression with `*/5` in the minute field does not represent days; a 5-day interval would require `*/5` in the day-of-month field (e.g., `0 0 */5 * *`). Option C is wrong because every 5 hours would use `0 */5 * * *` (minute set to 0, hour field with `*/5`). Option D is wrong because cron does not support sub-minute intervals; the smallest unit is one minute, so every 5 seconds is impossible with standard cron.

80
Matchingmedium

Match each Linux command to its primary function.

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

Concepts
Matches

List block devices

List open files

Manage partition tables

Inform OS of partition changes

Display block device attributes

Why these pairings

These commands are used for storage administration.

81
MCQeasy

Which command will show the current running processes in real time?

A.top
B.pstree
C.ps aux
D.htop
AnswerA

top continuously updates the list of processes.

Why this answer

top provides a real-time view of running processes. ps gives a snapshot, htop is an alternative, and pstree shows a process tree.

82
MCQhard

Your organization uses Ansible for configuration management across 500 servers. The management server is a Linux workstation. You have written a playbook to deploy a new monitoring agent. The playbook works on all test machines but fails on production machines at the 'Gather Facts' stage with the error: 'fatal: [server1]: FAILED! => {"msg": "Timed out waiting for privilege escalation prompt: become method 'sudo' requires a password" }'. All production servers have the same sudoers configuration. You have confirmed that the user 'ansible' has passwordless sudo configured correctly. What is the most likely cause?

A.The production servers have a different SSH key
B.The SSH timeout is too low
C.The ansible_become_password is not set in the inventory
D.The become_user is set incorrectly
AnswerC

Without ansible_become_password, Ansible waits for a password prompt; setting it to empty acknowledges passwordless sudo.

Why this answer

The error indicates that Ansible's privilege escalation (sudo) is prompting for a password, even though the 'ansible' user has passwordless sudo configured. This typically occurs when the 'ansible_become_password' variable is not set or is empty in the inventory, causing Ansible to wait for a password prompt that never comes. Since the playbook works on test machines, the difference is likely that the inventory for production lacks the required 'ansible_become_password' or 'ansible_become' settings, or the variable is not being passed correctly.

Exam trap

The trap here is that candidates assume passwordless sudo means no 'become_password' is needed, but Ansible still requires the variable to be explicitly set (even to an empty string) or the 'become' method to be configured correctly to avoid waiting for a prompt.

How to eliminate wrong answers

Option A is wrong because a different SSH key would cause an authentication failure at the SSH connection stage, not a privilege escalation timeout after successful login. Option B is wrong because an SSH timeout would produce a 'Connection timed out' error, not a 'Timed out waiting for privilege escalation prompt' error. Option D is wrong because setting 'become_user' incorrectly would typically result in a 'user does not exist' or 'permission denied' error, not a timeout waiting for a sudo password prompt.

83
Multi-Selecteasy

Which TWO characteristics apply to Docker containers compared to virtual machines? (Choose two.)

Select 2 answers
A.Containers share the host kernel
B.Containers have faster startup times
C.Containers provide stronger isolation
D.Containers include a full guest operating system
E.Containers require a hypervisor
AnswersA, B

Containers share the host kernel, making them more efficient.

Why this answer

Docker containers share the host kernel, unlike virtual machines which each run their own kernel. This is because containers are implemented as isolated user-space instances (using namespaces and cgroups) that all run on top of the same host OS kernel. This shared kernel architecture eliminates the need for a separate guest OS per container, making containers lightweight and fast to start.

Exam trap

CompTIA often tests the misconception that containers provide stronger isolation than VMs, but the correct understanding is that VMs offer hardware-level isolation via a hypervisor, while containers share the host kernel and thus have weaker isolation boundaries.

84
MCQeasy

A systems administrator writes a Bash script named 'backup.sh' and wants it to run with the Bash shell. Which line should appear first in the script?

A.# This is a bash script
B.#!/bin/bash
C.#/bin/bash
D.#!/bin/sh
AnswerB

Correct shebang for Bash.

Why this answer

The shebang line `#!/bin/bash` is required as the first line to instruct the operating system to execute the script using the Bash shell interpreter located at `/bin/bash`. Without this line, the script may be run by a different shell (e.g., `/bin/sh`), leading to syntax or behavior differences. The shebang must start with `#!` followed by the absolute path to the interpreter.

Exam trap

CompTIA often tests the distinction between a shebang (`#!`) and a comment (`#`), and the trap here is that candidates may confuse `#!/bin/sh` as equivalent to `#!/bin/bash` or forget the exclamation mark entirely, leading them to choose option C or D.

How to eliminate wrong answers

Option A is wrong because `# This is a bash script` is a comment, not a shebang; the kernel ignores it and may fall back to the default shell, which is not guaranteed to be Bash. Option C is wrong because `#/bin/bash` lacks the exclamation mark (`!`), so it is treated as a regular comment and does not invoke the Bash interpreter. Option D is wrong because `#!/bin/sh` points to the POSIX shell, which may be Dash or another shell on many Linux distributions, not Bash; Bash-specific features (e.g., `[[ ]]`, arrays) would fail.

85
MCQmedium

An administrator needs to create a shell script that will be executed by a non-login shell. The script requires access to environment variables set in the user's profile. Which file should the script source to ensure these variables are available?

A.~/.bashrc
B./etc/profile
C.~/.profile
D.~/.bash_profile
AnswerA

Correct. The .bashrc file is executed for non-login interactive shells and often contains environment variables.

Why this answer

Option A is correct because ~/.bashrc is the file sourced by non-login interactive shells in Bash. When a script is executed by a non-login shell, it does not read ~/.bash_profile or ~/.profile; instead, it reads ~/.bashrc. By sourcing ~/.bashrc within the script, the administrator ensures that environment variables defined there (e.g., PATH, custom aliases) are available to the script.

Exam trap

The trap here is that candidates often confuse ~/.bash_profile and ~/.bashrc, assuming that any user-specific profile file is sourced by all shells, but the key distinction is that non-login shells only source ~/.bashrc, not the login-specific profile files.

How to eliminate wrong answers

Option B is wrong because /etc/profile is a system-wide profile file sourced only by login shells, not by non-login shells. Option C is wrong because ~/.profile is a login shell initialization file (used by Bourne-compatible shells) and is not read by non-login shells. Option D is wrong because ~/.bash_profile is also a login shell initialization file for Bash; non-login shells do not source it.

86
MCQhard

Which command will show the environment variables for a specific process?

A.cat /proc/$PID/environ
B.set
C.printenv
D.env
AnswerA

Reading /proc/<pid>/environ displays the environment variables of that specific process.

Why this answer

The `/proc/[PID]/environ` file contains the environment variables that were set when the process was started. Reading this file with `cat` displays the exact environment of a specific process, which is not possible with shell built-ins or user-level commands that only show the current shell's environment.

Exam trap

CompTIA often tests the distinction between commands that show the current shell's environment (`set`, `printenv`, `env`) versus the `/proc` filesystem method that targets a specific process, leading candidates to pick a shell command instead of the process-specific file.

How to eliminate wrong answers

Option B is wrong because `set` displays all shell variables (including environment and local variables) for the current shell session, not for a specific process. Option C is wrong because `printenv` prints the environment variables of the current shell, not of an arbitrary process. Option D is wrong because `env` lists or modifies the environment of the current shell, and cannot target a specific process by PID.

87
MCQmedium

A script uses 'set -e' and then calls a function that returns a non-zero exit status. The script exits unexpectedly. Which of the following should be added to the function to prevent the script from exiting?

A.return 0 after the command
B.set +e inside the function
C.exit 0
D.trap '' ERR
AnswerB

Disables exit-on-error for the function, allowing non-zero exit codes without terminating.

Why this answer

The `set -e` directive causes the shell to exit immediately if any command returns a non-zero exit status. When a function called from such a script returns a non-zero status, the script exits. Adding `set +e` inside the function disables this behavior for the function's scope, allowing the function to handle errors internally without terminating the entire script.

Exam trap

The trap here is that candidates often think `return 0` or `exit 0` will override the non-zero exit status, but they fail to realize that `set -e` causes the script to exit immediately when the command fails, before any subsequent `return` or `exit` statement is executed.

How to eliminate wrong answers

Option A is wrong because `return 0` after the command would only succeed if the command itself does not cause an exit before the return statement; if the command fails and `set -e` is active, the script exits before reaching the `return 0`. Option C is wrong because `exit 0` would immediately terminate the script with a success code, which defeats the purpose of preventing an unexpected exit and does not allow the function to continue or return control to the caller. Option D is wrong because `trap '' ERR` prevents the ERR trap from running but does not disable the `set -e` behavior; the script will still exit on a non-zero exit status from any command.

88
MCQhard

A Kubernetes pod has a container that fails with CrashLoopBackOff. The administrator runs 'kubectl logs pod-name' but sees no output. What is the most likely cause?

A.The container exited before writing to stdout, and logs need to be retrieved with 'kubectl logs --previous'.
B.The container has no logging driver configured.
C.The log file is rotated and deleted.
D.The pod is not scheduled on any node.
AnswerA

Correct: use --previous to see previous container logs.

Why this answer

When a container enters CrashLoopBackOff, it restarts repeatedly. If 'kubectl logs pod-name' shows no output, it means the current (restarted) container has not written anything to stdout yet. The previous instance of the container may have written logs before crashing, and those logs are accessible using 'kubectl logs --previous' to retrieve the output from the terminated container.

Exam trap

The trap here is that candidates assume 'no output' means logs are missing or misconfigured, when in fact the current container simply hasn't written anything yet, and the previous container's logs are still available via --previous.

How to eliminate wrong answers

Option B is wrong because Kubernetes does not require a separate logging driver configuration; it captures container stdout/stderr by default via the container runtime interface (CRI). Option C is wrong because log rotation and deletion would not cause an empty log output on a freshly restarted container; the current container simply hasn't produced logs yet. Option D is wrong because if the pod were not scheduled on any node, 'kubectl logs' would return an error like 'Error from server: pod is not scheduled', not an empty output.

89
MCQhard

A Docker container using port 8080 fails to start with the error 'port is already allocated'. Which command should the administrator use to identify the process using that port?

A.ss -tan
B.ss -tln
C.ss -tlnp
D.ss -r
AnswerC

Shows listening TCP ports with PID.

Why this answer

Option C is correct because the `ss -tlnp` command lists TCP listening sockets (`-l`) with numeric addresses (`-n`) and shows the process identifier (PID) and process name (`-p`) that owns each socket. This directly identifies which process has bound port 8080, allowing the administrator to resolve the 'port is already allocated' error.

Exam trap

The trap here is that candidates may choose `ss -tln` (option B) because it shows listening ports, but they forget the `-p` flag is required to identify the process, leading to incomplete troubleshooting.

How to eliminate wrong answers

Option A is wrong because `ss -tan` lists all TCP sockets (including non-listening ones) without showing process ownership, so it cannot identify the process using port 8080. Option B is wrong because `ss -tln` lists TCP listening sockets but omits the `-p` flag, so it does not display the PID or process name, leaving the process unidentified. Option D is wrong because `ss -r` attempts to resolve hostnames and is not a valid flag combination for socket statistics; it does not list sockets or processes.

90
Multi-Selecthard

A developer is writing a shell script that needs to handle errors. Which THREE of the following are best practices for robust script error handling?

Select 3 answers
A.Ignore errors to simplify the script
B.Check the exit code of commands using $?
C.Use set +e to allow the script to continue on error
D.Use set -e to exit on any command failure
E.Use trap to catch signals and clean up
AnswersB, D, E

Allows conditional handling.

Why this answer

Option B is correct because checking the exit code of commands using `$?` allows the script to conditionally handle failures based on the specific return value of each command. This is a fundamental error-handling technique in shell scripting, as every command returns an exit code (0 for success, non-zero for failure), and inspecting `$?` immediately after a command lets the developer decide how to respond to that specific error.

Exam trap

CompTIA often tests the distinction between `set -e` and `set +e` and the proper use of `$?` versus relying solely on `set -e`, where candidates may incorrectly think that `set +e` is a best practice for error handling when it actually disables automatic exit on error.

91
MCQhard

A storage administrator needs to automate the expansion of an LVM volume group when free space drops below 10%. The script must add a new physical volume from a spare disk. Which of the following commands should be used in the script to add the new disk to the volume group?

A.pvcreate /dev/sdb1 && vgextend vg01 /dev/sdb1
B.vgcreate vg01 /dev/sdb
C.vgextend vg01 /dev/sdb1
D.lvresize -L +100G vg01
AnswerA

Initializes the partition as a PV and adds it to the VG.

Why this answer

Option A is correct because it first uses `pvcreate` to initialize the spare disk partition `/dev/sdb1` as a physical volume, which is a prerequisite for adding it to an LVM volume group. Then `vgextend vg01 /dev/sdb1` adds that initialized physical volume to the existing volume group `vg01`, expanding its total capacity. This two-step process ensures the disk is properly prepared for LVM management before being incorporated into the volume group.

Exam trap

The trap here is that candidates often think `vgextend` alone is sufficient, forgetting that LVM requires the device to be initialized as a physical volume with `pvcreate` before it can be added to a volume group.

How to eliminate wrong answers

Option B is wrong because `vgcreate` creates a new volume group, but the requirement is to add a disk to an existing volume group, not create a new one. Option C is wrong because `vgextend` alone will fail if `/dev/sdb1` has not been initialized as a physical volume with `pvcreate` first; LVM requires the device to be marked as a PV before it can be added to a VG. Option D is wrong because `lvresize` resizes a logical volume, not a volume group, and the task is to expand the volume group by adding a new physical volume, not to resize a logical volume.

92
MCQhard

A sysadmin needs to set a default gateway for a network interface. Which command(s) accomplish this?

A.netstat -rn
B.route add default gw 192.168.1.1
C.ip route add default via 192.168.1.1
D.Both A and B
AnswerD

Both route and ip can be used to add a default gateway.

Why this answer

Option D is correct because both `route add default gw 192.168.1.1` (option B) and `ip route add default via 192.168.1.1` (option C) can set a default gateway on Linux. The `route` command is legacy but still functional, while `ip route` is the modern net-tools replacement. Option A (`netstat -rn`) only displays the routing table and does not add a gateway, so it alone cannot accomplish the task.

Exam trap

The trap here is that candidates may think only the modern `ip route` command works, forgetting that the legacy `route` command is still accepted on many Linux distributions, or they may mistakenly believe `netstat -rn` can set a route because it displays routing information.

How to eliminate wrong answers

Option A is wrong because `netstat -rn` is a read-only command that displays the kernel routing table; it does not modify or set a default gateway. Option B is wrong because `route add default gw 192.168.1.1` is a valid legacy command that does set a default gateway, so it is not incorrect. Option C is wrong because `ip route add default via 192.168.1.1` is also a valid modern command that sets a default gateway, so it is not incorrect.

The question asks which command(s) accomplish the task, and both B and C work, making D the correct answer.

93
MCQeasy

A Linux administrator writes a script that uses bash-specific features like arrays and process substitution. Which shebang should be used?

A.#!/bin/bash
B.#!/bin/sh
C.#!/usr/bin/python3
D.#!/bin/ksh
AnswerA

Bash supports advanced features like arrays and process substitution.

Why this answer

The correct shebang is #!/bin/bash because the script uses bash-specific features such as arrays and process substitution. The shebang line tells the system to execute the script with the specified interpreter; /bin/bash is the Bourne Again SHell, which supports these features, while /bin/sh may be a POSIX shell that lacks them.

Exam trap

The trap here is that candidates often assume /bin/sh is always bash or that any shell can run bash-specific syntax, but on many Linux distributions /bin/sh is a different shell (e.g., dash) that lacks these extensions.

How to eliminate wrong answers

Option B is wrong because /bin/sh is often a POSIX-compliant shell (like dash on Debian) that does not support bash-specific features such as arrays and process substitution, causing the script to fail. Option C is wrong because /usr/bin/python3 is the Python 3 interpreter, which cannot execute bash syntax. Option D is wrong because /bin/ksh is the Korn shell, which has its own syntax and may not support bash-specific features like process substitution in the same way.

94
Multi-Selectmedium

A system administrator wants to automate server configuration and management across multiple Linux hosts. Which TWO tools are configuration management solutions designed for this purpose? (Choose two.)

Select 2 answers
A.Docker
B.Nagios
C.Kubernetes
D.Puppet
E.Ansible
AnswersD, E

Puppet is a configuration management tool.

Why this answer

Puppet is a mature configuration management tool that uses a declarative language (Puppet DSL) to define desired system states and enforces them via a client-server (agent-master) architecture over HTTPS. It automates server configuration across multiple hosts by applying manifests that specify packages, services, files, and users, ensuring consistency without manual intervention.

Exam trap

The trap here is that candidates confuse containerization (Docker) or orchestration (Kubernetes) with configuration management, or mistake monitoring (Nagios) for a tool that configures systems, when the question specifically asks for tools that automate server configuration and management across multiple hosts.

95
MCQhard

A developer writes a Dockerfile that installs multiple packages. To reduce the final image size, which of the following practices is most effective?

A.Use a multi-stage build.
B.Combine multiple RUN commands into a single RUN instruction.
C.Use apt-get clean after each installation.
D.Use a minimal base image like alpine.
AnswerB

Reduces number of layers, decreasing image size.

Why this answer

Combining multiple RUN commands into a single RUN instruction reduces the number of layers created in the Docker image. Each RUN instruction creates a new layer, and by merging them, you avoid storing intermediate files (e.g., package cache) across separate layers, which significantly shrinks the final image size. This is a direct and effective method for minimizing image footprint when installing multiple packages.

Exam trap

CompTIA often tests the misconception that using a minimal base image or cleaning up in separate steps is sufficient, when in fact the layer persistence model means only combining RUN commands (and cleaning within the same layer) truly eliminates intermediate file bloat.

How to eliminate wrong answers

Option A is wrong because multi-stage builds primarily reduce image size by separating build-time dependencies from the final runtime image, but they do not directly address the layer overhead from multiple RUN instructions during package installation. Option C is wrong because apt-get clean only removes cached package files within a single layer; if used in separate RUN instructions, the cache is already stored in a previous layer and cannot be reclaimed, making it ineffective for reducing final image size. Option D is wrong because while using a minimal base image like Alpine reduces the base layer size, it does not mitigate the layer bloat caused by multiple RUN instructions; the question specifically asks about the practice for reducing image size when installing multiple packages, and combining RUN commands is more directly impactful.

96
MCQmedium

A DevOps engineer is designing a CI/CD pipeline for a microservices application. The pipeline should build a Docker image, run unit tests, and if successful, push the image to a private registry. Which tool is best suited for orchestrating this pipeline?

A.Git
B.cron
C.Jenkins
D.Ansible
AnswerC

Jenkins is designed for building, testing, and deploying software continuously.

Why this answer

Jenkins is a widely adopted CI/CD automation server that excels at orchestrating complex pipelines, including building Docker images, running unit tests, and pushing images to a private registry. Its pipeline-as-code feature (Jenkinsfile) allows defining stages, triggers, and post-build actions, making it the best fit for this microservices CI/CD workflow.

Exam trap

CompTIA often tests the distinction between CI/CD orchestration tools and general automation or scheduling tools; the trap here is that candidates may confuse Ansible's automation capabilities with CI/CD pipeline orchestration, or think cron can handle complex multi-step workflows with conditional logic.

How to eliminate wrong answers

Option A is wrong because Git is a distributed version control system used for source code management, not for orchestrating CI/CD pipelines or executing build/test/deploy steps. Option B is wrong because cron is a time-based job scheduler in Unix/Linux that can only run simple scripts at fixed intervals; it lacks pipeline logic, dependency management, and integration with Docker registries or test frameworks. Option D is wrong because Ansible is a configuration management and automation tool primarily used for provisioning and infrastructure as code, not for continuous integration pipeline orchestration; it does not natively support event-driven CI/CD triggers or pipeline stages.

97
MCQmedium

An administrator uses Podman containers and wants them to start automatically when the host boots. Which method should be used?

A.podman auto-start on
B.podman generate systemd --new --files, then systemctl enable container-name
C.podman register-service container-name
D.Add a command to /etc/rc.local to start the container
AnswerB

This creates systemd unit files and enables them for automatic startup.

Why this answer

Option B is correct because Podman does not have a built-in auto-start mechanism; instead, it integrates with systemd by generating a systemd service unit file using `podman generate systemd --new --files`. This creates a service that manages the container as a transient unit, and then `systemctl enable` makes it start automatically at boot. This approach leverages systemd's dependency-based boot sequencing and ensures the container is restarted if it fails.

Exam trap

The trap here is that candidates may assume Podman has a simple built-in auto-start toggle like Docker's `--restart always` flag, but Podman requires explicit systemd integration for boot-time startup, and the exam tests knowledge of the correct command sequence (`generate systemd` followed by `systemctl enable`).

How to eliminate wrong answers

Option A is wrong because `podman auto-start on` is not a valid Podman command; Podman does not have a native auto-start feature. Option C is wrong because `podman register-service` is not a real Podman subcommand; Podman uses systemd integration, not a separate registration command. Option D is wrong because while `/etc/rc.local` can start containers, it is a legacy method that lacks systemd's dependency management, restart policies, and logging, making it unreliable for production container management.

98
Multi-Selectmedium

Which TWO options are valid ways to pass environment variables to a Docker container?

Select 2 answers
A.--var VAR=value
B.--env-file file
C.-e VAR=value
D.--variable VAR=value
E.-v VAR=value
AnswersB, C

This loads environment variables from a file.

Why this answer

The correct options are A and B. -e and --env-file are standard methods. -v is for volumes, and --variable is not a valid flag.

99
Multi-Selecteasy

Which TWO commands are used to view a file page by page?

Select 2 answers
A.tail
B.more
C.cat
D.head
E.less
AnswersB, E

more displays a file page by page.

Why this answer

The `more` and `less` commands are both pager utilities that display file contents one screen at a time, allowing the user to scroll forward (and in the case of `less`, backward) through the output. `more` is the traditional pager that pauses after each screenful, while `less` is a more feature-rich pager that supports backward navigation and searching. Both are correct for viewing a file page by page.

Exam trap

The trap here is that candidates may confuse `more` and `less` as being mutually exclusive or think only one is correct, but the question asks for TWO commands, and both are valid pagers; also, some might mistakenly think `cat` with a pipe to `more` or `less` counts, but the question asks for commands used directly to view a file page by page.

100
MCQmedium

Which shebang ensures maximum portability across systems for a Python script?

A.#!/usr/bin/env python3
B.#!/bin/python
C.#!/usr/bin/python
D.#!/usr/local/bin/python3
AnswerA

env uses PATH to locate python3, making it portable across different systems.

Why this answer

Option A is correct because `#!/usr/bin/env python3` uses the `env` utility to locate the `python3` interpreter in the user's `PATH`, making the script portable across different Unix-like systems where Python 3 may be installed in various directories (e.g., `/usr/bin/python3`, `/usr/local/bin/python3`). This shebang avoids hardcoding an absolute path, which is the key to maximum portability.

Exam trap

CompTIA often tests the misconception that hardcoding a common path like `/usr/bin/python` is safe, but the trap is that this path may point to Python 2 on many systems, while the question explicitly requires Python 3 and maximum portability.

How to eliminate wrong answers

Option B is wrong because `/bin/python` is a hardcoded path that often points to Python 2 on many systems, not Python 3, and may not exist at all on modern distributions that have moved Python 3 to `/usr/bin/python3`. Option C is wrong because `#!/usr/bin/python` is a hardcoded path that typically refers to Python 2 on many systems (e.g., RHEL/CentOS 7) and may not be present or may point to a different version, reducing portability. Option D is wrong because `#!/usr/local/bin/python3` is a hardcoded path that assumes Python 3 is installed in `/usr/local/bin`, which is not the default location on most Linux distributions (e.g., Debian/Ubuntu use `/usr/bin/python3`), breaking portability.

101
MCQmedium

A systems administrator wants to build a custom Docker image from a Dockerfile located in the current directory. Which command should be used?

A.docker create .
B.docker commit .
C.docker build .
D.docker image build .
AnswerC

Builds from Dockerfile.

Why this answer

The `docker build .` command reads the Dockerfile from the current directory and builds a custom Docker image from its instructions. This is the standard command for building an image from a Dockerfile, where the dot represents the build context (the current directory).

Exam trap

The trap here is that candidates may confuse `docker build` with the deprecated `docker image build` syntax or mistakenly think `docker commit` can build from a Dockerfile, when it actually captures container state changes.

How to eliminate wrong answers

Option A is wrong because `docker create .` creates a new container from an existing image, not from a Dockerfile; it expects an image name, not a path. Option B is wrong because `docker commit .` creates a new image from a container's changes, not from a Dockerfile; it requires a container ID or name, not a directory. Option D is wrong because `docker image build .` is not a valid Docker command; the correct subcommand is `docker build`, not `docker image build`.

102
MCQhard

A system administrator is using Ansible to deploy a web application across multiple servers. The playbook uses a variable `app_version` defined in a group_vars file for the `webservers` group. The playbook fails with the error: 'ERROR! 'app_version' is undefined'. The administrator confirms that the variable is correctly spelled and defined in `/etc/ansible/group_vars/webservers`. The playbook runs successfully on the Ansible control node but fails on all managed nodes. What is the most likely cause of this error?

A.The variable `app_version` is misspelled in the task.
B.The group_vars file is not being loaded because the inventory path is not correctly specified.
C.The playbook uses `loop` keyword incorrectly.
D.The playbook is missing a `vars_files` directive to include the variable file.
AnswerB

Ansible loads group_vars relative to the inventory; incorrect path causes undefined variables.

Why this answer

The error 'app_version' is undefined despite the variable being correctly defined in `/etc/ansible/group_vars/webservers` indicates that Ansible is not loading that group_vars file. This typically happens when the inventory path specified in the ansible.cfg or command line does not point to the directory containing the group_vars folder. Ansible automatically loads group_vars only from the directory where the inventory file resides, not from a hardcoded path like `/etc/ansible/group_vars/` unless the inventory is also located there.

Exam trap

The trap here is that candidates assume group_vars files are always loaded from a global path like `/etc/ansible/group_vars/`, but Ansible only loads them relative to the inventory location, not from an absolute path unless the inventory itself is in that directory.

How to eliminate wrong answers

Option A is wrong because the administrator confirmed the variable is correctly spelled in the task, so a misspelling is not the issue. Option C is wrong because the error message is about an undefined variable, not a loop syntax error; an incorrect `loop` keyword would produce a different error like 'ERROR! 'loop' is not a valid attribute'. Option D is wrong because group_vars files are automatically loaded by Ansible based on the inventory group name; a `vars_files` directive is not required for group_vars, only for custom variable files not following the group_vars naming convention.

103
MCQmedium

An Ansible playbook includes the following task: 'ansible.builtin.service: name=nginx state=restarted'. However, the playbook fails with 'module not found'. What is the most likely cause?

A.The playbook is not in the correct directory.
B.The module name uses the wrong FQCN. The correct module is 'ansible.builtin.systemd_service'.
C.The target host does not have nginx installed.
D.The control node does not have Python installed.
AnswerB

The module 'service' has been replaced by 'systemd_service' in newer Ansible.

Why this answer

The error 'module not found' indicates that Ansible cannot locate the module specified in the task. The correct fully qualified collection name (FQCN) for the service module in the `ansible.builtin` collection is `ansible.builtin.service`, not `ansible.builtin.systemd_service`. The `systemd_service` module does not exist in the `ansible.builtin` collection; the correct module for managing systemd services is `ansible.builtin.systemd`, but the standard service module (`ansible.builtin.service`) works across init systems and is the appropriate choice here.

Exam trap

The trap here is that candidates may assume a systemd-specific module name exists (like `systemd_service`) because of the `state=restarted` parameter, but the correct module is simply `ansible.builtin.service`, which handles restarts across all init systems.

How to eliminate wrong answers

Option A is wrong because the playbook's directory location does not affect module resolution; Ansible searches for modules in its configured library paths and collections, not the playbook's directory. Option C is wrong because the error is 'module not found', not a failure related to nginx not being installed; if nginx were missing, the error would be about package or service state, not module resolution. Option D is wrong because the control node's Python installation is not the direct cause of a 'module not found' error; Python is required for module execution, but the error here is about the module name not being recognized by Ansible's module loader.

104
MCQhard

A script needs to iterate over all .txt files in a directory. Which loop structure correctly implements this?

A.while read line; do
B.select option; do
C.until condition; do
D.for f in *.txt; do
AnswerD

This bash loop iterates over each .txt file in the current directory.

Why this answer

The `for f in *.txt; do` loop is correct because it uses shell globbing to expand `*.txt` into a list of all .txt filenames in the current directory, then iterates over each filename. This is the standard and most efficient way to process a set of files matching a pattern in Bash and POSIX shell scripting.

Exam trap

The trap here is that candidates may confuse `while read` (which processes lines of text) with iterating over files, or think `select` is a general-purpose loop, when in fact only `for` with a glob pattern directly matches the requirement of iterating over all .txt files.

How to eliminate wrong answers

Option A is wrong because `while read line; do` reads lines from stdin or a file, not filenames matching a pattern, and would require piping `ls *.txt` or similar, which is fragile and not the intended loop for file iteration. Option B is wrong because `select option; do` is used to present a menu of choices to the user for interactive selection, not for iterating over files. Option C is wrong because `until condition; do` runs the loop until a condition becomes true, and does not inherently iterate over a list of files; it would need an explicit counter or file list to work.

105
MCQhard

A sysadmin is tasked with creating a script that will run only on weekdays at 9:00 AM using cron. The script should not run on holidays. Which approach best achieves this requirement?

A.Use systemd timers with a calendar specification that excludes holidays
B.Use cron to run at 9:00 on weekdays, and include a test in the script that checks a holiday list
C.Use cron to run at 9:00 every day, and include conditional logic to abort on weekends
D.Use `at` to schedule the job individually each weekday morning
AnswerB

This ensures the script runs on weekdays but can skip holidays by checking within the script.

Why this answer

Option B is correct because cron can schedule the script to run at 9:00 AM on weekdays using the day-of-week field (e.g., `0 9 * * 1-5`), and the script itself can check a holiday list (e.g., a file or API) to exit early on holidays. This approach cleanly separates scheduling from holiday logic, avoiding cron's lack of built-in holiday awareness.

Exam trap

CompTIA often tests the misconception that cron can directly handle holidays, when in fact cron has no concept of holidays and requires external logic (like a script check) to skip them.

How to eliminate wrong answers

Option A is wrong because systemd timers do not natively support excluding arbitrary holidays; they use calendar expressions that can only exclude fixed patterns (e.g., specific dates), not dynamic holiday lists. Option C is wrong because running the script every day and aborting on weekends wastes resources and adds unnecessary complexity; cron's weekday field already handles weekends efficiently. Option D is wrong because using `at` requires manual or scripted scheduling each morning, which is impractical for a recurring weekday job and lacks the built-in weekday filtering that cron provides.

106
MCQeasy

Sarah is a Linux systems administrator for a company that runs a web application inside a Podman container. The container is launched using a systemd service file on a Red Hat Enterprise Linux 8 server. The service file is located at /etc/systemd/system/webapp.service and includes an ExecStart directive that runs `podman run -d --name webapp -p 80:80 nginx`. The server was recently rebooted for kernel updates. After the reboot, the web application is not responding. Sarah logs in and runs `systemctl status webapp.service`, which shows the service is 'disabled' and 'inactive'. She wants to ensure that the container starts automatically after every future reboot. What should Sarah do?

A.Add the line `@reboot /usr/bin/podman start webapp` to root's crontab.
B.Modify the container image to include a restart policy of 'always'.
C.Run `systemctl enable webapp.service` and then start the service.
D.Run `podman generate systemd --new --name webapp` to create a new systemd unit.
AnswerC

Correct: Enabling the systemd service ensures it starts on boot.

Why this answer

Option C is correct because `systemctl enable webapp.service` creates the necessary symlinks to start the service automatically at boot, and `systemctl start webapp.service` immediately starts the container. Since the service is currently disabled and inactive, enabling it ensures the systemd unit is triggered on future reboots, which will execute the `ExecStart` command to run the Podman container.

Exam trap

The trap here is that candidates confuse enabling a systemd service with setting a container's restart policy, thinking that `--restart=always` in the Podman command will survive a reboot, when in fact systemd must be enabled to launch the service after boot.

How to eliminate wrong answers

Option A is wrong because adding a `@reboot` cron job to start the container is a workaround that bypasses systemd's native boot management, leading to potential race conditions and lack of proper dependency handling. Option B is wrong because modifying the container image's restart policy (e.g., `--restart=always`) only affects the container's behavior within Podman, not the systemd service's enablement; after a reboot, the systemd service must be enabled to launch the container. Option D is wrong because `podman generate systemd --new --name webapp` creates a new systemd unit file, but the existing service file at `/etc/systemd/system/webapp.service` already exists and is correctly configured; generating a new unit would be redundant and does not address the need to enable the existing service.

107
MCQhard

A DevOps team wants to automatically run tests before every commit in a local Git repository. Which Git hook should be used?

A.post-receive
B.pre-commit
C.post-commit
D.pre-push
AnswerB

This hook is triggered before the commit is recorded, allowing tests to prevent a failing commit.

Why this answer

The pre-commit hook runs before a commit is created, making it the correct choice for automatically running tests before every commit in a local Git repository. This hook can validate code quality, run unit tests, or check for syntax errors, and if it exits with a non-zero status, the commit is aborted.

Exam trap

The trap here is confusing the timing of Git hooks: candidates often pick pre-push because they think of 'testing before pushing,' but the question explicitly asks about 'before every commit,' which requires the pre-commit hook.

How to eliminate wrong answers

Option A is wrong because post-receive is a server-side hook that runs after updates are pushed to a remote repository, not before a local commit. Option C is wrong because post-commit runs after the commit has already been created, so it cannot prevent a commit from being made. Option D is wrong because pre-push runs before a push to a remote repository, not before a local commit, and it would not catch issues at the commit stage.

108
MCQhard

A DevOps engineer wants to reduce the size of a Docker image by combining build stages. Which Dockerfile feature should be used?

A.RUN --mount=type=cache
B.Layer caching
C.Multi-stage builds (multiple FROM statements)
D.Using a smaller base image like Alpine
AnswerC

Copies only needed artifacts to final image.

Why this answer

Multi-stage builds, implemented by using multiple FROM statements in a single Dockerfile, allow a DevOps engineer to copy only the necessary artifacts from intermediate build stages into the final image. This eliminates build-time dependencies, tools, and intermediate layers from the final image, significantly reducing its size without sacrificing build functionality.

Exam trap

The trap here is that candidates confuse layer caching (a performance feature) with multi-stage builds (a size-reduction feature), or they assume using a smaller base image alone achieves the same result as eliminating entire build stages.

How to eliminate wrong answers

Option A is wrong because RUN --mount=type=cache is used to persist package manager caches across builds to speed up subsequent builds, not to reduce the final image size by combining build stages. Option B is wrong because layer caching is a performance optimization that reuses unchanged layers from previous builds to accelerate rebuilds, but it does not reduce the size of the final image by combining stages. Option D is wrong because using a smaller base image like Alpine reduces the starting size of the image, but it does not combine build stages or eliminate intermediate build artifacts; multi-stage builds are the specific feature for that purpose.

109
MCQhard

An administrator is tasked with creating a systemd service that runs a Python script after the network is available. The script must restart automatically if it fails. Which systemd service unit directive should be used to ensure restart on failure?

A.Restart=always
B.RemainAfterExit=yes
C.Restart=on-failure
D.RestartSec=5
AnswerC

Restarts the service only when the process exits with a non-zero exit status or is terminated by a signal.

Why this answer

The `Restart=on-failure` directive instructs systemd to restart the service unit only when the process exits with a non-zero exit code, is terminated by a signal (including SIGKILL), or times out. This is the correct choice because the requirement is to restart the script only if it fails, not unconditionally. Using `Restart=always` would restart the service even after a clean exit, which is unnecessary and could mask intentional stops.

Exam trap

CompTIA often tests the distinction between `Restart=always` and `Restart=on-failure`, trapping candidates who assume that 'always' is the safest choice without reading the exact failure condition requirement.

How to eliminate wrong answers

Option A is wrong because `Restart=always` causes the service to restart regardless of the exit status, including normal clean exits, which does not match the requirement to restart only on failure. Option B is wrong because `RemainAfterExit=yes` indicates that the service is considered active even after the main process exits, but it does not control restart behavior on failure. Option D is wrong because `RestartSec=5` specifies a delay (5 seconds) before attempting a restart, but it is not a restart condition directive; it only modifies the timing when used with a `Restart=` setting.

110
MCQmedium

A developer runs a web application inside a Podman container. The application logs HTTP requests to stdout in JSON format. The operations team wants to centralize these logs by forwarding them to a remote syslog server. The administrator considers several approaches. Which approach is the most reliable and recommended way to forward container logs to syslog without modifying the application?

A.Use a cron job to run `podman logs -f` and pipe the output to `logger`.
B.Use `journalctl -u container-name` to export logs via a syslog forwarder.
C.Use `podman exec` to run a log shipper inside the container.
D.Configure the application to write logs to a file in a mounted volume, and have the host's syslog daemon tail that file.
AnswerD

This is a reliable and recommended approach.

Why this answer

Option B is correct because mounting a volume and having the application write logs to a file allows the host syslog daemon to tail that file, decoupling log collection from the container runtime. Option A is inefficient and unreliable. Option C is complex and container logs may not be in journald.

Option D is not recommended as it modifies the container runtime.

111
MCQeasy

The backup script above always outputs 'Backup failed' even when the tar command succeeds. Which of the following is the cause?

A.The tar command should use -czvf
B.The if statement syntax is wrong
C.The variable &? is not defined
D.The correct variable is $? not &?
AnswerD

The script incorrectly uses &? instead of the correct $? variable.

Why this answer

The script uses `&?` to reference the exit status of the `tar` command, but the correct shell variable is `$?`. The `$?` variable holds the exit code of the last executed command (0 for success, non-zero for failure). Using `&?` is a syntax error that results in an empty or invalid value, causing the `if` statement to always evaluate to false (or treat the condition as non-zero), thus always printing 'Backup failed'.

Exam trap

CompTIA often tests the distinction between `$?` and common typos like `&?` or `?$`, exploiting the fact that candidates may overlook the exact syntax of shell special variables and assume any symbol before `?` works.

How to eliminate wrong answers

Option A is wrong because `-czvf` is a valid set of flags for `tar` (create, gzip, verbose, file) and would not cause the script to always output 'Backup failed' if the command succeeds; the issue is not with the tar flags. Option B is wrong because the `if` statement syntax (`if [ condition ]; then ... fi`) is correct; the problem lies in the variable name used inside the condition, not the structure of the if statement. Option C is wrong because `&?` is not a defined variable in bash; the shell does not have a built-in variable named `&?`, and using it does not trigger a special behavior—it simply evaluates to an empty string, which breaks the logic.

112
MCQmedium

A Linux administrator is writing a Bash script that needs to parse a CSV file line by line and extract the second field. Which of the following approaches is the most efficient?

A.Using a `while read` loop with IFS=','
B.Using `awk -F',' '{print $2}'`
C.Using `cut -d, -f2`
D.Using `sed` to extract the second column
AnswerB

awk is designed for text processing and can handle quoted fields with proper configuration.

Why this answer

Option B is correct because `awk` is purpose-built for field-based text processing; `awk -F',' '{print $2}'` efficiently splits each line by comma and prints the second field without needing an explicit loop. It handles edge cases like empty fields and large files with minimal overhead, making it the most efficient choice for CSV parsing in a script.

Exam trap

The trap here is that candidates often choose the `while read` loop (option A) because it seems straightforward and Bash-native, but they overlook the severe performance penalty and fragility with quoted fields, while `awk` is the correct, efficient, and robust solution for field parsing in Linux scripting exams.

How to eliminate wrong answers

Option A is wrong because a `while read` loop with IFS=',' is significantly slower on large files due to the overhead of spawning a subshell and reading line by line, and it can mishandle lines with quoted commas or trailing spaces. Option C is wrong because `cut -d, -f2` cannot handle quoted fields containing commas (e.g., 'field1,"field,2",field3') and will incorrectly split such lines. Option D is wrong because `sed` is a stream editor designed for line-oriented text transformations, not field extraction; using `sed` to isolate the second column requires complex regex patterns that are error-prone and less efficient than `awk`.

113
Multi-Selectmedium

Which two of the following are valid methods to pass environment variables to a Docker container at runtime? (Select TWO.)

Select 2 answers
A.Defining variables in a .env file and using --env-file
B.Using the -e option in docker run
C.Using the ENV instruction in the Dockerfile
D.Using the export command inside the container
E.Using the ARG instruction in the Dockerfile
AnswersA, B

The --env-file option loads environment variables from a file at runtime.

Why this answer

Option A is correct because the `--env-file` flag in `docker run` allows you to pass environment variables from a file (typically a `.env` file) to the container at runtime. This method is useful for managing multiple variables without cluttering the command line and supports variable substitution and quoting rules as defined by Docker.

Exam trap

CompTIA often tests the distinction between build-time instructions (`ENV`, `ARG`) and runtime options (`-e`, `--env-file`), so the trap here is confusing the `ENV` instruction in the Dockerfile (which sets variables at build time) with the `-e` option (which sets variables at runtime).

114
MCQhard

A Linux server runs a critical service managed by a systemd service unit. The administrator needs to configure the service to automatically restart if it crashes, but only up to 3 times within a 30-second window. If the service restarts more than 3 times in 30 seconds, systemd should stop attempting to restart and leave the service in a failed state. Which set of directives should be added to the [Service] section of the unit file to achieve this behavior?

A.`Restart=on-abort` and `MaxStartups=3`
B.`Restart=on-failure` and `StartLimitBurst=5` and `StartLimitIntervalSec=60`
C.`Restart=always` and `RestartSec=10`
D.`Restart=on-failure` and `StartLimitBurst=3` and `StartLimitIntervalSec=30`
AnswerD

This correctly limits restarts to 3 times within 30 seconds.

Why this answer

Option D is correct because it uses `Restart=on-failure` to trigger a restart only when the service crashes (not on other stops), combined with `StartLimitBurst=3` and `StartLimitIntervalSec=30` to limit restarts to 3 attempts within a 30-second window. When the burst limit is exceeded, systemd automatically places the unit in a failed state, exactly matching the requirement.

Exam trap

The trap here is that candidates often confuse `Restart=always` (which restarts on any exit, including intentional stops) with `Restart=on-failure` (which only restarts on crashes), or they misremember the default values of `StartLimitBurst` and `StartLimitIntervalSec`, leading them to pick options with incorrect burst counts or intervals.

How to eliminate wrong answers

Option A is wrong because `Restart=on-abort` only restarts the service if it terminates due to a signal that is not caught (e.g., SIGABRT), not on general crashes, and `MaxStartups` is not a valid systemd directive (it is used in sshd configuration, not unit files). Option B is wrong because `StartLimitBurst=5` and `StartLimitIntervalSec=60` would allow up to 5 restarts in 60 seconds, not the required 3 in 30 seconds. Option C is wrong because `Restart=always` restarts the service regardless of exit reason (including manual stops), and `RestartSec=10` only sets a delay between restarts, with no limit on the number of restart attempts, so the service would keep restarting indefinitely.

115
MCQeasy

A DevOps engineer needs to automate the deployment of a microservice using Ansible. The playbook should install the latest version of nginx on all web servers. Which Ansible module should be used in the playbook?

A.service: name=nginx state=started
B.command: apt install nginx
C.apt: name=nginx state=latest
D.yum: name=nginx state=latest
AnswerC

The apt module with state=latest ensures the latest version is installed.

Why this answer

Option C is correct because the `apt` module is the proper Ansible module for managing packages on Debian-based systems, and `state=latest` ensures the most recent version of nginx is installed. This aligns with the requirement to automate deployment using Ansible's declarative package management rather than imperative shell commands.

Exam trap

The trap here is that candidates often confuse the `service` module (for managing service state) with package installation modules, or they default to the `command` module out of habit, missing Ansible's dedicated package modules that ensure idempotency and cross-platform compatibility.

How to eliminate wrong answers

Option A is wrong because the `service` module manages the state of a service (started/stopped), not the installation of a package; it assumes nginx is already installed. Option B is wrong because using the `command` module to run `apt install nginx` bypasses Ansible's idempotency and package state management, making the playbook fragile and non-declarative. Option D is wrong because the `yum` module is for Red Hat-based systems (using RPM), while the question does not specify the OS family; without context, `apt` is the safer choice for Debian/Ubuntu, and `yum` would fail on non-RHEL systems.

116
MCQeasy

A system administrator needs to run a script every 15 minutes. Which systemd unit type is used to schedule this?

A.systemd timer
B.at job
C.anacron
D.cron job
AnswerA

Timer units can be configured with OnCalendar or OnUnitActiveSec to run every 15 minutes.

Why this answer

Systemd timers are the native systemd unit type for scheduling tasks at specified intervals, such as every 15 minutes. They replace traditional cron jobs in systemd-based Linux distributions and are defined with a .timer unit file that triggers a corresponding .service unit. This makes option A correct because the question explicitly asks for the systemd unit type used for scheduling.

Exam trap

The trap here is that candidates familiar with traditional Linux scheduling immediately think of cron, but the question explicitly asks for a 'systemd unit type,' making cron a distractor despite its functional similarity.

How to eliminate wrong answers

Option B (at job) is wrong because the 'at' command schedules a one-time task at a specific time, not recurring every 15 minutes. Option C (anacron) is wrong because anacron is designed for tasks that need to run daily, weekly, or monthly, assuming the system may not be running continuously, and it does not support sub-daily intervals like 15 minutes. Option D (cron job) is wrong because while cron can schedule tasks every 15 minutes, the question specifically asks for a systemd unit type, and cron is a separate service, not a systemd unit.

117
MCQeasy

A developer writes a Python script that uses the `requests` library to fetch data from an API. The script works on the developer's workstation but fails on the server with an import error. What is the most likely cause?

A.The `requests` module is not installed on the server
B.The script uses an incorrect API endpoint
C.The server lacks internet connectivity
D.The script has a syntax error in the import statement
AnswerA

The `requests` module is not part of the standard library and must be installed via pip.

Why this answer

The `requests` library is a third-party Python package that must be installed separately via `pip` or a package manager. The script works on the developer's workstation because `requests` is present there, but fails on the server with an import error, indicating the module is missing from the server's Python environment. This is the most likely cause because an import error specifically points to a missing module, not to network or syntax issues.

Exam trap

CompTIA often tests the distinction between runtime errors (e.g., network issues, bad endpoints) and import-time errors (e.g., missing modules), trapping candidates who confuse an ImportError with a connectivity or syntax problem.

How to eliminate wrong answers

Option B is wrong because an incorrect API endpoint would cause an HTTP error (e.g., 404 or 400) at runtime, not an import error when the script starts. Option C is wrong because lack of internet connectivity would cause a connection timeout or DNS resolution failure during the `requests.get()` call, not an import error when loading the module. Option D is wrong because a syntax error in the import statement would be caught by Python's parser before execution, producing a SyntaxError, not an ImportError; the script works on the workstation, so the import syntax is correct.

118
MCQmedium

A pod in the Kubernetes cluster is in CrashLoopBackOff. Based on the exhibit, what is the most likely cause?

A.The application inside the container is crashing repeatedly.
B.The container failed to start because of a missing configuration file.
C.The image pull failed due to authentication issues.
D.The container image is not available in the registry.
AnswerA

The CrashLoopBackOff status and BackOff event indicate the application is crashing right after start.

Why this answer

The CrashLoopBackOff status indicates that a container in a pod is repeatedly crashing after starting. Kubernetes attempts to restart the container, but the application inside exits with a non-zero exit code, causing the restart loop. This is most commonly caused by the application itself crashing due to a bug, misconfiguration, or resource issue.

Exam trap

CompTIA often tests the distinction between container startup failures (ImagePullBackOff, ErrImagePull) and runtime crashes (CrashLoopBackOff), so candidates must remember that CrashLoopBackOff implies the container started at least once before crashing.

How to eliminate wrong answers

Option B is wrong because a missing configuration file would typically cause an Init:Error or CreateContainerConfigError, not CrashLoopBackOff, as the container would fail to start at all. Option C is wrong because image pull failures due to authentication issues result in ImagePullBackOff or ErrImagePull, not CrashLoopBackOff. Option D is wrong because an unavailable container image also leads to ImagePullBackOff or ErrImagePull, as the container never starts to crash.

119
MCQeasy

Refer to the exhibit. An administrator creates this systemd unit file for a backup script. When the administrator runs `systemctl start backup.service`, the script runs but the service shows 'inactive (dead)' immediately. What change should be made to keep the service active until the script finishes?

A.Add 'RemainAfterExit=yes' to the [Service] section
B.Change the service type to 'forking'
C.Add 'ExecStop' to the service definition
D.Change the service type to 'simple'
AnswerA

RemainAfterExit=yes keeps the service in 'active' state even after the process exits, which is what the administrator wants.

Why this answer

The correct answer is A because adding 'RemainAfterExit=yes' to the [Service] section tells systemd to consider the service as active even after the main process (the backup script) exits. Without this directive, systemd sees the process terminate and immediately marks the service as 'inactive (dead)', even though the script may still be running or its effects are ongoing. This is the standard way to keep a service unit in an 'active' state after the main command completes.

Exam trap

The trap here is that candidates often confuse 'RemainAfterExit' with service types like 'forking' or 'simple', mistakenly thinking changing the type will keep the service active, when in fact only 'RemainAfterExit' explicitly tells systemd to remain active after the process exits.

How to eliminate wrong answers

Option B is wrong because changing the service type to 'forking' is used when the process forks and the parent exits, leaving a child process running; it does not keep the service active after the script finishes if the script itself exits. Option C is wrong because adding 'ExecStop' defines a command to run when the service is stopped, but it does not affect the service state after the main process exits. Option D is wrong because changing the service type to 'simple' is the default and behaves the same as the current configuration—systemd considers the service active only while the main process is running, so it will still show 'inactive (dead)' immediately after the script finishes.

120
Multi-Selectmedium

Which TWO container networking modes allow a container to have its own IP address on the host network? (Choose TWO.)

Select 2 answers
A.Macvlan
B.Host
C.None
D.Overlay
E.Bridge
AnswersA, E

Container gets its own MAC/IP on physical network.

Why this answer

Macvlan mode assigns each container a unique MAC address and IP address from the host's physical network, making the container appear as a separate device on the same subnet. Bridge mode creates a virtual bridge (typically docker0) and assigns containers IPs from a private subnet, allowing them to communicate with the host network via NAT. Both modes give the container its own IP address on the host network, though bridge uses a private range while macvlan uses the host's subnet directly.

Exam trap

The trap here is that candidates often confuse 'own IP address' with 'own network namespace'—Host mode gives the container its own namespace but shares the host's IP, while Bridge gives a private IP that is not directly on the host's physical subnet, leading some to incorrectly select Host or Overlay.

121
Multi-Selecthard

A security-conscious administrator runs containers with Podman. Which THREE methods ensure that a container runs with the least privilege required?

Select 3 answers
A.--privileged
B.--user 1000
C.--cap-drop=ALL
D.--read-only=true
E.--security-opt seccomp=default.json
AnswersB, C, E

Runs the container as a non-root user, reducing privilege.

Why this answer

Option B is correct because using `--user 1000` runs the container process with a non-root user (UID 1000), which reduces the attack surface by preventing root-level access inside the container. This is a fundamental least-privilege practice, as containers default to running as root unless explicitly changed.

Exam trap

CompTIA often tests the misconception that `--read-only=true` is a privilege-reduction method, when in fact it only restricts filesystem writes and does not limit user or capability privileges.

122
MCQmedium

A cron job runs a script that uses a command only available in a custom directory. The script fails from cron but works in the user's shell. Which of the following is the most common cause?

A.The script is not executable
B.The script has incorrect line endings
C.The cron job runs as root but command is in user's PATH
D.The cron job does not source the user's .bashrc
AnswerD

Cron's minimal environment lacks the custom PATH defined in .bashrc.

Why this answer

The most common cause is that cron jobs run in a minimal environment and do not source the user's shell initialization files like .bashrc. This means the custom directory containing the command is not in the PATH variable when the script executes under cron, even though it works in the user's interactive shell where .bashrc is sourced.

Exam trap

CompTIA often tests the misconception that cron inherits the user's interactive shell environment, leading candidates to incorrectly choose option C (user mismatch) instead of recognizing that cron does not source shell initialization files.

How to eliminate wrong answers

Option A is wrong because if the script were not executable, it would fail in both the user's shell and cron, not just cron. Option B is wrong because incorrect line endings (e.g., Windows CRLF) would cause syntax errors in both environments, not selectively in cron. Option C is wrong because if the cron job runs as root, root's PATH typically includes system directories, but the custom directory is unlikely to be in root's PATH either; however, the question states the command is in a custom directory, and the core issue is that cron does not source any user's shell profile, so the PATH is not set to include that custom directory regardless of the user.

123
MCQeasy

An administrator needs to run a backup script every day at 2:00 AM. The script is located at /usr/local/bin/backup.sh and is executable. The administrator considers several methods to schedule this task. Which method should the administrator use to ensure the script runs at exactly 2:00 AM every day without additional configuration overhead?

A.Add the following line to the crontab for root: `0 2 * * * /usr/local/bin/backup.sh`
B.Append the script path to /etc/rc.local file.
C.Place the script in /etc/cron.daily/ directory.
D.Create a systemd timer unit that triggers the script daily at 2:00 AM.
AnswerA

This crontab entry schedules the script to run at exactly 2:00 AM daily.

Why this answer

The correct method is to add a cron job via crontab because cron is the standard Unix/Linux utility for scheduling tasks at specific times. The syntax `0 2 * * *` precisely defines execution at 2:00 AM daily (minute 0, hour 2, every day, every month, every day of week), and the script path is fully qualified. This approach requires no additional configuration overhead beyond a single crontab entry.

Exam trap

The trap here is that candidates may confuse cron.daily (which runs daily but at a non-configurable time) with a user-crontab entry, or assume systemd timers are simpler than they actually are, overlooking the extra unit files required.

How to eliminate wrong answers

Option B is wrong because /etc/rc.local runs once at system boot, not at a specific daily time like 2:00 AM. Option C is wrong because /etc/cron.daily/ runs once per day but at a system-defined time (typically around 6:25 AM via anacron), not at exactly 2:00 AM, and it cannot be precisely scheduled. Option D is wrong because while a systemd timer can achieve the same result, it requires creating both a service unit and a timer unit, which introduces significantly more configuration overhead compared to a simple crontab entry.

124
MCQmedium

You are a Linux administrator at a company that runs a web application in Docker containers on a single host. The application consists of a front-end container (nginx) and a back-end container (node.js). Recently, after a system update, the front-end container fails to start with the error: 'Error response from daemon: driver failed programming external connectivity on endpoint frontend: (iptables failed: iptables --wait -t filter -A DOCKER ! -i docker0 -o docker0 -p tcp -d 172.17.0.2 --dport 80 -j ACCEPT: iptables: No chain/target/match by that name)'. Which action should you take to resolve the issue?

A.Restart the Docker daemon with systemctl restart docker
B.Reinstall iptables
C.Change the network driver to macvlan
D.Update the kernel to the latest version
AnswerA

Restarting Docker recreates its iptables chains and rules, fixing the missing chain error.

Why this answer

The error indicates that the Docker daemon's iptables rules are corrupted or missing, often caused by a system update that restarted or modified the iptables service. Restarting the Docker daemon with `systemctl restart docker` forces Docker to reinitialize its iptables chains (e.g., DOCKER, DOCKER-USER) and reapply the necessary rules, resolving the connectivity failure.

Exam trap

CompTIA often tests the misconception that iptables itself is broken or needs reinstallation, when the real issue is that Docker's custom iptables chains were lost and need to be recreated by restarting the Docker daemon.

How to eliminate wrong answers

Option B is wrong because reinstalling iptables is unnecessary; the iptables command itself is present and functional (the error is about a missing chain, not a missing binary). Option C is wrong because changing the network driver to macvlan would alter the networking model but does not address the missing iptables chain; the issue is with Docker's default bridge network and its iptables rules. Option D is wrong because updating the kernel is not required; the error stems from a configuration mismatch between Docker and iptables, not a kernel compatibility issue.

125
MCQmedium

A system administrator wants to ensure that a container can access host devices such as USB drives. Which Docker run option should be used?

A.--device /dev/ttyUSB0
B.--privileged
C.--pid=host
D.--net=host
AnswerA

This grants the container access to the specified host device.

Why this answer

The `--device` flag in Docker allows a container to directly access a specific host device, such as `/dev/ttyUSB0` for a USB drive or serial adapter. This grants the container read/write permissions to the device node without requiring full privileged access, making it the precise and secure option for this requirement.

Exam trap

The trap here is that candidates often choose `--privileged` because they think it is the only way to give a container hardware access, but the exam tests the understanding that `--device` provides granular, secure device access without the broad security implications of full privilege escalation.

How to eliminate wrong answers

Option B is wrong because `--privileged` grants the container all capabilities and full access to all host devices, which is excessive and a security risk; it is not the targeted solution for accessing a specific device like a USB drive. Option C is wrong because `--pid=host` shares the host's PID namespace with the container, allowing the container to see all host processes, but it does not provide any access to host devices. Option D is wrong because `--net=host` makes the container use the host's network stack directly, which affects networking only and has no effect on device access.

126
Multi-Selecthard

Which THREE statements about Ansible are true? (Choose three.)

Select 2 answers
A.Ansible playbooks are written in YAML
B.Ansible uses a centralized master server
C.Ansible requires Python on the control node only
D.Ansible is idempotent
E.Ansible requires an agent to be installed on managed nodes
AnswersA, D

Playbooks are YAML files.

Why this answer

Ansible playbooks are written in YAML because YAML is a human-readable data serialization language that allows Ansible to define automation workflows declaratively. The control node parses the YAML playbook into Python data structures, which are then executed against managed nodes via modules. This design eliminates the need for a custom domain-specific language and simplifies version control and collaboration.

Exam trap

CompTIA often tests the misconception that Ansible requires a master server (like Puppet or Chef) or that it needs agents on managed nodes, but the trap here is that Ansible is agentless and uses a simple push model from a single control node.

127
MCQhard

You are a DevOps engineer managing a Git repository for a large development team. Your CI/CD pipeline runs automated tests on every push. Recently, developers have been pushing commits that break the build. You need to enforce that all commits pass the tests before being pushed to the remote repository. Which Git hook should you implement on the client side?

A.pre-receive
B.pre-commit
C.post-commit
D.pre-push
AnswerD

Pre-push runs after commit but before push, ensuring tests pass before code leaves the local machine.

Why this answer

The pre-push hook (option D) runs after a `git push` command is issued but before the data is actually sent to the remote repository. This allows you to run tests locally and abort the push if they fail, enforcing that only commits that pass tests are pushed. It is the correct client-side hook for this requirement.

Exam trap

CompTIA often tests the distinction between client-side and server-side hooks, and the trap here is that candidates confuse pre-receive (server-side) with pre-push (client-side), thinking any hook that runs 'before receive' will block the push on the client.

How to eliminate wrong answers

Option A is wrong because pre-receive is a server-side hook that runs on the remote repository after the push is received, so it cannot prevent the push from being sent from the client. Option B is wrong because pre-commit runs before each commit is created, not before a push, so it cannot enforce that all commits in a push pass tests. Option C is wrong because post-commit runs after a commit is created and cannot abort the commit or push, making it useless for blocking broken commits from being pushed.

128
MCQhard

An administrator configures Docker as shown in the exhibit. After starting a container, the warning about the 'user' directive appears. What is the most likely cause?

A.The storage driver overlay2 is not compatible with the systemd cgroup driver.
B.The cgroup driver configured in daemon.json does not match the actual driver in use.
C.The container is running with reduced privileges, and nginx cannot use the 'user' directive.
D.The log driver configuration is causing nginx to log warnings.
AnswerB

The daemon.json specifies systemd, but docker info shows cgroupfs, indicating a mismatch.

Why this answer

The warning about the 'user' directive indicates a mismatch between the cgroup driver configured in Docker's daemon.json and the cgroup driver actually in use by the system (e.g., systemd vs. cgroupfs). Docker expects the configured driver to match the system's init system; when they differ, Docker emits warnings because cgroup management may behave inconsistently, affecting resource limits and container isolation.

Exam trap

CompTIA often tests the subtle distinction between a configuration mismatch warning and an actual runtime failure, leading candidates to misinterpret the warning as a functional error in nginx or storage compatibility.

How to eliminate wrong answers

Option A is wrong because overlay2 is a storage driver and has no direct compatibility issue with the systemd cgroup driver; the warning is about cgroup driver mismatch, not storage. Option C is wrong because the 'user' directive in nginx is unrelated to container privilege reduction; the warning originates from Docker's cgroup driver check, not from nginx's runtime behavior. Option D is wrong because the log driver configuration does not cause warnings about the 'user' directive; log driver settings affect log output format and destination, not cgroup driver validation.

129
MCQhard

Refer to the exhibit. The development team is using Git to manage their project. A release candidate needs to include only the changes from the `feature/update` branch, but NOT the 'Add new module' commit. Which Git command sequence should be used to create a new release branch that contains only the feature branch?

A.git checkout feature/update && git rebase 1m2n3o4
B.git checkout -b release 1m2n3o4 && git cherry-pick 4d5e6f7 8f9g0h1
C.git checkout -b release master && git revert 2j3k4l5
D.git checkout -b release feature/update && git merge --no-ff master
AnswerB

Starting from the initial commit, cherry-picking the two feature branch commits includes only those changes, excluding 'Add new module'.

Why this answer

Option B is correct because it creates a new release branch starting from the commit before the 'Add new module' commit (1m2n3o4), then cherry-picks only the two commits from the `feature/update` branch (4d5e6f7 and 8f9g0h1) that represent the desired changes. This ensures the release branch contains exactly the feature branch changes without including the unwanted 'Add new module' commit.

Exam trap

The trap here is that candidates may think `git revert` removes a commit from history, when in fact it only creates a new inverse commit, leaving the original commit present in the branch's history.

How to eliminate wrong answers

Option A is wrong because `git rebase 1m2n3o4` while on `feature/update` would replay the feature branch commits onto commit 1m2n3o4, but this would still include the 'Add new module' commit if it is part of the feature branch history, and does not create a new release branch. Option C is wrong because `git revert 2j3k4l5` would create a new commit that undoes the 'Add new module' commit, but the release branch would still contain that commit in its history, which violates the requirement to not include it at all. Option D is wrong because merging `master` into a branch based on `feature/update` would bring in all commits from master, including the 'Add new module' commit, which is explicitly unwanted.

130
Multi-Selecthard

Which THREE tools are commonly used for configuration management?

Select 3 answers
A.Chef
B.Ansible
C.Puppet
D.Kubernetes
E.Docker
AnswersA, B, C

Chef is a configuration management tool.

Why this answer

Chef is a configuration management tool that uses a Ruby-based DSL to define system configurations as 'recipes' and 'cookbooks'. It follows a pull-based model where nodes run the Chef client to fetch and apply configurations from a Chef server, ensuring desired state compliance across infrastructure.

Exam trap

CompTIA often tests the distinction between configuration management (Chef, Ansible, Puppet) and container/orchestration tools (Docker, Kubernetes), leading candidates to mistakenly select Kubernetes or Docker as configuration management tools.

131
MCQeasy

After writing a script, the administrator cannot execute it with './script.sh'. The permissions are '-rw-rw-r--'. Which command makes the script executable?

A.chmod u+x script.sh
B.chmod +x script.sh
C.chmod g-x script.sh
D.chmod a+rwx script.sh
AnswerA

Adds execute for the owner.

Why this answer

Option A is correct because the current permissions (`-rw-rw-r--`) show that the owner lacks execute permission. The command `chmod u+x script.sh` adds execute permission for the user (owner) only, which is the minimal and most secure way to make the script executable by the administrator who owns it. This directly addresses the requirement without granting unnecessary permissions to the group or others.

Exam trap

CompTIA often tests the distinction between `chmod +x` (which adds execute for all) and `chmod u+x` (which adds execute only for the owner), expecting candidates to recognize that the minimal permission change is the correct answer.

How to eliminate wrong answers

Option B is wrong because `chmod +x script.sh` adds execute permission for all three categories (user, group, others) by default when no target is specified, which is overly permissive and violates the principle of least privilege. Option C is wrong because `chmod g-x script.sh` removes execute permission from the group, which does not help make the script executable; it actually reduces permissions. Option D is wrong because `chmod a+rwx script.sh` grants read, write, and execute permissions to all users (user, group, others), which is excessively permissive and unnecessary for the administrator's goal.

132
MCQhard

A senior administrator is troubleshooting a shell script that fails to execute properly. The script starts with #!/bin/bash and has execute permissions. Which of the following could cause the script to fail to run when invoked as ./script.sh?

A.The shebang line is not on the first line.
B.The script contains carriage return characters (\r).
C.The script uses #!/bin/sh instead of bash.
D.The script starts with a byte order mark (BOM).
AnswerB

Can cause 'No such file or directory'.

Why this answer

Option B is correct because carriage return characters (\r) are a common issue when scripts are edited on Windows and then transferred to Linux. The shebang line #!/bin/bash expects a Unix-style line ending (LF), but \r characters cause the shell to interpret the command interpreter as '/bin/bash\r', which is not a valid executable path. This results in a 'No such file or directory' error when the script is invoked as ./script.sh, even though permissions are correct.

Exam trap

The trap here is that candidates may think the shebang line must be on the first line (Option A) is the issue, but Cisco tests the subtle Windows line-ending problem (\r) that causes the interpreter path to be invalid, which is a common real-world pitfall when scripts are edited in Windows environments and transferred to Linux.

How to eliminate wrong answers

Option A is wrong because the shebang line must be on the first line of the script; if it is not, the script will still execute but will be interpreted by the default shell (usually /bin/sh) rather than bash, which may cause different behavior but not necessarily a failure to run. Option C is wrong because using #!/bin/sh instead of #!/bin/bash does not cause the script to fail to run; it simply invokes the system's default Bourne shell, which may lack some bash-specific features but will still execute the script if it is compatible. Option D is wrong because a byte order mark (BOM) at the start of the script is a Unicode encoding artifact that can cause the shebang line to be misinterpreted, but it is less common than carriage return issues and typically results in a 'bad interpreter' error similar to \r, but the question specifically tests the more frequent Windows-to-Linux line-ending problem.

133
MCQmedium

A systems administrator creates a bash script that processes log files. The script uses a for loop to iterate over files in /var/log and runs a command on each. Which of the following would prevent the script from failing if no files match the pattern?

A.set -u
B.set -e
C.shopt -s failglob
D.shopt -s nullglob
AnswerD

Expands to nothing, preventing failure.

Why this answer

Option D is correct because `shopt -s nullglob` causes the shell to expand a glob pattern that matches no files into an empty string rather than leaving the pattern literal. Without this setting, if no files match the pattern in `/var/log`, the for loop receives the literal pattern string (e.g., `*.log`) and attempts to process it as a filename, which would cause the command to fail or produce unexpected results. Enabling nullglob ensures the loop body simply does not execute when no matches exist, preventing script failure.

Exam trap

The trap here is that candidates often confuse `nullglob` with `failglob` or assume that `set -e` or `set -u` can handle glob failures, when in fact only `nullglob` prevents the literal pattern string from being passed as an argument, thereby avoiding a command failure.

How to eliminate wrong answers

Option A is wrong because `set -u` treats unset variables as an error and causes the script to exit when referencing an undefined variable, but it does not affect how glob patterns are expanded when no files match. Option B is wrong because `set -e` causes the script to exit immediately if any command returns a non-zero exit status, but it does not change the behavior of glob expansion; a failed glob pattern would still be passed as a literal string, potentially causing a command failure that `set -e` would then propagate. Option C is wrong because `shopt -s failglob` causes the shell to print an error and exit if a glob pattern matches no files, which is the opposite of preventing script failure — it would actively cause the script to fail.

134
MCQeasy

Which command will run a container in detached mode with the name 'web' and map host port 8080 to container port 80, using the nginx image?

A.docker run -d --name web -p 8080:80 nginx
B.docker exec -d --name web -p 8080:80 nginx
C.docker start -d --name web -p 8080:80 nginx
D.docker run -it --name web -p 8080:80 nginx
AnswerA

Correct. This runs the nginx container in detached mode with the specified name and port mapping.

Why this answer

Option A is correct because `docker run` creates and starts a new container. The `-d` flag runs it in detached mode (background), `--name web` assigns the name 'web', `-p 8080:80` maps host port 8080 to container port 80, and `nginx` specifies the image to use. This is the standard syntax for deploying a container with port mapping and a custom name.

Exam trap

CompTIA often tests the distinction between `docker run` (create + start) and `docker start` (start existing container), and the requirement for `-d` versus `-it` to achieve detached mode, causing candidates to confuse the subcommands or flags.

How to eliminate wrong answers

Option B is wrong because `docker exec` is used to run a command inside an existing container, not to create or start a new container; it does not accept `-d` for detached mode in the same way, and `-p` is not a valid flag for `docker exec`. Option C is wrong because `docker start` is used to start an existing stopped container, not to create a new one; it does not accept `-p` for port mapping, and the `nginx` argument would be interpreted as a container name, not an image. Option D is wrong because `-it` runs the container in interactive mode with a TTY, not detached mode; the question specifically requires detached mode (`-d`).

135
MCQhard

Refer to the exhibit. The administrator receives an email that a cron job failed. What is the most likely cause?

A.The script is not executable.
B.The script is missing a shebang line.
C.The cron daemon is not running.
D.The script has an unmatched if statement.
AnswerD

Correct: The error 'syntax error near unexpected token `fi'' suggests an if statement without a matching fi.

Why this answer

The cron job failed because the script contains an unmatched if statement, which causes a syntax error when the shell interprets the script. Cron jobs execute scripts in a non-interactive shell, and any syntax error will cause the script to exit with a non-zero status, triggering the failure email. The unmatched if statement prevents the script from completing execution, leading to the reported failure.

Exam trap

CompTIA often tests the distinction between script execution failures due to syntax errors versus permission or environment issues, and the trap here is that candidates may incorrectly attribute the failure to a missing shebang line or non-executable script, overlooking the specific syntax error message shown in the exhibit.

How to eliminate wrong answers

Option A is wrong because if the script were not executable, the cron job would fail with a 'Permission denied' error, but the cron daemon would still attempt to run it and send a failure notification; however, the exhibit shows a syntax error, not a permission issue. Option B is wrong because while a missing shebang line can cause the script to be interpreted by the default shell (often /bin/sh), which might still work, it would not directly cause an unmatched if statement error; the exhibit explicitly shows an 'unexpected end of file' error due to missing 'fi'. Option C is wrong because if the cron daemon were not running, no cron jobs would execute at all, and the administrator would not receive a failure email for a specific job; the email indicates the daemon is active and attempted the job.

136
MCQeasy

A team uses Ansible for configuration management. A playbook fails with the error 'ERROR! Syntax Error while loading YAML script'. Which of the following is the most likely cause?

A.Missing SSH key
B.Incorrect indentation in the YAML file
C.Invalid module name
D.Playbook not executable
AnswerB

YAML syntax errors are most commonly due to indentation mistakes.

Why this answer

The error 'Syntax Error while loading YAML script' indicates that Ansible's YAML parser encountered a structural problem in the playbook file. The most common cause in YAML is incorrect indentation, because YAML relies on consistent spacing (typically 2 spaces per level) to define the hierarchy of tasks, plays, and variables. A missing SSH key would produce a connection or authentication error, not a YAML syntax error.

Exam trap

The trap here is that candidates may confuse a YAML parsing error with a runtime execution error, such as an SSH key issue or an invalid module, because they all prevent the playbook from running successfully.

How to eliminate wrong answers

Option A is wrong because a missing SSH key causes an authentication failure (e.g., 'Permission denied (publickey)') during the connection phase, not a YAML syntax error during parsing. Option C is wrong because an invalid module name results in a module-specific error (e.g., 'ERROR! couldn't resolve module/action'), not a YAML syntax error. Option D is wrong because playbooks are not executed as standalone scripts; Ansible runs them via the `ansible-playbook` command, so the executable bit is irrelevant — the error would be a 'Permission denied' if the file were executed directly, not a YAML syntax error.

137
MCQmedium

A DevOps engineer is writing a unit file for a systemd service that should start after the network-online.target. Which directive should be added to the [Unit] section?

A.Requires=network-online.target
B.Wants=network-online.target
C.BindsTo=network-online.target
D.After=network-online.target
AnswerD

Correct. The After directive ensures the service starts after the specified target is reached.

Why this answer

The 'After=' directive in the [Unit] section of a systemd unit file specifies the ordering relationship, ensuring that the current service starts only after the named unit (network-online.target) has reached the 'active' state. This is the correct directive for controlling startup order without creating a dependency that would force the target to start if it is not already enabled.

Exam trap

The trap here is that candidates confuse ordering directives ('After=', 'Before=') with dependency directives ('Requires=', 'Wants=', 'BindsTo='), assuming that 'Requires=' or 'Wants=' also imply ordering, which they do not without an explicit 'After='.

How to eliminate wrong answers

Option A is wrong because 'Requires=' creates a hard dependency that will cause the service to fail if network-online.target is not started, but it does not enforce ordering; the service could start before the target unless 'After=' is also used. Option B is wrong because 'Wants=' creates a soft dependency that attempts to start network-online.target but does not enforce ordering; the service may start before the target completes. Option C is wrong because 'BindsTo=' creates a stronger dependency than 'Requires=' where the service will stop if network-online.target stops, and it also does not imply ordering; it is used for tightly coupled services, not for simple startup sequencing.

138
MCQeasy

A bash script uses a for loop to iterate over files in a directory. Which of the following correctly assigns each filename to the variable FILE?

A.for FILE in $(ls *.txt); do
B.for FILE in *.txt; do
C.for FILE in 'ls *.txt'; do
D.for FILE = *.txt; do
AnswerB

Uses glob expansion correctly, handling all filenames safely.

Why this answer

Option B is correct because the shell expands the wildcard pattern `*.txt` into a list of matching filenames before the `for` loop executes, and each filename is assigned to the variable `FILE` in turn. This approach is safe and efficient because it avoids parsing the output of `ls`, which can break with filenames containing spaces or special characters.

Exam trap

The trap here is that candidates often choose `$(ls *.txt)` (Option A) because they think they need to explicitly list files with `ls`, not realizing that the shell's built-in globbing is safer and more efficient, and that `ls` output parsing is fragile.

How to eliminate wrong answers

Option A is wrong because `$(ls *.txt)` uses command substitution to run `ls`, which parses its output and can break on filenames with spaces, newlines, or glob characters; it also forks an unnecessary subshell. Option C is wrong because `'ls *.txt'` is a literal string (single quotes prevent expansion), so the loop would iterate over the single string `ls *.txt` instead of actual filenames. Option D is wrong because the syntax `for FILE = *.txt` uses an equals sign instead of the required `in` keyword, which is a syntax error in bash.

139
Multi-Selectmedium

An administrator wants to ensure that a web service starts after the database service has fully initialized. Which TWO methods can be used to achieve this ordering dependency in systemd?

Select 2 answers
A.Add Requires=db.service in the [Unit] section
B.Add After=db.service in the [Unit] section of web.service
C.Add BindsTo=db.service in the [Unit] section
D.Add Wants=db.service in the [Unit] section
E.Add PartOf=db.service in the [Unit] section
AnswersA, B

Makes db.service a required dependency; together with After, it ensures ordering.

Why this answer

Option A is correct because `Requires=db.service` in the `[Unit]` section declares a strong dependency: if `db.service` fails to start, `web.service` will not be started. Option B is correct because `After=db.service` in the `[Unit]` section of `web.service` ensures that `web.service` starts only after `db.service` has reached the 'active' state, enforcing the required ordering. Together, these two directives guarantee both dependency and sequencing.

Exam trap

The trap here is that candidates often pick only `After=` (option B) thinking it alone enforces the dependency, forgetting that `After=` only orders startup and does not prevent the web service from starting if the database fails — the exam expects the combination of `Requires=` and `After=` to fully satisfy the 'starts after and depends on' requirement.

140
MCQeasy

A systems administrator needs to automate the execution of a backup script every day at 2:00 AM using a systemd service. Which unit type should the administrator create?

A.A .service unit
B.A .path unit
C.A .mount unit
D.A .timer unit
AnswerD

A timer unit triggers a service unit on a schedule.

Why this answer

A .timer unit is the correct choice because systemd timers are designed to schedule and trigger the execution of other units (such as services) at specific times or intervals. By creating a .timer unit that activates at 2:00 AM daily and a corresponding .service unit for the backup script, the administrator can automate the backup using systemd's built-in scheduling mechanism, which is more reliable and integrated than cron for systemd-managed systems.

Exam trap

The trap here is that candidates often confuse .timer units with .service units, mistakenly thinking a .service unit alone can handle scheduling, but systemd requires a separate timer unit to define the schedule and trigger the service.

How to eliminate wrong answers

Option A is wrong because a .service unit defines how to start, stop, and manage a process, but it does not include scheduling logic; it must be triggered by another unit (like a .timer) to run at a specific time. Option B is wrong because a .path unit monitors file system changes (e.g., file creation or modification) and activates a service when those events occur, not for time-based scheduling. Option C is wrong because a .mount unit controls the mounting of file systems and has no capability to schedule periodic execution of scripts.

141
MCQmedium

A DevOps engineer needs to ensure that a containerized web application always restarts automatically if the container exits unexpectedly. Which Docker run option should be used?

A.--restart=on-failure
B.--restart=unless-stopped
C.--restart=no
D.--restart=always
AnswerD

Always restarts regardless of exit status.

Why this answer

The `--restart=always` policy ensures that the container restarts regardless of the exit code or reason for termination, including unexpected crashes. This is the correct choice for a containerized web application that must maintain high availability by automatically recovering from any unexpected exit.

Exam trap

CompTIA often tests the subtle distinction between `--restart=always` and `--restart=unless-stopped`, where candidates mistakenly choose `unless-stopped` thinking it provides the same automatic restart but without the risk of restarting after a manual stop, missing that the requirement explicitly says 'always restarts automatically' regardless of how the container exits.

How to eliminate wrong answers

Option A is wrong because `--restart=on-failure` only restarts the container if it exits with a non-zero exit code, which may not cover all unexpected exit scenarios (e.g., a signal-based kill). Option B is wrong because `--restart=unless-stopped` will not restart the container if it was explicitly stopped by the user, which could leave the application down after manual intervention. Option C is wrong because `--restart=no` is the default policy that never automatically restarts the container, failing to meet the requirement for automatic recovery.

142
MCQhard

A containerized application is consuming excessive memory on a Linux host running Podman. Which command sets a memory limit of 512 megabytes when running a container?

A.podman run --memory=512m myimage
B.podman run --limit-memory 512 myimage
C.podman run --mem=512m myimage
D.podman run --memory-limit=512MB myimage
AnswerA

--memory=512m correctly sets a memory limit of 512 megabytes.

Why this answer

Option A is correct because Podman uses the `--memory` flag (identical to Docker's syntax) to set a hard memory limit on a container. The value `512m` specifies 512 megabytes. This directly restricts the container's memory usage via cgroups, preventing it from consuming excessive host memory.

Exam trap

CompTIA often tests the exact flag syntax and unit format, so the trap here is that candidates may confuse Podman's `--memory` with Docker's `--memory` (they are identical) or invent plausible-sounding flags like `--limit-memory` or `--mem`, or use incorrect unit capitalization like `MB` instead of `m`.

How to eliminate wrong answers

Option B is wrong because `--limit-memory` is not a valid Podman flag; the correct flag is `--memory`. Option C is wrong because `--mem` is not a valid Podman flag; the correct abbreviation is `--memory` (or `-m`). Option D is wrong because `--memory-limit` is not a valid Podman flag, and the value `512MB` uses an incorrect unit format (Podman expects lowercase 'm' for megabytes, e.g., `512m`).

143
MCQmedium

Which command will display the disk usage of each file and directory in the current directory?

A.df -h
B.ls -lh
C.du -sh *
D.fdisk -l
AnswerC

du -sh * displays the total size of each file/directory in human-readable format.

Why this answer

Option C is correct because `du -sh *` calculates and displays the disk usage of each file and directory in the current directory. The `-s` flag summarizes each item, `-h` provides human-readable sizes (e.g., KB, MB), and the `*` wildcard expands to all non-hidden entries in the current directory, making it the precise command for this task.

Exam trap

CompTIA often tests the distinction between `df` (filesystem-level) and `du` (directory/file-level) disk usage, and the trap here is that candidates mistakenly choose `ls -lh` thinking it shows disk usage, when it only shows logical file size and does not account for blocks or directory contents.

How to eliminate wrong answers

Option A is wrong because `df -h` reports filesystem-level disk space usage (total, used, available) for mounted filesystems, not per-file or per-directory usage. Option B is wrong because `ls -lh` lists file sizes and metadata but does not calculate actual disk usage (it shows logical file size, not blocks consumed, and cannot handle directories recursively). Option D is wrong because `fdisk -l` is a partition table manipulation tool that lists disk partitions and their geometry, not file or directory disk usage.

144
Multi-Selectmedium

Which TWO statements about container security are correct when using Docker? (Choose two.)

Select 2 answers
A.SELinux is automatically enabled inside containers.
B.Containers have their own kernel, isolated from the host.
C.Using --cap-drop=ALL removes all capabilities, making the container more secure.
D.By default, containers run with a reduced set of Linux capabilities.
E.Using --network=host increases container isolation.
AnswersC, D

Dropping all capabilities and adding only needed ones is a security best practice.

Why this answer

Option C is correct because using `--cap-drop=ALL` removes all Linux capabilities from the container, which eliminates any privileged operations the container could perform. This forces the container to run with the absolute minimum privileges, significantly reducing the attack surface and making it more secure.

Exam trap

CompTIA often tests the misconception that containers have their own kernel or that SELinux is automatically active, while the real focus is on Linux capabilities and the shared kernel model.

145
MCQmedium

A cron job runs a script that produces output, but the administrator does not receive the expected email notification. Which is the most likely cause?

A.The script uses absolute paths for all commands.
B.MAILTO variable is not set in the crontab.
C.The PATH environment variable is not set.
D.The script is not executable.
AnswerB

Cron only sends output to the address specified in MAILTO; if not set, output is lost.

Why this answer

The MAILTO variable in a crontab specifies the email address to which cron sends the output (stdout/stderr) of a job. If MAILTO is not set, cron defaults to mailing output to the owner of the crontab (the user who created it). However, if the administrator expects notifications at a different address, the missing MAILTO variable would prevent that specific email from being sent.

This is the most direct cause of not receiving the expected email notification.

Exam trap

CompTIA often tests the distinction between variables that affect script execution (PATH) versus those that control cron's mail behavior (MAILTO), leading candidates to mistakenly choose PATH or executable permissions when the issue is specifically about email delivery.

How to eliminate wrong answers

Option A is wrong because using absolute paths for all commands does not affect email delivery; it actually helps ensure the script runs correctly regardless of the cron environment. Option C is wrong because the PATH environment variable affects command resolution within the script, not the sending of email notifications by cron. Option D is wrong because if the script were not executable, it would fail to run entirely, producing an error that would still be mailed to the crontab owner (or the MAILTO address if set), so the lack of email notification is not explained by this.

146
MCQmedium

An Ansible playbook fails with a syntax error. Which command validates the playbook syntax without running it?

A.ansible-lint playbook.yml
B.ansible-playbook --check
C.ansible-playbook --validate
D.ansible-playbook --syntax-check
AnswerD

This command parses the playbook and reports syntax errors without executing any tasks.

Why this answer

The `--syntax-check` flag is a built-in option of `ansible-playbook` that parses the YAML file and validates its syntax without executing any tasks. This is the correct tool for catching syntax errors in a playbook before running it.

Exam trap

The trap here is that candidates may confuse `--syntax-check` with `--check` (dry run) or assume `ansible-lint` is the syntax validator, but `--syntax-check` is the only command that validates syntax without any execution.

How to eliminate wrong answers

Option A is wrong because `ansible-lint` is a separate tool that checks for best practices, style, and potential issues, but it does not perform a strict syntax validation of the playbook. Option B is wrong because `--check` performs a dry run that executes the playbook in check mode, which still runs the playbook logic and can fail on syntax errors, not just validate syntax. Option C is wrong because `--validate` is not a valid flag for `ansible-playbook`; the correct flag for syntax validation is `--syntax-check`.

147
MCQmedium

A Linux engineer is troubleshooting a cron job that does not execute as expected. The crontab entry reads: '*/5 * * * * /usr/local/bin/backup.sh'. The script runs manually when executed as root. Which of the following is the most likely cause?

A.The cron daemon is not running.
B.The script file does not have execute permissions.
C.The system clock is incorrect.
D.The script requires environment variables that are not set in cron's shell.
AnswerD

Common issue: cron has limited PATH and env.

Why this answer

D is correct because cron jobs run in a minimal shell environment (typically /bin/sh) with a very limited set of environment variables. The script /usr/local/bin/backup.sh may rely on variables like PATH, HOME, or custom variables that are not set in cron's shell, causing it to fail even though it runs fine manually as root. This is a classic cron issue where the interactive shell's environment differs from cron's non-interactive environment.

Exam trap

CompTIA often tests the misconception that a script failing in cron is due to permissions or the cron daemon status, when the real issue is the stripped-down environment that lacks variables the script depends on.

How to eliminate wrong answers

Option A is wrong because if the cron daemon were not running, no cron jobs would execute at all, but the question states only this specific job fails, and the script runs manually. Option B is wrong because the script runs manually when executed as root, which implies it has execute permissions; if permissions were missing, the manual execution would also fail. Option C is wrong because an incorrect system clock would affect all cron jobs based on timing, but the job is scheduled with '*/5 * * * *' and would still attempt to run; the issue is specific to the script's execution environment, not the timing.

148
MCQeasy

A developer wants to run a container with a specific command that overrides the default entrypoint. Which Docker command should be used?

A.docker run myimage /bin/bash
B.docker exec myimage /bin/bash
C.docker run --entrypoint /bin/bash myimage
D.docker start myimage /bin/bash
AnswerC

Overrides ENTRYPOINT.

Why this answer

Option C is correct because the `--entrypoint` flag in `docker run` allows you to override the default entrypoint defined in the Docker image. By specifying `--entrypoint /bin/bash`, the container will start with `/bin/bash` as its entrypoint, ignoring any `ENTRYPOINT` or `CMD` instructions in the Dockerfile. This is the standard Docker syntax for replacing the entrypoint at runtime.

Exam trap

The trap here is that candidates often confuse `docker run` with `docker exec` or assume that appending a command after the image name (as in option A) overrides the entrypoint, when in fact it only overrides the CMD unless the entrypoint is explicitly changed with `--entrypoint`.

How to eliminate wrong answers

Option A is wrong because `docker run myimage /bin/bash` appends `/bin/bash` as a command argument to the image's default entrypoint (if one exists), or overrides the default CMD, but it does not override the entrypoint itself; if the image has an ENTRYPOINT, the `/bin/bash` argument is passed to that entrypoint, not executed directly. Option B is wrong because `docker exec` is used to run a command in an already running container, not to start a new container with a different entrypoint. Option D is wrong because `docker start` only restarts an existing stopped container and does not accept a command argument; it cannot override the entrypoint or run a new command.

149
MCQmedium

An administrator needs to run a script '/usr/local/bin/cleanup.sh' every day at 2:30 AM. Which crontab entry is correct?

A.2 30 * * * /usr/local/bin/cleanup.sh
B.*/30 2 * * * /usr/local/bin/cleanup.sh
C.30 * * * * /usr/local/bin/cleanup.sh
D.30 2 * * * /usr/local/bin/cleanup.sh
AnswerD

Correct syntax for 2:30 AM daily.

Why this answer

The correct crontab syntax is `minute hour day month weekday command`. Option D specifies minute 30, hour 2, and asterisks for all other fields, which means the script runs at 2:30 AM every day. This matches the requirement exactly.

Exam trap

CompTIA often tests the order of minute and hour fields in crontab entries, and the trap here is that candidates may swap them (placing hour first) or use `*/30` thinking it means 'at 30 minutes past the hour' rather than 'every 30 minutes'.

How to eliminate wrong answers

Option A is wrong because it places the hour (2) in the minute field and the minute (30) in the hour field, causing the script to run at 30 minutes past every hour on the 2nd day of the month. Option B is wrong because `*/30` in the minute field means 'every 30 minutes' and `2` in the hour field means 'only during hour 2', so the script runs at 2:00 AM, 2:30 AM, and 2:00 AM again (due to the 30-minute interval), not just once at 2:30 AM. Option C is wrong because it sets minute 30 and hour as `*` (every hour), so the script runs at 30 minutes past every hour, i.e., 24 times per day.

150
Multi-Selecthard

Which THREE of the following are valid ways to define environment variables in a Docker container? (Choose three.)

Select 4 answers
A.Passing with docker run -e VAR=value
B.Including in a docker-compose.yml under services: environment:
C.Using the ARG instruction in Dockerfile
D.Using the ENV instruction in Dockerfile
E.Using --env-file option with docker run
AnswersA, B, D, E

Overrides or sets variable at runtime.

Why this answer

Option A is correct because the `docker run -e VAR=value` syntax directly sets an environment variable inside the container at runtime. This overrides any ENV instruction in the Dockerfile for that specific run, giving the operator flexibility without modifying the image.

Exam trap

CompTIA often tests the distinction between build-time (`ARG`) and runtime (`ENV`, `-e`, `--env-file`) variable definitions, and candidates mistakenly think `ARG` persists into the running container.

← PreviousPage 2 of 3 · 151 questions totalNext →

Ready to test yourself?

Try a timed practice session using only Scripting Containers questions.