mohtashim
mohtashim

Reputation: 57

How to read and print Ansible set_fact array in unix shell script

I created a String array using set_fact which contains path to different files as below.

   - name: set_fact
     set_fact
       fpath: []
     set_fact:
       fpath: "{{ fpath + [ BASEPATH ~ '/' ~ item|basename ] }}"
     loop: "{{ Source_Files.split(',') }}"
     vars:
      fpath: []

   - name: Printing fpath
     debug:
       var: fpath

I pass the variable fpath to a shell script as below:

   - shell: "~/backup.sh '{{ fpath }}' > ~/backup.log"

Below is my backup.sh

echo "Prameter 1:"$1 > ~/param.out

IFS=
FPATH=`python <<< "print ' '.join($FPATH)"`
echo "${FPATH[@]}"
for a in "$FPATH"; do
  echo "Printing Array: $a"
  echo $a >> ~/stuffarray.txt
done

Prameter 1 print all the three files in the below format

Output:

Prameter 1:[u/tmp/scripts/file1.src, u/var/logs/wow.txt, u/tmp.hello.exe]

However the conversion of $1 which is a python string array to a Unix shell script array is not happening and it does not print any value for Unix shell script array. This is more of a passing python style string array and reading it in the shell script by looking through the values.

I'm on the latest version of ansible and python.

Can you please suggest how can I pass the the python string array from ansible to a shell script variable so I could loop through it ?

Upvotes: 1

Views: 584

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68074

The variable fpath is cleared on each iteration of the loop

   - name: set_fact
     set_fact:
       fpath: "{{ fpath }} + [ '{{ BASEPATH }}/{{ item | basename }}' ]"
     with_items:
       - "{{ Source_Files.split(',') }}"
     vars:
       fpath: []

Correct

   - name: set_fact
     set_fact:
       fpath: "{{ fpath|default([]) + [ BASEPATH ~ '/' ~ item|basename ] }}"
     loop: "{{ Source_Files.split(',') }}"

, or if fpath might have been used before

   - set_fact:
       fpath: []
   - set_fact:
       fpath: "{{ fpath + [ BASEPATH ~ '/' ~ item|basename ] }}"
     loop: "{{ Source_Files.split(',') }}"

(not tested)

Upvotes: 1

Related Questions