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,
--
Todd

On 7/28/23 2:12 AM, Prady A wrote:
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 <module>\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 <module>", "    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)

--
You received this message because you are subscribed to the Google Groups "Ansible 
Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/d3d38e2c-9984-89df-eb86-e3795162c9d6%40gmail.com.

Reply via email to