Javatpoint Logo
Javatpoint Logo

Ansible Command

Ansible command module is used to run any commands or run any scripts in the remote target machine. Or used to execute commands on a remote node.

The command module is used to run simple Linux commands on a remote node or server, which is a part of the host group or standalone server mentioned in the host group.

Ansible Command Module and Shell Module

The shell module is used when we need to execute a command in remote servers, in the shell of your choice. By default, the commands are run on the /bin/sh shell. You can make use of the various operations such as '|', '<', '>' etc. and environmental variables such as $HOME.

The command module does not process the commands through a shell. So it does not support the above operations.

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

The first command lists all the files in the current folders and writes that to the file, temp.txt.

The above example displays the content of the hello.txt file.

Changing the Default Directory

The command will always execute in the default directory. You can change and specify the directory path where you want to run the command using the chdir parameter. This parameter is available for both command and shell module.

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

In the above example, using the "Bourne Again Shell" by giving the obsolete the path /bin/bash. And changed the directory to /home/Ansible/command_chdir_example.

Executing Multiple Commands

If you need to run multiple commands, then you can give them to both shell and command modules using the "with_items".

Example 1:

Example 2:

In the above examples, we want to execute three files; hello.txt, hello1.txt, and hello2.txt. Since I give the {{item}} keyword in the command, it will be replaced with an element of the list in each iteration. Ensure that the level of indentation of "with_item" is on the same level as the module name.


Next TopicAnsible File




Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA