I have a custom ansible module.
10 def main():
11 module = AnsibleModule(
12 argument_spec = dict(
13 server = dict(required=True, type='str'),
14 max_offset = dict(required=False, default=0.100, type='float')
15 ),
16 supports_check_mode = False
17 )
18
19 # Write params into normal variables
20 max_offset = module.params['max_offset']
21 server = module.params.get('server')
I want to call it with additional parameter only if a variable ntp.max_offset
is defined.
I dont know how to do this.
So I tried this code:
- name: GROUP::TEST
ntptest: server="{{ hostvars[item][eth]['ipv4']['address'] }}"
parameter:
name: "max_offset"
value: ntp.max_offset
when: ntp.max_offset is defined
register: modules_output
with_items: "{{groups['ntp_servers']}}"
when: server is not defined
But unfortunately.
Ansible treats values of the extra variables as strings. To pass values that are not strings, we need to use JSON format. To pass extra vars in JSON format we need to enclose JSON in quotation marks: ansible-playbook extra_var_json.
As per latest Ansible Version 2.5, to check if a variable is defined and depending upon this if you want to run any task, use undefined keyword. Save this answer. Show activity on this post. Strictly stated you must check all of the following: defined, not empty AND not None.
Assigning a value to a variable in a playbook is quite easy and straightforward. Begin by calling the vars keyword then call the variable name followed by the value as shown. In the playbook above, the variable name is salutations and the value is Hello world!
You can use default(omit)
(see "Making variables optional") eg:
- name: GROUP::TEST
ntptest:
server: "{{ hostvars[item][eth]['ipv4']['address'] }}"
max_offset: "{{ ntp.max_offset | default(omit) }}"
This causes the value not to be sent to the module when the variable is undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With