NarūnasK
NarūnasK

Reputation: 4950

Forced to create file beforehand ansible conditional include

# "Run application specific configuration scripts"
- include: "app_cfg/{{ app_name }}.yml"
  when: "{{ app_conf[app_name].app_cfg }}"
  ignore_errors: no
  tags:
    - conf

I thought that I will be able conditionally include application specific playbooks simply by setting one variable to the true/false value like so:

app_conf:
  my_app_1:
    app_cfg: no
  my_app_2:
    app_cfg: yes

Unfortunately Ansible is forcing me to create file beforehand:

ERROR: file could not read: <...>/tasks/app_cfg/app_config.yml

Is there a way I can avoid creating a bunch of empty files?

# ansible --version
ansible 1.9.2

Upvotes: 0

Views: 197

Answers (1)

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68289

include with when is not conditional in common sense.
It actually includes every task inside include-file and append given when statement to every task included task.
So it expects include-file to exist.

You can try to handle this using with_first_found and skip: true.
Something like this:

# warning, code not tested
- include: "app_cfg/{{ app_name }}.yml"
  with_first_found:
    - files:
        - "{{ app_conf[app_name].app_cfg | ternary('app_cfg/'+app_name+'.yml', 'unexisting.file') }}"
      skip: true
  tags: conf

It supposed to supply valid config name if app_cfg is true and unexisting.file (which will be skipped) otherwise.

See this answer about skip option.

Upvotes: 2

Related Questions