Linux Labs

Automation: Git and Ansible / Stage 4 of 6

Inventory and ad-hoc commands

Not running Starting usually ~20 s
Leave the lesson

Step 3 of 5 · on a machine · 8 min

An ad-hoc command: CHANGED and SUCCESS

Ansible does one job on every machine of a group with a single command — no description files.

An ad-hoc command looks like this: ansible <machines> -m <module> -a '<arguments>'. Machines are a name, a group or all; the module is the kind of work; the arguments say what exactly to do:

bash
# run a program on the web group machines
ansible web -m command -a 'uptime'
# put a file with this content on them
ansible web -m copy -a 'content="text\n" dest=/path/file'

The command module runs a program and returns its output. The copy module brings a file to its description: the path is dest, the content is content. Run copy twice and read the file with command.

Exercise · look

Run copy twice

In ~/ansible-lab put the file /home/student/note.txt on the web group machines twice with the copy module, then read it with the command module.

First, predict

The third command only reads the file. Which status will Ansible print for app1?

Now start the exercise, run the command and compare your prediction with the output.

Sign in and start The machine is available after signing in

After each command Ansible prints the machine's status. CHANGED means the module changed something. SUCCESS with "changed": false means everything was already right. copy compares the file with the description: the second time the file matched, and the module left it alone. command does not know what the program it runs does, so it always answers CHANGED — even for cat.

The property “a repeated run does not change what is already in the right state” is called idempotency. Working with Ansible rests on it: a description can be applied any number of times, and the answer shows where a machine differed.

Check yourself 1 question

The web group machines need the file /home/student/app.env with the line MODE=prod, and a repeated run has to show there is nothing to change. Which ad-hoc command do you pick?

  • The file appears, but command does not compare the result and answers CHANGED on every run — the answer does not tell whether the machine differed.

  • The file is the same, but the answers differ: command always says CHANGED, copy says SUCCESS when the file is already right. A repeat with -m copy shows it.

copy compares the file with the description and changes it only when they differ, so a repeat answers SUCCESS with "changed": false. command runs a program and does not judge the result — its answer is CHANGED on every run.

Ubuntu 24.04
Loading…