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

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)

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:

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,

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. 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:

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
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()

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

port: 25

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

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(’ ') }}”

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