The lab installs three packages with name: "{{ packages }}" instead of a loop, and starts services with loop: "{{ services }}". Why the difference, and what do state: started and enabled: true each guarantee?
Package modules accept a list in name and install everything in one transaction, which is faster than one run per package; service takes one name, so it needs a loop. started means running now, enabled means started at boot.
- name: Sicherstellen, dass erforderliche Pakete vorhanden sind
ansible.builtin.apt:
name: "{{ packages }}" # apache2, openssl, ca-certificates
state: latest
update_cache: yes
- name: Sicherstellen, dass Dienste gestartet und aktiviert sind
ansible.builtin.service:
name: "{{ item }}"
state: started
enabled: true
loop: "{{ services }}"
Passing the whole list to apt lets apt resolve dependencies once and download and install in a single step. A loop would call apt three times. Ansible's docs recommend the list form for package modules for this reason.
The service task sets two separate properties:
| Option | Guarantees | Without it |
|---|---|---|
state: started |
the service is running now | it may be stopped until someone starts it |
enabled: true |
it starts at the next boot | it is gone after a reboot |
Both are idempotent: on a host where Apache already runs and is enabled, the task reports ok.
Go deeper:
ansible.builtin.service module (official docs) —
stateandenabled.ansible.builtin.apt module (official docs) —
nameas a list,state: latest,update_cache.