Conditional looping through a dict with "when"

34 views
Skip to first unread message

Alexander Rilik

unread,
Feb 20, 2016, 11:35:15 AM2/20/16
to Ansible Project
Hello all,

I'm implementing a custom role to setup a bunch of network device profiles to be later associated to LXD containers.
A loop over a list of eth/br devices would be used to achieve this. The loop is not an issue but I'd like to implement a "when" condition so to attempt to create the bridge only when it is not there already.

To clarify further, the logic would be the following:
- for each element in the bridge mapping dictionary, run this: lxc profile show br_dev <key>
- if the command returns 1, the bridge does not exist, so let's create it in the next task
- run profile creation task: lxc profile create dev_br<key>
- run another task to associate the physical device to the profile

So, the problem: how do I prevent the subsequent tasks from running if the bridges already exist? I know the "when" clause is great to prevent a task from running in certain conditions, but what I want here is to run only part of the task (that is, only some parts of the loop).
I'm thinking of using the output of each command's "rc" stored in the register variable, but can't find a way to include it in my subsequent loops!
Any alternative, cleaner way is more then welcome. A colleague suggested, for instance, to rely on subtasks included as sub-yamls but I'm still thinking how to turn that into reality.

I feel I've been unclear, yet I'm confident your understanding skills are greater than my explanatory skills.

Thank you! I'm providing the files:

group_vars:

---
bridge_mapping
:
 
250: eth0
 
150: eth0
 
23: eth1

main role file:

---
- name: check if profile exists
  command
: lxc profile show br_dev{{ item.1.id }}
  ignore_errors
: yes
 
register: profile_exists
  with_subelements
:
 
- exposure_alternative
 
- vlans
  tags
:
   
- lxd_setup
   
- lxd_profiles_create




- debug: var={{ item }}
  with_items
: profile_exists.results
  tags
:
   
- debug


- name: setup lxd profile
  command
: lxc profile create dev_br{{ item.key }}
  with_dict
: bridge_mapping
 
when: <what should be here?>
  tags
:
   
- lxd_setup
   
- lxd_profiles_create


- name: setup lxd profile dev
 
# sample command: lxc profile device add dev_br123 eth1 nic nictype=bridged parent br123
  command
: lxc profile device add dev_br{{ item.key }} {{ item.value }} nic nictype=bridged parent=br{{ item.key }}
  with_dict
: bridge_mapping
 
when: <what should be here?>
  tags
:
   
- lxd_setup
   
- lxd_profiles_create



Reply all
Reply to author
Forward
0 new messages