Shurik
Shurik

Reputation: 572

ansible check mandatory parameters via loop

I'm working on create ansible role and as the first task I want to verify that all relevant mandatory parameters defined and not empty.

The number of mandatory parameters is dynamic and changed based on configuration. e.g. if flag is true than it will require additional mandatory parameters.

in order to solve the dynamic parameters, I create the mandatory_parameters.j2 template file that contains all the relevant parameters

required_vars:
  - release_pipeline_bb_url
  - release_mail_to
  - dummy
{% if release_pipeline_credential_enabled %}
  - release_pipeline_credential.private_key
{% endif %}
{% if release_descriptor_credential_enabled %}
  - release_descriptor_credential.UserName
  - release_descriptor_credential.Password
{% endif %}

after it I load this file as vars

- name: Create mandatory validation file
  template:
      dest: "{{ jenkins_casc_folder }}/{{ role_name }}/mandatory.yaml"
      src: mandatory_parameters.j2

- name: Load mandatory parameter file as variable
  include_vars:
      file: "{{ jenkins_casc_folder }}/{{ role_name }}/mandatory.yaml"

I success to check if mandatory parameter define and not empty for "regular" variables, but it's not working for dictionary, like release_descriptor_credential.Password

- name: Validate all mandatory parameters
  fail: msg="The variable '{{ item }}' is not defined or empty"
  when: ( vars[item] is not defined) or ( vars[item] |length == 0)
  loop: "{{ required_vars }}"

How I can validate also for dictionary type?

I tried also via lookup but without success.

Upvotes: 2

Views: 784

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68144

The task below does the job

  - name: Validate all mandatory parameters
    fail:
      msg: "The variable '{{ item }}' is not defined or empty"
    loop: "{{ required_vars }}"
    when: myvar|length == 0
    vars:
      mydict: "{{ item.split('.').0 }}"
      myattr: "{{ item.split('.').1|default('') }}"
      myvar: "{{ (myattr|length > 0)|
                  ternary( lookup('vars', mydict, default='')[myattr]|default(''),
                           lookup('vars', mydict, default='')) }}"

Upvotes: 1

Related Questions