Categories

Sep 19, 2019 in Ansible

Q: Ansible shell

1 Answer

Oct 11, 2019
The Ansible shell and command modules are used for executing commands in remote servers. Both modules take the command name followed by a list of arguments.

Ansible Shell Module and Command Module

We can use the shell module when we need to execute a command in remote servers, in the shell of our choice. By default, the commands are run on the /bin/sh shell. You can make use of the various operations like ‘|’,'<‘,’>’ etc. and environment variables like $HOME.

If you don’t need those, you should use the command module instead. The command module does not process the commands through a shell. So it doesn’t support the above-mentioned operations.

You give the command you want to execute the same way you give it on a Unix shell, command name followed by arguments.

- name: Executing a Command Using Shell Module

  shell: ls -lrt > temp.txt

- name: Executing a command using command module

  command: cat hello.txt

The first command lists all the files in the current folder and writes that to the file, temp.txt. The second example displays the content of the hello.txt file.

Changing Default Directory and Shell

In the last examples, the command will always be executed in the default directory. You can change this behavior, and specify the directory path where you want to run the command using chdir parameter. This is available for both shell and command modules.

You can also change the default shell by specifying the absolute path of the require shell in the executable parameter.

- hosts: loc

  tasks:

  - name: Ansible Shell chdir and executable parameters

    shell: ls -lrt > temp.txt

    args:

      chdir: /root/ansible/shell_chdir_example

      executable: /bin/bash

- hosts: loc

  tasks:

  - name: Ansible command module with chdir and executable parameters

    command: ls -lrt

    args:

      chdir: /home/mdtutorials2/command_chdir_example

      executable: /bin/bash

In both examples, I am using the ‘Bourne Again SHell’ by giving the absolute path /bin/bash. And I have changed the directory to /root/ansible/shell_chdir_example.

Note: Shell and command modules are among the few modules in Ansible which are not idempotent by default. So if you rerun a task, the system status is not checked before running. For some tasks like the last example, it is also desired.
Click here to read more about Ansible
Click here to read more about Insurance

Related questions

Madanswer
Aug 24, 2019 in Ansible
Aug 24, 2019 in Ansible
Aug 24, 2019 in Ansible
...