Jeremy Huey
Jeremy Huey

Reputation: 11

looping a shell command in ansible

I'm trying to get going with some more advanced Ansible playbooks and have hit a wall. I'm trying to get Ansible to do what this /bin/bash 'for' loop does;

for i in $(</filename.txt);do '/some/command options=1 user=usera server=$i';done

filesnames.txt contains 50-100 hostnames.

I can't use jinja templates as the command has to be run, not just the config file updated.

Any help would be greatly appreciated.

Thanks in advance, Jeremy

Upvotes: 1

Views: 23310

Answers (1)

mvk_il
mvk_il

Reputation: 960

  1. you can use jinja templates, but differently
  2. your specific code is not doing something that is most advisable
  3. for multi-line code you should use shell module.

example of multi-code piece of call:

- name: run multiline stuff
  shell: |
    for x in "${envvar}"; do
       echo "${x}"
    done
  args:
    executable: /bin/bash

note I'm explicitly setting executable, which will ensure bash-isms would work.

I just used envvar as an example, of arbitrary environment variable available.

if you need to pass specific env variables, you should use environment clause of the call to shell module, refer to: http://docs.ansible.com/ansible/playbooks_environment.html

For simple variables you can just use their value in shell: echo "myvar: {{myvar}}"

If you wish to use an ansible list/tuple variable inside bash code, you can make it bash variable first. e.g. if you have a list of stuff in mylist, you can expand it and assign into a bash array, and then iterate over it. the shell code of the call to shell would be:

    mylist_for_bash=({{mylist|join(" ")}})
    for myitem in "${mylist_for_bash[@]}"; do
      echo "my current item: ${myitem}"
    done

Another approach would be to pass it as string env variable, and convert it into an array later in the code.

NOTE: of course all this works correctly only with SPACELESS values I've never had to pass array with space containing items

Upvotes: 3

Related Questions