Score:0

Not able to execute shell commands in ansible control node

gw flag

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'

it seems my serverside_execute_command(cmd): function is working. 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 ID. Then try again.".format(result.stdout))
       sys.exit(1)
    id = output[0].rstrip('\n')   
 
  
if __name__ == "__main__":
file_name= "Template.xltm"
mail(file_name)
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.