TExcelTAD
Home › Configuration Management: Ansible › command & shell Without Breaking Idempotency

command & shell Without Breaking Idempotency

Sometimes no module does what you need: a vendor installer, make install, a database migration, a CLI that registers the server somewhere. command and shell run it, but Ansible has no idea what the program did, so by default it reports changed on every run. That breaks two things: the changed count no longer means anything, and handlers notified by the task fire every time.

Module Runs Use when
command the program directly, no shell the default choice
shell through /bin/sh you need pipes, redirects, &&, globs or $VARS
script a local script, copied to the host and run a longer script you keep next to the playbook
raw an SSH command without Python bootstrapping a host that has no Python yet

Pass arguments as a list (argv:) or through cmd:; with argv there is no word splitting or quoting to worry about.

Three ways to make a command idempotent

1. creates / removes. Skip the command if a file exists (creates) or doesn't (removes). Ideal for "run the installer once":

bash · try it yourself
cat > once.yml <<'YML'
- name: Run an installer once
  hosts: localhost
  gather_facts: false
  tasks:
    - name: Unpack the tool (only if not done yet)
      ansible.builtin.command:
        cmd: sh -c 'mkdir -p tool && echo v1.4 > tool/VERSION'
        creates: tool/VERSION
YML
ansible-playbook once.yml | grep -E '^(ok|changed)'
ansible-playbook once.yml | grep -E '^(ok|changed)'
changed: [localhost]
ok: [localhost]

2. changed_when. Decide from the output whether anything changed. Many tools print something different when there was nothing to do:

bash · try it yourself
cat > migrate.sh <<'SH'
#!/bin/sh
# a stand-in for a migration tool: applies pending migrations once
if [ -f .migrated ]; then echo "No migrations to apply."; else touch .migrated; echo "Applied 3 migrations."; fi
SH
chmod +x migrate.sh
cat > migrate.yml <<'YML'
- name: Database migrations
  hosts: localhost
  gather_facts: false
  tasks:
    - name: Apply pending migrations
      ansible.builtin.command:
        argv: [./migrate.sh]
      register: mig
      changed_when: "'No migrations to apply' not in mig.stdout"
YML
ansible-playbook migrate.yml | grep -E '^(ok|changed)'
ansible-playbook migrate.yml | grep -E '^(ok|changed)'
changed: [localhost]
ok: [localhost]

For read-only commands (git rev-parse HEAD, systemctl is-active), simply write changed_when: false.

3. Check first, act only when needed. Run a read-only check, register its result, and make the real command conditional:

yaml
- name: Is the node already in the cluster?
  ansible.builtin.command: consul members
  register: members
  changed_when: false

- name: Join the cluster
  ansible.builtin.command: consul join 10.0.1.10
  when: inventory_hostname not in members.stdout

failed_when: when the exit code lies

Some programs exit non-zero for normal situations (grep finds nothing → exit 1), others exit 0 on failure. failed_when replaces the default rule "rc != 0 means failed":

bash · try it yourself
printf 'alpha\nbeta\n' > list.txt
cat > grep.yml <<'YML'
- name: grep without false failures
  hosts: localhost
  gather_facts: false
  tasks:
    - name: Look for gamma
      ansible.builtin.command:
        argv: [grep, -c, gamma, list.txt]
      register: found
      changed_when: false
      failed_when: found.rc not in [0, 1]

    - name: Report
      ansible.builtin.debug:
        msg: "gamma lines: {{ found.stdout }} (rc={{ found.rc }})"
YML
ansible-playbook grep.yml | grep -E '^(ok|changed|fatal)|msg'
ok: [localhost]
ok: [localhost] => {
    "msg": "gamma lines: 0 (rc=1)"

shell, safely

When you need shell, add set -o pipefail so a failure early in a pipeline isn't hidden by a successful last command (ansible-lint checks for this), and set executable: /bin/bash, since /bin/sh on Debian and Ubuntu is dash, which only gained pipefail recently:

yaml
- name: Count error lines in the app log
  ansible.builtin.shell:
    cmd: set -o pipefail && grep -c ERROR /var/log/app.log | tee /tmp/errors
    executable: /bin/bash
  register: errors
  changed_when: false
  failed_when: errors.rc > 1

Never put untrusted values into a shell command line: {{ user_input }} inside cmd: is a shell injection. Use command with argv, or the | quote filter.

Test yourself

A command task without creates, removes or changed_when runs twice. What does the second run report?

  1. ok
  2. changed
  3. skipped
  4. failed

Which option skips a command when a file already exists?

  1. removes
  2. creates
  3. stat
  4. chdir

Why add failed_when: result.rc not in [0, 1] to a grep task?

  1. grep exits 1 when nothing matches, which is not an error here
  2. grep always fails
  3. To hide all errors
  4. To make it changed