开发者

Ansible conditionals with nested loops

开发者 https://www.devze.com 2022-12-07 17:12 出处:网络
I\'ve read the ansible docs on conditionals and loops. But it\'s still not clear to me how it exactly works.

I've read the ansible docs on conditionals and loops. But it's still not clear to me how it exactly works.

my yaml struct开发者_开发问答ure looks like this:

---
myusers:
   - username: user1
     homedir: 'home1'
     sshkey: 'ssh-rsa bla1'
   - username: user2
     homedir: 'home2'
     sshkey: 'ssh-rsa bla2'
     process: 
        - transfer:
          transtype: 'curl'
          traname: 'ftps://targetsystem'

          

my playbook part looks like this:

   - name: test j2
     debug:
       msg: |-
         dest: "/var/tmp/{{ item.0.username }}/{{ item.0.traname }} {{ item.1.transtype }}"
     when: item.0.process is not none
     loop: "{{ myusers | subelements('process')}}"

Now I only want to loop when the sub-element process exists. I had this working at one point but don't understand what I changed to break it. Mainly I don't understand what the effect of the sequence of 'when' and 'loop' has. It appears to me when I run it that the condition 'when' is ignored. Also when I swap the sequence of when and loop.

The error I get when running the playbook is :

FAILED! => {"msg": "could not find 'process' key in iterated item {u'username': u'user1' ...

I've also tried with different conditions like:

 item.0.process is defined
 myusers.username.process is not none

etc...


By default, the subelement lookup (and the corresponding filter) requires each top level element to have the subelement key (and will error with the above message if it does not exist)

You can change this behavior by setting the skip_missing parameter (note: I also fixed the index to address the traname key which was the wrong one in your question example)

   - name: test j2
     debug:
       msg: |-
         dest: "/var/tmp/{{ item.1.username }}/{{ item.0.traname }} {{ item.1.transtype }}"
     when: item.0.process is not none
     loop: "{{ myusers | subelements('process', skip_missing=true) }}"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号