Ansible adhoc command

Ansible can run a command on the remote nodes. quite easily.

ansible command

Use ansible command, not ansible-playbook command which you use often.

% ansible webservers -a "free -m"

Web01 | success | rc=0 >>
             total       used       free     shared    buffers   cached
Mem:          3831        444       3387          0         87   157
-/+ buffers/cache:        199       3632
Swap:            0          0          0
Web02 | success | rc=0 >>
             total       used       free     shared    buffers   cached
Mem:          3831       2656       1174          0        401   306
-/+ buffers/cache:       1949       1881
Swap:            0          0          0

If you want to use pipe or redirect, use -m shell.

% ansible webservers -m shell -a "free -m | grep Mem"

Web01 | success | rc=0 >>
Mem:          3831        444       3386          0         87 157

Web02 | success | rc=0 >>
Mem:          3831       2657       1174          0        401 306

Hence, you can get server information from all hosts.

-m specifies module. There are many examples.

ex 1: copy files to remote nodes

% ansible webservers -m copy -a "src=/tmp/spam dest=/tmp/ham"

ex 2: make a directory on the remote nodes

% ansible webservers -m file -a "dest=/path/to/c mode=644 owner=mdehaan group=mdehaan state=directory"

ex 3: package install

% ansible webservers -m yum -a "name=dstat state=installed"

ex 4: deploy via git

% ansible webservers -m git -a "repo=git://foo.example.org/repo.git dest=/srv/myapp version=HEAD"

ex5: managing services

% ansible webservers -m service -a "name=httpd state=started"

Tips: store command results to files

ansible command has a -t option. When you specify this option, the command results will be outputted to the specified directory with JSON format. Files are separated by the hosts.

% ansible webservers -a "free -m" -t tmp

% ls tmp/
Web01 Web02

This is an example of the json file.

{
    "changed": true,
    "cmd": [
        "free",
        "-m"
    ],
    "delta": "0:00:00.003748",
    "end": "2014-01-21 22:32:18.565043",
    "rc": 0,
    "start": "2014-01-21 22:32:18.561295",
    "stderr": "",
    "stdout": "             total       used       free     shared
    buffers     cached\nMem:          3831        444       3386
    0         87        157\n-/+ buffers/cache:        198
    3632\nSwap:            0          0          0"

You can use ansible command with some monitoring system or record long-live command, or something else. Try it and find your use-case.