TRW
TRW

Reputation: 1004

Omit attribute when fact is not defined

I've currently many of this tasks. The file module here is just an example.

- file:
    path: "{{ datapath }}"
    state: "directory"
  when:
    - "storage is not defined"

- file:
    path: "{{ datapath }}"
    state: "directory"
  delegate_to: "{{ storage.host }}"
  when:
    - "storage is defined"
    - "storage.host is defined"

Which either creates a directory on the inventory_host or on a different host, when the fact is defined.

I wonder, if it is possible to reduce the number of tasks here. Normally I would use the omit filter. But because I've several conditions, I'm not sure what kind of syntax to use here for delegate_to.

Upvotes: 1

Views: 379

Answers (1)

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39159

You can also use the omit special variable in an inline expression

- file:
    path: "{{ datapath }}"
    state: directory
  delegate_to: "{{ storage.host if storage.host is defined else omit }}"

With this, and because you can chain inline-if's, then you could have multiple conditions that ends in an omit, e.g.

delegate_to: >-
  {{
    storage.host
      if storage.host is defined
      else 'localhost'
        if for_localhost | default(false)
        else omit
  }}

Would be:

  • delegated to storage.host when defined
  • delegated to localhost when for_localhost is truthy
  • omitted, otherwise

Upvotes: 1

Related Questions