Conditionals: check type of element

2019-02-20 15:36发布

问题:

I'm looking for a syntax to check if a variable contains any subelements or is just a string. Lets say I have a file vars/myvars.yml

myvars: {
  key1: {
    greeting: "hello"
  },
  key2: {
    greeting: {
      en: "hi",
      fr: "bonjour"
    }
  }
}

I'm looking for a condition to only accept a string and no object. So in this case, key1.greeting should match the condition, but key2.greeting should not.

---
- name: test
  vars_files:
    - vars/myvars.yml
  hosts: all
  tasks:
  - debug: 
      msg: "greeting is '{{ item.value.greeting }}'"
    when: item.value.greeting ???is type string???
    with_dict: "{{ myvars }}"

Any ideas?

回答1:

You can use the type_debug filter:

when: "item.value.greeting | type_debug == 'your_wanted_type'"

For a string your_wanted_type might be AnsibleUnicode or unicode, depending on how you define the value.



标签: ansible