# \[Ansible Project\] Not able to process the shell command in control node

**URL:** <https://forum.ansible.com/t/ansible-project-not-able-to-process-the-shell-command-in-control-node/38272>\
**Category:** Ansible Project\
**Created:** [July 28, 2023, 6:12am UTC](https://forum.ansible.com/t/ansible-project-not-able-to-process-the-shell-command-in-control-node/38272 "2023-07-28T06:12:08Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![Prady\_A](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/prady_a/32/4792_2.png) [@Prady\_A](https://forum.ansible.com/u/Prady_A)\
**Post date:** [July 28, 2023, 6:12am UTC](https://forum.ansible.com/t/ansible-project-not-able-to-process-the-shell-command-in-control-node/38272/1 "2023-07-28T06:12:08Z")

</div>

Hi Experts,

Need your suggestion pls.

The below one is ansible file which calls an python file in the control node(localhost) and process an excel file which is also present in control node based on hostnames. There is no issue in processing the excel and now I am facing challenges while sending the file in mail.I am trying to extract the current logged in user in control node and send mail to that logged in user. But both my below command incoporated in python script are not working.  
#cmd = 'echo $USER  
#cmd = ‘who am i | cut -d" " -f 1’  
output, errors, return\_code = serverside\_execute\_command(cmd)

it seems my **serverside\_execute\_command(cmd):**  
I executed the python program standalone it is working as expected in the control node.But when it is called from Ansible code it is throwing the below error. Any insight would be greatly helpful.

**Error:**  
fatal: [jp1ld100 → localhost]: FAILED! =\> {“changed”: true, “msg”: “non-zero return code”, “rc”: 1, “stderr”: “Traceback (most recent call last):\n File "/root/.ansible/tmp/ansible-tmp-1690520194.14-32141-129555701534658/process\_hostnames\_v3.py", line 213, in \n mail(filename)\n File "/root/.ansible/tmp/ansible-tmp-1690520194.14-32141-129555701534658/process\_hostnames\_v3.py", line 168, in mail\n if not re.match(‘x’, output[0]):\nIndexError: list index out of range\n”, “stderr\_lines”: [“Traceback (most recent call last):”, " File "/root/.ansible/tmp/ansible-tmp-1690520194.14-32141-129555701534658/process\_hostnames\_v3.py", line 213, in “, " mail(dest\_filename)”, " File "/root/.ansible/tmp/ansible-tmp-1690520194.14-32141-129555701534658/process\_hostnames\_v3.py", line 168, in mail", " if not re.match(‘x’, output[0]):", “IndexError: list index out of range”], “stdout”: “Test.xltm\nFile [Test.xltm] has been updated and sent to mail\nDEBUG cmd: who am i | cut -d" " -f 1\nDEBUG return\_code: 0\n”, “stdout\_lines”: [“Test.xltm”, “File [Test.xltm] has been updated and sent to mail”, “DEBUG cmd: who am i | cut -d" " -f 1”, “DEBUG return\_code: 0”]}

**Process.yml:**  
name: Collect host  
hosts: all  
tasks:

- block:
- name: python  
script: “process\_hostnames.py ‘{{ arg }}’”  
args:  
executable: python3  
delegate\_to: localhost  
register: out  
vars:  
arg: “{{ ansible\_play\_hosts\_all | join(’ ') }}”
- debug:  
var: out.stdout\_lines  
run\_once: true

**process\_hostnames.py**

def **serverside\_execute\_command(cmd):**  
import subprocess  
try:  
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,  
check=True, shell=True, universal\_newlines=True)  
except subprocess.CalledProcessError:  
print(‘{0}’.format(result.stdout))  
sys.exit(1)

output =   
errors =   
stdout = result.stdout.splitlines()  
try:  
for line in stdout:  
if line.strip() == “”:  
pass  
else:  
output.append(line.strip())  
except UnicodeDecodeError:  
output = [“OUTPUT UNREADABLE”]  
try:  
errors.append(result.stderr.strip())  
except UnicodeDecodeError:  
errors = [" ERRORS UNREADABLE"]  
return\_code = result.returncode

print(“DEBUG cmd: {0}”.format(cmd))  
print(“DEBUG return\_code: {0}”.format(str(return\_code)))

return (output, errors, return\_code)

def mail(dest\_filename):  
#cmd = ‘echo $USER’  
cmd = ‘who am i | cut -d" " -f 1’  
output, errors, return\_code = **serverside\_execute\_command(cmd)**  
if not re.match(‘x’, output[0]):  
raise RuntimeError(“You are {0}.Please login as xID. Then try again.”.format(result.stdout))  
sys.exit(1)  
xid = output[0].rstrip(‘\n’)

if **name** == “ **main** ”:  
file\_name= “Template.xltm”  
mail(file\_name)

---

<div class="post-metadata">

**Author:** ![utoddl](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/utoddl/32/249_2.png) [@utoddl](https://forum.ansible.com/u/utoddl)\
**Post date:** [July 28, 2023, 12:43pm UTC](https://forum.ansible.com/t/ansible-project-not-able-to-process-the-shell-command-in-control-node/38272/2 "2023-07-28T12:43:02Z")

</div>

On my controller, `who am i` produces no output. In your python script running on my system, because there is no output, `output[0]` correctly produces the “IndexError: list index out of range” message.

Having your python script go to all that trouble to run an external program to get the user name seems a bit much. I’d suggest doing this instead:

```auto
import os
import pwd
userid = pwd.getpwuid(os.getuid())[0]

```

Then there’s the question of whether you want to roll your own email sending program rather than using the `community.general.notification.mail` module. There may be good reasons either way.

Good luck,

---

<div class="post-metadata">

**Author:** ![Prady\_A](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/prady_a/32/4792_2.png) [@Prady\_A](https://forum.ansible.com/u/Prady_A)\
**Post date:** [July 28, 2023, 2:46pm UTC](https://forum.ansible.com/t/ansible-project-not-able-to-process-the-shell-command-in-control-node/38272/3 "2023-07-28T14:46:19Z")

</div>

Hi Todd,

Thank you so much as always.  
Actually to run the ansible we switch from normal user to root user and run the ansible.  
In my case when I m running “who am i” from Putty it is working but when I am executing it from visual studio code using remote ssh login plugin there it is not working.  
Basically I want to send the mail from the user who logged in ex: [id@domain.com](mailto:id@domain.com). Even though we logged in as root when we give “who am i” it returns the logged in user even though you su to another user. I will try to use your code. Incase still my approach is bad please let me know.

Ex:

```auto
ubuntu /home/gara% who am i
gara pts/0 2008-06-20 11:36 (192.168.0.1)
ubuntu /home/gara% whoami
gara
ubuntu /home/gara% su -
Password:
root@ubuntu:~# who am i
gara pts/0 Jun 20 11:36 (192.168.0.1)
root@ubuntu:~# whoami
root
root@ubuntu:~#

```

Regarding the mailing function I am using the below. But it takes 10 min to send the mail.

class Send\_Mail:  
def **init** (self, to\_addrs, workbook\_path):  
self.to\_addrs = to\_addrs  
self.workbook\_path = workbook\_path  
d = self.workbook\_path.rsplit(“/”, 3)  
self.workbook\_filename = d[3]

def send\_mail(self):  
import smtplib  
from email.mime.text import MIMEText  
from email import encoders  
from email.mime.base import MIMEBase  
from email.mime.multipart import MIMEMultipart

msg = MIMEMultipart()  
msg[‘Subject’] = “Validation Result”  
msg[“From”] = “[Validation\_Result@domain.com](mailto:Validation_Result@domain.com)”  
msg[“To”] = self.to\_addrs  
msg.preamble = ‘excel test’

try:  
file = open(self.workbook\_path, ‘rb’)  
attachment = MIMEBase(‘application’, ‘vnd.ms-excel’)  
attachment.set\_payload(file.read())  
file.close()  
encoders.encode\_base64(attachment)  
attachment.add\_header(“Content-Disposition”, ‘attachment’, filename=self.workbook\_filename)  
msg.attach(MIMEText(‘Attached is your validation result.\n\n\n’, ‘plain’))  
msg.attach(attachment)

smtp = smtplib.SMTP(‘localhost’)  
smtp.send\_message(msg)  
smtp.close()  
except IOError as e:  
print(‘IOE Exception!!\n{0}’.format(e))  
except:  
raise RuntimeError(“Sorry,email could not be sent successfully.”  
"Please scp the validation result yourself, "  
"there might be something wrong with the email address or something\n ")  
else:  
print(‘Validation result is now being sent as an Excel file to {0}.’.format(self.to\_addrs))  
finally:  
smtp.close()  
file.close()

---

<div class="post-metadata">

**Author:** ![Evan\_Hisey](https://avatars.discourse-cdn.com/v4/letter/e/ce73a5/32.png) [@Evan\_Hisey](https://forum.ansible.com/u/Evan_Hisey)\
**Post date:** [July 28, 2023, 3:18pm UTC](https://forum.ansible.com/t/ansible-project-not-able-to-process-the-shell-command-in-control-node/38272/4 "2023-07-28T15:18:16Z")

</div>

This seems massively complicated for a simple shell command to send an email. ON top of that you are attempting to break the anisble.builtin.script module by forcing it to run on the localhost (controller) rather than the target. Better option would be to just use the either the command module and mailx or the community.general.mail.module, both options will run fine with the “delegate\_to: localhost” and require much less coding to make work.

A rough example base on the visible code:

name: mail host list

community.general.mail:

host: [mail.server.com](http://mail.server.com)

port: 25

---

<div class="post-metadata">

**Author:** ![Prady\_A](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/prady_a/32/4792_2.png) [@Prady\_A](https://forum.ansible.com/u/Prady_A)\
**Post date:** [July 28, 2023, 3:21pm UTC](https://forum.ansible.com/t/ansible-project-not-able-to-process-the-shell-command-in-control-node/38272/5 "2023-07-28T15:21:16Z")

</div>

Thank you both of you and code .  
I ll try to simplify it. since the module is already we are using in different program, i reused it.

Regards  
Prady

---

<div class="post-metadata">

**Author:** ![Evan\_Hisey](https://avatars.discourse-cdn.com/v4/letter/e/ce73a5/32.png) [@Evan\_Hisey](https://forum.ansible.com/u/Evan_Hisey)\
**Post date:** [July 28, 2023, 3:25pm UTC](https://forum.ansible.com/t/ansible-project-not-able-to-process-the-shell-command-in-control-node/38272/6 "2023-07-28T15:25:20Z")

</div>

You could reuse the module with some thing like:

name: send email

command: python3 /path/to/process\_hostnames.py ‘{{ arg }}’  
delegate\_to: localhost  
register: out  
vars:  
arg: “{{ ansible\_play\_hosts\_all | join(’ ') }}”

---

<div class="post-metadata">

**Author:** ![Prady\_A](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/prady_a/32/4792_2.png) [@Prady\_A](https://forum.ansible.com/u/Prady_A)\
**Post date:** [July 28, 2023, 3:37pm UTC](https://forum.ansible.com/t/ansible-project-not-able-to-process-the-shell-command-in-control-node/38272/7 "2023-07-28T15:37:47Z")

</div>

Hi Hissy,

As I said earlier I am extracting those hostname to an excel macro file which is done by python program and send that file to a different team. But I will consider your mail module inside the ansible now.

Regards
