Ansible task with switching variables

Viewed 59

I'm trying to create ansible playbook that will use variables if they are defined without using "while:" and manually typing the undefined variables & duplicating tasks.

For example I have the below variables:

vars:
    service_List:
      - 1:
          state: present
          address_type: ipv4
          ip: 10.0.0.0
      - 2:
          state: present
          jump: true
          ip: 10.5.5.0
          hold_true: yes
      - 3:
          state: present
          address_type: ipv4
          is_enabled: true
          dhcp: none

I want to have a single task that will use the above variables on a specific module.

example of a task: (notice the with_dict)

tasks:
- name: task name here
  some_module:
    **This here will include the code for adding the variables form vars**
    **So for example, for 1st dict it will include state, address_type and ip**
    **for 2nd dict it will include variables state,jump,ip,hold_true** 
    **example: state: "{{ item.value.state }}" 
  with_dict: "{{ service_List }}"

Please help with missing code inside the task

1 Answers

It depends on the some_module use case. In particular, whether the parameters are required or not. And, if required, whether there is a default value or not. There are three options if a parameter is missing in the dictionary

  1. The parameter is not required. Use default(omit)
  2. The parameter is required. Use default(defaul_value_of_this_param)
  3. The parameter is required but there is no default. The module will crash.

For example,

tasks:
  - name: task name here
    some_module:
      state: "{{ item.value.state }}" 
      address_type: "{{ item.value.address_type|default('ipv4') }}"
      ip: "{{ item.value.ip|default(omit) }}"
      jump: "{{ item.value.jump|default(False) }}"
      hold_true: "{{ item.value.hold_true|default(omit) }}"
    with_dict: "{{ service_List }}"

In addition to this, you can use Module defaults.

Related