Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 29 ยท Everyday Modules

Services, Commands and Scheduling

Control services with service and systemd, schedule jobs with cron, run commands safely, wait for ports, check health with uri, reboot hosts and restart through handlers.

Installing software and writing config files is only half the job. The software also has to run, restart when its configuration changes, start again after a reboot, and prove that it is healthy. This lesson covers the modules that deal with running things: service and systemd, cron, command, shell and script, then the "wait and verify" modules wait_for and uri, and finally reboot.

The real modules act on a managed host, so their examples are read-only. Two JavaScript stand-ins let you watch the logic: a small service state machine that explains why started is idempotent but restarted is not, and a retry loop that models until, retries and delay for health checks.

Services: service and systemd

The ansible.builtin.service module is the portable choice; it talks to whatever init system the host uses. When you know the host runs systemd, ansible.builtin.systemd_service (also callable as ansible.builtin.systemd) adds systemd-only options such as daemon_reload and masked.

YAML
- name: Ensure nginx is running and starts at boot
  ansible.builtin.service:
    name: nginx
    state: started
    enabled: true

- name: Pick up a new unit file, then start the app
  ansible.builtin.systemd_service:
    name: myapp
    state: started
    enabled: true
    daemon_reload: true

There are two independent settings here. state is about right now: started, stopped, restarted or reloaded. enabled is about boot time: whether the service starts automatically. Setting one does not touch the other.

The important idempotence rule: started and stopped describe a state and change nothing when the service is already there. restarted and reloaded describe an action and always do their work, so they always report changed. That is why you rarely write state: restarted in a normal task. You use a handler instead, so the restart happens only when a config task actually changed something.

YAML
tasks:
  - name: Write the nginx config
    ansible.builtin.template:
      src: nginx.conf.j2
      dest: /etc/nginx/nginx.conf
      validate: "nginx -t -c %s"
    notify: Reload nginx

handlers:
  - name: Reload nginx
    ansible.builtin.service:
      name: nginx
      state: reloaded

Handlers run once at the end of the play, no matter how many tasks notified them (see Handlers, Tags and Task Control). Prefer reloaded over restarted when the program supports it, because a reload does not drop connections.

Here is the state machine in code. It tracks whether a service is running and enabled, and reports whether each request changed anything.

JS A service state machine

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that the second started and the second stopped report nothing, while restarted changes every time.

Scheduling: cron

The ansible.builtin.cron module manages entries in a user's crontab. Always give the entry a name: Ansible stores it as a comment above the line and uses it to find and update that entry later. Without a name, every run could add another copy.

YAML
- name: Nightly database backup at 02:30
  ansible.builtin.cron:
    name: "nightly backup"
    minute: "30"
    hour: "2"
    user: backup
    job: "/usr/local/bin/backup.sh >> /var/log/backup.log 2>&1"

- name: Remove the old cleanup job
  ansible.builtin.cron:
    name: "old cleanup"
    state: absent

For the whole system, cron_file: ansible_backup writes a file under /etc/cron.d/ instead of a user's crontab. On systems that use systemd, a timer unit is a modern alternative, and you manage it with template plus systemd_service as above.

Running commands: command, shell and script

When no module does the job, you run a command. Three modules exist, and choosing carefully matters.

YAML
- name: Initialize the database once
  ansible.builtin.command:
    cmd: /opt/myapp/bin/init-db --force-nothing
    creates: /var/lib/myapp/.initialized

- name: Count error lines (needs a pipe, so shell)
  ansible.builtin.shell: "grep -c ERROR /var/log/myapp.log | tee /tmp/errors.txt"
  register: error_count
  changed_when: false
  failed_when: error_count.rc > 1

- name: Run a local script on the remote host
  ansible.builtin.script:
    cmd: scripts/rotate.sh --keep 7
    creates: /var/lib/myapp/.rotated
  • command runs the program directly, with no shell. Pipes, redirects, wildcards, && and environment variables like $HOME do not work. That limitation is a feature: it is safer and more predictable. Use argv: (a list) for arguments that contain spaces.
  • shell runs the text through /bin/sh, so pipes and redirects work. Use it only when you need them, and quote any variable that holds outside data with | quote.
  • script copies a script from the control node, runs it on the host, and does not require the script to be installed there first.

