add omit_date option for template dump (#67302)

* added omit_date option for template dump

omit_date=yes removed the date field in the exported template

* Update zabbix_template.py

- ansibot fixes
- better function call handling

* Update zabbix_template_info.py

* Create 67302-zabbix_template_info-add-omit_date-field

* Rename 67302-zabbix_template_info-add-omit_date-field to 67302-zabbix_template_info-add-omit_date-field.yml
pull/67563/head
Markus Fischbacher 5 years ago committed by GitHub
parent cceb517aff
commit 8aec058473
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -0,0 +1,3 @@
minor_changes:
- zabbix_template - add new option omit_date to remove date from exported/dumped template (https://github.com/ansible/ansible/pull/67302)
- zabbix_template_info - add new option omit_date to remove date from exported/dumped template (https://github.com/ansible/ansible/pull/67302)

@ -105,6 +105,14 @@ options:
default: "json" default: "json"
version_added: '2.9' version_added: '2.9'
type: str type: str
omit_date:
description:
- Removes the date field for the exported/dumped template
- Requires C(state=dump)
required: false
type: bool
default: false
version_added: '2.10'
state: state:
description: description:
- Required state of the template. - Required state of the template.
@ -221,6 +229,7 @@ EXAMPLES = r'''
login_user: username login_user: username
login_password: password login_password: password
template_name: Template template_name: Template
omit_date: yes
state: dump state: dump
register: template_dump register: template_dump
@ -232,6 +241,7 @@ EXAMPLES = r'''
login_password: password login_password: password
template_name: Template template_name: Template
dump_format: xml dump_format: xml
omit_date: false
state: dump state: dump
register: template_dump register: template_dump
''' '''
@ -240,7 +250,7 @@ RETURN = r'''
--- ---
template_json: template_json:
description: The JSON dump of the template description: The JSON dump of the template
returned: when state is dump returned: when state is dump and omit_date is no
type: str type: str
sample: { sample: {
"zabbix_export":{ "zabbix_export":{
@ -267,13 +277,12 @@ template_json:
template_xml: template_xml:
description: dump of the template in XML representation description: dump of the template in XML representation
returned: when state is dump and dump_format is xml returned: when state is dump, dump_format is xml and omit_date is yes
type: str type: str
sample: |- sample: |-
<?xml version="1.0" ?> <?xml version="1.0" ?>
<zabbix_export> <zabbix_export>
<version>4.2</version> <version>4.2</version>
<date>2019-07-12T13:37:26Z</date>
<groups> <groups>
<group> <group>
<name>Templates</name> <name>Templates</name>
@ -470,16 +479,22 @@ class Template(object):
else: else:
return obj return obj
def dump_template(self, template_ids, template_type='json'): def dump_template(self, template_ids, template_type='json', omit_date=False):
if self._module.check_mode: if self._module.check_mode:
self._module.exit_json(changed=True) self._module.exit_json(changed=True)
try: try:
dump = self._zapi.configuration.export({'format': template_type, 'options': {'templates': template_ids}}) dump = self._zapi.configuration.export({'format': template_type, 'options': {'templates': template_ids}})
if template_type == 'xml': if template_type == 'xml':
return str(ET.tostring(ET.fromstring(dump.encode('utf-8')), encoding='utf-8').decode('utf-8')) xmlroot = ET.fromstring(dump.encode('utf-8'))
# remove date field if requested
if omit_date:
date = xmlroot.find(".date")
if date is not None:
xmlroot.remove(date)
return str(ET.tostring(xmlroot, encoding='utf-8').decode('utf-8'))
else: else:
return self.load_json_template(dump) return self.load_json_template(dump, omit_date=omit_date)
except ZabbixAPIException as e: except ZabbixAPIException as e:
self._module.fail_json(msg='Unable to export template: %s' % e) self._module.fail_json(msg='Unable to export template: %s' % e)
@ -536,9 +551,12 @@ class Template(object):
xml_root_text = list(line.strip() for line in ET.tostring(parsed_xml_root, encoding='utf8', method='xml').decode().split('\n')) xml_root_text = list(line.strip() for line in ET.tostring(parsed_xml_root, encoding='utf8', method='xml').decode().split('\n'))
return ''.join(xml_root_text) return ''.join(xml_root_text)
def load_json_template(self, template_json): def load_json_template(self, template_json, omit_date=False):
try: try:
return json.loads(template_json) jsondoc = json.loads(template_json)
if omit_date and 'date' in jsondoc['zabbix_export']:
del jsondoc['zabbix_export']['date']
return jsondoc
except ValueError as e: except ValueError as e:
self._module.fail_json(msg='Invalid JSON provided', details=to_native(e), exception=traceback.format_exc()) self._module.fail_json(msg='Invalid JSON provided', details=to_native(e), exception=traceback.format_exc())
@ -639,6 +657,7 @@ def main():
link_templates=dict(type='list', required=False), link_templates=dict(type='list', required=False),
clear_templates=dict(type='list', required=False), clear_templates=dict(type='list', required=False),
macros=dict(type='list', required=False), macros=dict(type='list', required=False),
omit_date=dict(type='bool', required=False, default=False),
dump_format=dict(type='str', required=False, default='json', choices=['json', 'xml']), dump_format=dict(type='str', required=False, default='json', choices=['json', 'xml']),
state=dict(type='str', default="present", choices=['present', 'absent', 'dump']), state=dict(type='str', default="present", choices=['present', 'absent', 'dump']),
timeout=dict(type='int', default=10) timeout=dict(type='int', default=10)
@ -672,6 +691,7 @@ def main():
link_templates = module.params['link_templates'] link_templates = module.params['link_templates']
clear_templates = module.params['clear_templates'] clear_templates = module.params['clear_templates']
template_macros = module.params['macros'] template_macros = module.params['macros']
omit_date = module.params['omit_date']
dump_format = module.params['dump_format'] dump_format = module.params['dump_format']
state = module.params['state'] state = module.params['state']
timeout = module.params['timeout'] timeout = module.params['timeout']
@ -720,9 +740,9 @@ def main():
module.fail_json(msg='Template not found: %s' % template_name) module.fail_json(msg='Template not found: %s' % template_name)
if dump_format == 'json': if dump_format == 'json':
module.exit_json(changed=False, template_json=template.dump_template(template_ids, template_type='json')) module.exit_json(changed=False, template_json=template.dump_template(template_ids, template_type='json', omit_date=omit_date))
elif dump_format == 'xml': elif dump_format == 'xml':
module.exit_json(changed=False, template_xml=template.dump_template(template_ids, template_type='xml')) module.exit_json(changed=False, template_xml=template.dump_template(template_ids, template_type='xml', omit_date=omit_date))
elif state == "present": elif state == "present":
# Load all subelements for template that were provided by user # Load all subelements for template that were provided by user

@ -34,6 +34,12 @@ options:
choices: ['json', 'xml'] choices: ['json', 'xml']
default: json default: json
type: str type: str
omit_date:
description:
- Removes the date field for the dumped template
required: false
type: bool
default: false
extends_documentation_fragment: extends_documentation_fragment:
- zabbix - zabbix
''' '''
@ -46,6 +52,7 @@ EXAMPLES = '''
login_password: secret login_password: secret
template_name: Template template_name: Template
format: json format: json
omit_date: yes
register: template_json register: template_json
- name: Get Zabbix template as XML - name: Get Zabbix template as XML
@ -55,6 +62,7 @@ EXAMPLES = '''
login_password: secret login_password: secret
template_name: Template template_name: Template
format: xml format: xml
omit_date: no
register: template_json register: template_json
''' '''
@ -62,12 +70,11 @@ RETURN = '''
--- ---
template_json: template_json:
description: The JSON of the template description: The JSON of the template
returned: when format is json returned: when format is json and omit_date is true
type: str type: str
sample: { sample: {
"zabbix_export": { "zabbix_export": {
"version": "4.0", "version": "4.0",
"date": "2019-10-27T14:17:24Z",
"groups": [ "groups": [
{ {
"name": "Templates" "name": "Templates"
@ -101,7 +108,7 @@ template_json:
template_xml: template_xml:
description: The XML of the template description: The XML of the template
returned: when format is xml returned: when format is xml and omit_date is false
type: str type: str
sample: >- sample: >-
<zabbix_export> <zabbix_export>
@ -181,19 +188,29 @@ class TemplateInfo(object):
return template_id return template_id
def load_json_template(self, template_json): def load_json_template(self, template_json, omit_date=False):
try: try:
return json.loads(template_json) jsondoc = json.loads(template_json)
# remove date field if requested
if omit_date and 'date' in jsondoc['zabbix_export']:
del jsondoc['zabbix_export']['date']
return jsondoc
except ValueError as e: except ValueError as e:
self._module.fail_json(msg='Invalid JSON provided', details=to_native(e), exception=traceback.format_exc()) self._module.fail_json(msg='Invalid JSON provided', details=to_native(e), exception=traceback.format_exc())
def dump_template(self, template_id, template_type='json'): def dump_template(self, template_id, template_type='json', omit_date=False):
try: try:
dump = self._zapi.configuration.export({'format': template_type, 'options': {'templates': template_id}}) dump = self._zapi.configuration.export({'format': template_type, 'options': {'templates': template_id}})
if template_type == 'xml': if template_type == 'xml':
return str(ET.tostring(ET.fromstring(dump.encode('utf-8')), encoding='utf-8').decode('utf-8')) xmlroot = ET.fromstring(dump.encode('utf-8'))
# remove date field if requested
if omit_date:
date = xmlroot.find(".date")
if date is not None:
xmlroot.remove(date)
return str(ET.tostring(xmlroot, encoding='utf-8').decode('utf-8'))
else: else:
return self.load_json_template(dump) return self.load_json_template(dump, omit_date)
except ZabbixAPIException as e: except ZabbixAPIException as e:
self._module.fail_json(msg='Unable to export template: %s' % e) self._module.fail_json(msg='Unable to export template: %s' % e)
@ -210,6 +227,7 @@ def main():
validate_certs=dict(type='bool', required=False, default=True), validate_certs=dict(type='bool', required=False, default=True),
timeout=dict(type='int', default=10), timeout=dict(type='int', default=10),
template_name=dict(type='str', required=True), template_name=dict(type='str', required=True),
omit_date=dict(type='bool', required=False, default=False),
format=dict(type='str', choices=['json', 'xml'], default='json') format=dict(type='str', choices=['json', 'xml'], default='json')
), ),
supports_check_mode=False supports_check_mode=False
@ -227,6 +245,7 @@ def main():
validate_certs = module.params['validate_certs'] validate_certs = module.params['validate_certs']
timeout = module.params['timeout'] timeout = module.params['timeout']
template_name = module.params['template_name'] template_name = module.params['template_name']
omit_date = module.params['omit_date']
format = module.params['format'] format = module.params['format']
try: try:
@ -245,9 +264,9 @@ def main():
module.fail_json(msg='Template not found: %s' % template_name) module.fail_json(msg='Template not found: %s' % template_name)
if format == 'json': if format == 'json':
module.exit_json(changed=False, template_json=template_info.dump_template(template_id, template_type='json')) module.exit_json(changed=False, template_json=template_info.dump_template(template_id, template_type='json', omit_date=omit_date))
elif format == 'xml': elif format == 'xml':
module.exit_json(changed=False, template_xml=template_info.dump_template(template_id, template_type='xml')) module.exit_json(changed=False, template_xml=template_info.dump_template(template_id, template_type='xml', omit_date=omit_date))
if __name__ == "__main__": if __name__ == "__main__":

Loading…
Cancel
Save