A system administrator is using Ansible to manage a fleet of Linux servers. They need to ensure that a specific package, `nginx`, is installed and running, and that its service is enabled to start upon system boot. Which Ansible module and associated tasks would correctly achieve this goal?
- A- name: Setup Nginx ansible.builtin.package: name=nginx state=installed ansible.builtin.service: name=nginx state=running enabled=true
- B- name: Ensure Nginx is installed and running apt: name=nginx state=present systemd: name=nginx state=started enabled=yes
- C- name: Configure Nginx yum: name=nginx state=latest shell: systemctl enable nginx && systemctl start nginx
- D- name: Install and start Nginx package: name=nginx state=present service: name=nginx state=started enabled=yes
Show answer & explanationAnswer & explanation
Correct answer: A. - name: Setup Nginx ansible.builtin.package: name=nginx state=installed ansible.builtin.service: name=nginx state=running enabled=true
Option D correctly uses the `ansible.builtin.package` module to ensure the package is installed (state=installed is equivalent to present) and the `ansible.builtin.service` module to ensure the service is running (`state=running` is equivalent to `started`) and enabled (`enabled=true` is equivalent to `yes`). Both modules are idempotent and handle different Linux distributions correctly.
Why the other options are wrong
- B. This option is incorrect because `apt` is distribution-specific, and while `systemd` module exists, the generic `service` module is preferred for broader compatibility. `state=started` and `enabled=yes` are valid for `service` module.
- C. `yum` is distribution-specific. Using `shell` for service management is generally discouraged in Ansible as it's not idempotent and doesn't leverage Ansible's built-in error handling and state management.
- D. This option is missing the `ansible.builtin.` prefix for the modules, which is good practice. Also, it combines package and service tasks incorrectly under a single name.
Ansible Package & Service Management
Ansible modules for managing software packages and their associated services on target hosts, ensuring desired states are met idempotently.
- `ansible.builtin.package` module manages software packages (e.g., install, remove, update).
- `ansible.builtin.service` module manages system services (e.g., start, stop, enable, disable).
- Both modules are idempotent: they only make changes if the system is not already in the desired state.
- They abstract away distribution-specific commands (e.g., `apt`, `yum`, `systemctl`, `service`).
Memory trick: Packages are installed, then services are started and enabled, all with Ansible's might.