Total Pageviews

Translate

April 3, 2018

Using Shell and Command modules in Ansible

by 4hathacker  |  in Redhat Enterprise Linux at  8:06 AM

Hi folks...

Welcome to MyAnsibleQuest !!!



After a long break, I am writing on my blog and this is in continuation with other Ansible posts. In this post, we will observe the usage of shell and command module with simple examples particularly to find out the differences between them.

Before starting, I would like to share some information about the environment setup for this post. 

1. I have an inventory file in /etc/ansible/hosts which consists of 3 servers (node 218 and node 227 are in webservers group while node 222 is in dbservers group).



2. I am using PyCharm as a code view editor for defining yaml files and running them in the terminal of PyCharm only.

3. Ansible 2.5 came in the beginning of this year only. We will be using the same in a virtual environment (Ansible_Shell_Command_Script) setup in python 2.7.



So, let's start with the shell module. Before starting let us check which shell is there in RHEL7.2 OS. To check this, type "echo $0" or "file -h /bin/bash" or "file -h /bin/sh" in the shell,



For me it came as '/bin/bash'. It may be something different if you are using some other OS.

Now, the shell module, almost similar to command module, accepts a command name with a list of space separated arguments. The prime concern here is, whatever the command we are passing, it goes through the shell (/bin/bash) on the remote node. The shell by default is /bin/sh and the option can be changed by using argument as 'executable: /bin/bash'.

Case 1: We will check a simple cat command for all the log files present in the /tmp directory.

Playbook:

Output:


Case 2: We will print some environment variables like $HOME, $ JAVA_HOME in a text file.

Playbook:

Output:


Conclusion: 

1. The command module fails to do so because of * wildcard. In case of operators like “<”, “>”, “|”, ”;” and “&” it will not work.
2. The command module will remain unaware of the environment variables yet it seems like there is no error and playbook runs well. If you look at the output, the state is seen as changed for all the tasks, even though in the second task command module did nothing.

This can be checked if we  look for the .txt files in both node218 and node227.




So, its important to use command and shell module carefully. The way we can access environment variables is given below. In my view, sometimes it will be better to take help from Ansible docs and look for similar modules for performing tasks, rather to rely on command or shell module.

To access local environment variables we can use either gather_facts or env look up.



That's all for this post.

0 comments:

Like Our Facebook Page

Nitin Sharma's DEV Profile
Proudly Designed by 4hathacker.