cancel
Showing results for 
Search instead for 
Did you mean: 
cjan
Mission Specialist
Mission Specialist
  • 2,564 Views

how to replicate bash for loop with two if condition in ansible playbook?

hi

can someone show me how to replicate below bash script into ansible-playbook.

#!/bin/sh

for NODE in server01 server02 server03 server04

do

grep -q $NODE file1

RETURN1=$?

grep -q $NODE file2

RETURN2=$?

if [ $RETURN1 -eq 1 ] && [ $RETURN2 -eq 1 ]

then

echo $NODE

fi

done

Labels (2)
0 Kudos
4 Replies
Alexandre
Starfighter Starfighter
Starfighter
  • 2,555 Views

Hi,

Look, please, at example below:

- name: Multi if demo
   hosts: all
   gather_facts: false
   vars:
      file1: "server02 server03"
      file2: "server03 server04"
   tasks:
       - name: Simple multi if demo
         debug:
            msg: "{{ inventory_hostname }}"
         when:
             - inventory_hostname in file1
             - inventory_hostname in file2

cjan
Mission Specialist
Mission Specialist
  • 2,540 Views

thanks you. it works.

Is it possible to pass content of file1 and file2 as variable in file1 and
file2.

cat file1
-------
server02
server03

cat file2
---------
server03
server04


Thanks
Shrijan
0 Kudos
Alexandre
Starfighter Starfighter
Starfighter
  • 2,534 Views

Hi

It is a little bit more complicate:

- name: Multi if demo
   hosts: all
   gather_facts: false
   vars:
     file1s: "{{ lookup('file','file1') }}"
     file2s: "{{ lookup('file','file2') }}"
   tasks:
     - name: Simple multi if demo
   debug:
      msg: "{{ inventory_hostname }}"
   when:
      - inventory_hostname in file1s
      - inventory_hostname in file2s

Good luck.

 

0 Kudos
cjan
Mission Specialist
Mission Specialist
  • 2,537 Views

Many Thanks Alex.

 

its works now. 

0 Kudos
Join the discussion
You must log in to join this conversation.