None of the three knows whether a command changed anything, so each always reports changed unless you tell it otherwise. Use creates: or removes: to skip the task when a path exists (or does not), and changed_when and failed_when to define the result yourself, as in Modules and Idempotence. Before you reach for any of them, search ansible-doc -l for a real module.

Waiting and verifying: wait_for and uri

After starting a service, do not assume it is ready. The wait_for module polls until a condition holds or the timeout ends the task with a failure.

YAML
- name: Wait until the app accepts connections
  ansible.builtin.wait_for:
    host: 127.0.0.1
    port: 8080
    delay: 2
    timeout: 60
    state: started

- name: Wait for the log to say ready
  ansible.builtin.wait_for:
    path: /var/log/myapp.log
    search_regex: "server ready"
    timeout: 30

An open port means something is listening, not that it works. The uri module makes a real HTTP request and can check the status code and the body, so it is the right tool for a health check. Combine it with retries, delay and until so a slow start does not fail the run.

YAML
- name: App health check
  ansible.builtin.uri:
    url: http://127.0.0.1:8080/health
    status_code: 200
    return_content: true
  register: health
  until: health.status == 200
  retries: 10
  delay: 3
  changed_when: false

changed_when: false matters: a read-only check should never show as a change. The uri module can also run from the control node with delegate_to: localhost when you want to test the service from the outside, the way a user would.

The next stand-in models the retry loop. It "starts" a service that becomes healthy on the fourth attempt, and shows how retries and delay decide whether the task passes.

JS Retries until healthy

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In real Ansible the first request is attempt 1 and retries counts the extra tries, so the total is retries + 1 at most; the stand-in follows that rule.

Rebooting

Some changes (kernel updates, for example) need a reboot. The reboot module restarts the host, waits for it to come back, and then runs a test command to make sure it is really usable, all inside one task so the play can continue.

YAML
- name: Reboot if the kernel was updated
  ansible.builtin.reboot:
    reboot_timeout: 600
    test_command: uptime
  when: kernel_updated | default(false)

Use it deliberately. In a group of web servers, combine it with serial so only some hosts are down at a time, which you will see in Handlers, Tags and Task Control and later in the rolling-update projects.

flowchart TD
  A["Config file task<br/>changed?"] -- yes --> B["notify handler"]
  A -- no --> Z["Nothing to restart"]
  B --> C["Handler runs once<br/>at end of play"]
  C --> D["service: reloaded"]
  D --> E["wait_for: port open"]
  E --> F["uri: /health returns 200"]

The usual chain: change the config, let a handler reload, then wait and verify.

Do not use shell: systemctl restart nginx or shell: service nginx restart. They always report changed, they do not check the result the way the service modules do, and they hide your intent. Use service or systemd_service.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A task says service: name=nginx state=started. The service is already running. What does the task report?

    started describes a state. When the service is already running, Ansible changes nothing and reports ok.
  2. 2. Why should a cron task always have a name?

    Ansible stores the name as a comment above the cron line and looks it up by that name when the task runs again.
  3. 3. You need a pipe in a command. Which module do you use, and what else should you add?

    command does not use a shell, so pipes fail. shell works but always reports changed, so you define the result yourself.
  4. 4. Why is a uri health check better than wait_for on a port alone?

    A listening port only means a socket is open. A real request shows whether the application responds correctly.

Summary

  • service is portable; systemd_service adds daemon_reload and other systemd features. state and enabled are independent.
  • started and stopped are idempotent states; restarted and reloaded always change, so trigger them from handlers.
  • cron entries need a name so Ansible can update or remove them later.
  • command has no shell, shell has pipes but always reports changed, script runs a local file remotely; control results with creates, removes, changed_when and failed_when.
  • wait_for waits for ports, files or text; uri checks real HTTP health, with until, retries and delay.
  • reboot waits for the host to return and can run a test command; pair it with serial on groups.

Next: Windows, Network Devices and Cloud Modules.