1

I wanted to send the hostnames from ansible role to python script. In my host file there are 2 hosts 1ld900 and 1ld901.

my role as below

 ---
    - name:execute python
      script: writetoexcel.py {{ ansible_play_hosts_all | join(" ") }}
      args:
        executable: python3
      delegate_to: localhost

But while passing it passing some extra "[" to python script. like below and also there is only one index in list.

[['1ld900','1ld901']]

without the join then it is sending some other garbage character marked in bold

 "[['**[u**1ld900,', '**u**1ld901**]**']]

kindly help me to send a clean list to python script like below

["1ld900","1ld901"]
user984993
  • 23
  • 3

1 Answers1

2

Short answer: Quote the argument

    - script: writetoexcel.py "{{ ansible_play_hosts_all|join(' ') }}"

Details:

Given the inventory

shell> cat hosts
cluster
svm1
svm2

and the Python script for testing

shell> cat test.py
import sys


for arg in sys.argv:
    print(arg)

The playbook

shell> cat pb.yml
- hosts: all

  tasks:

    - block:
        - script: test.py {{ ansible_play_hosts_all|join(' ') }}
          args:
            executable: python3
          delegate_to: localhost
          register: out
        - debug:
            var: out.stdout_lines
      run_once: true

gives (abridged)

TASK [debug] *****************************************************************************
ok: [cluster] => 
  out.stdout_lines:
  - /home/admin/.ansible/tmp/ansible-tmp-1687401621.3263886-1295583-29148533099582/test.py
  - cluster
  - svm1
  - svm2

The first argument is the path of the script and the other arguments are all hosts in the play. You have to quote the argument on the command line if you want to get them in a single argument. Because of the multiple quoting levels, it's better to create a variable for this purpose

    - block:
        - script: "test.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

gives (abridged)

TASK [debug] *****************************************************************************
ok: [cluster] => 
  out.stdout_lines:
  - /home/admin/.ansible/tmp/ansible-tmp-1687401621.8429682-1295611-212016290172502/test.py
  - cluster svm1 svm2
Vladimir Botka
  • 5,138
  • 8
  • 20
  • Thank you for detailed. + – user984993 Jun 22 '23 at 07:54
  • @user984993, in that case you may check on [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers) and [Accept the answer](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work). – U880D Jun 22 '23 at 12:21