Search code examples
ansiblejinja2openstack

Setting up correctly gateway_ip in Ansible function


I am using the following function to deploy an Openstack subnet using Ansible and variable file:

- name: Create the subnets 
  os_subnet: 
     cloud: "{{ item.cloud }}" 
     state: present
     validate_certs: no
     gateway_ip: "{{ item.gateway_ip | default(None) }}"
     dns_nameservers: "{{ item.dns if item.dns is defined else omit }}"
     enable_dhcp: yes
     name: "{{ item.subnet }}"
     network_name: "{{ item.network }}"
     cidr: "{{ item.cidr }}"
     allocation_pool_start: "{{ item.allocation_pool_start }}"
     allocation_pool_end: "{{ item.allocation_pool_end }}"
     host_routes: "{{ item.host_routes | default(omit) }}" 
  with_items: 
  - "{{ subnets }}"
  tags: subnets

In my environment, I will have some subnets that will have gateway configured, some not. I would like to create a workaround to make it possible configuring gateway ip for some servers and for some of them not.

I have tried yet to configure it like this, but it will assign also for the ones that do not have the gateway_ip configured in the variable file a gateway. I have tried also the no_gateway_ip option, but for this one I didn't find the proper filter to get a gateway_ip when it is defined in the variable file.

Any way to trick this?


Solution

  • Found the way: no_gateway_ip should be involved, not gateway_ip.

    - name: Create the subnets 
      os_subnet: 
         cloud: "{{ item.cloud }}" 
         state: present
         validate_certs: no
         no_gateway_ip: "{{ not (item.gateway_ip is defined) }}"
         dns_nameservers: "{{ item.dns if item.dns is defined else omit }}"
         enable_dhcp: yes
         name: "{{ item.subnet }}"
         network_name: "{{ item.network }}"
         cidr: "{{ item.cidr }}"
         allocation_pool_start: "{{ item.allocation_pool_start }}"
         allocation_pool_end: "{{ item.allocation_pool_end }}"
         host_routes: "{{ item.host_routes | default(omit) }}" 
      with_items: 
      - "{{ subnets }}"
      tags: subnets