Ansible: How to run the for command through playbook

58 views
Skip to first unread message

nishant bawane

unread,
Apr 6, 2017, 2:22:36 PM4/6/17
to Ansible Project
Below is the playbook using "for command".

Playbook:

    - name: "Fetch the ip of all the servers from hosts.new file"
      shell: for i in `awk '{print $1}' hosts.new`
               do echo "$i"
               done
      args:
        chdir: "/home/dp794d/"
      failed_when: "output.rc > 1"
      register: output
   - debug: msg="{{ output.stdout }}"

Actual output :

PLAY [myserver] ****************************************************************

TASK [setup] *******************************************************************
ok: [zlp12037]

TASK [Fetch the ip of all the servers from hosts.new file] *********************
changed: [zlp12037]

TASK [set_fact] ****************************************************************
ok: [zlp12037]

TASK [debug] *******************************************************************
ok: [zlp12037] => {
    "output.stdout": ""
Expected output :

12.82.240.174
12.82.240.166
12.82.224.62
12.82.224.70

Kai Stian Olstad

unread,
Apr 6, 2017, 2:55:06 PM4/6/17
to ansible...@googlegroups.com
On 06. april 2017 18:55, nishant bawane wrote:
> Below is the playbook using "for command".
>
> Playbook:
>
> - name: "Fetch the ip of all the servers from hosts.new file"
> shell: for i in `awk '{print $1}' hosts.new`
> do echo "$i"
> done
> args:
> chdir: "/home/dp794d/"
> failed_when: "output.rc > 1"
> register: output
> - debug: msg="{{ output.stdout }}"
>
> Actual output :
>
> PLAY [myserver]
> ****************************************************************
>
> TASK [setup]
> *******************************************************************
> ok: [zlp12037]
>
> TASK [Fetch the ip of all the servers from hosts.new file]
> *********************
> changed: [zlp12037]
>
> TASK [set_fact]
> ****************************************************************
> ok: [zlp12037]
>

I'm baffled that you didn't get an error message since your for loop is
not valid syntax.

Try:

shell: for i in `awk '{print $1}' hosts.new`;
do echo "$i";
done


Or on one line

shell: for i in `awk '{print $1}' hosts.new`; do echo "$i"; done


--
Kai Stian Olstad

nishant bawane

unread,
Apr 10, 2017, 9:00:29 AM4/10/17
to Ansible Project, ansible-pr...@olstad.com
Thanks for your help, it worked fine.
Reply all
Reply to author
Forward
0 new messages