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