| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# (c) 2019, Ruben Tsirunyan <[email protected]> |
| 5 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
|
| 7 |
from __future__ import absolute_import, division, print_function |
| 8 |
__metaclass__ = type |
| 9 |
|
| 10 |
|
| 11 |
DOCUMENTATION = r""" |
| 12 |
--- |
| 13 |
module: zabbix_valuemap |
| 14 |
short_description: Create/update/delete Zabbix value maps |
| 15 |
description: |
| 16 |
- This module allows you to create, modify and delete Zabbix value maps. |
| 17 |
author: |
| 18 |
- "Ruben Tsirunyan (@rubentsirunyan)" |
| 19 |
requirements: |
| 20 |
- "python >= 3.9" |
| 21 |
options: |
| 22 |
host_name: |
| 23 |
type: "str" |
| 24 |
description: |
| 25 |
- Name of host to add value map to. |
| 26 |
required: true |
| 27 |
name: |
| 28 |
type: "str" |
| 29 |
description: |
| 30 |
- Name of the value map. |
| 31 |
required: true |
| 32 |
state: |
| 33 |
type: "str" |
| 34 |
description: |
| 35 |
- State of the value map. |
| 36 |
- On C(present), it will create a value map if it does not exist or update the value map if the associated data is different. |
| 37 |
- On C(absent), it will remove the value map if it exists. |
| 38 |
choices: ["present", "absent"] |
| 39 |
default: "present" |
| 40 |
mappings: |
| 41 |
type: "list" |
| 42 |
elements: dict |
| 43 |
description: |
| 44 |
- List of value mappings for the value map. |
| 45 |
- Required when I(state=present). |
| 46 |
suboptions: |
| 47 |
value: |
| 48 |
type: "str" |
| 49 |
description: Original value. |
| 50 |
required: true |
| 51 |
map_to: |
| 52 |
type: "str" |
| 53 |
description: Value to which the original value is mapped to. |
| 54 |
required: true |
| 55 |
type: |
| 56 |
type: "int" |
| 57 |
description: Mapping match type. |
| 58 |
default: 0 |
| 59 |
required: false |
| 60 |
|
| 61 |
extends_documentation_fragment: |
| 62 |
- community.zabbix.zabbix |
| 63 |
|
| 64 |
""" |
| 65 |
|
| 66 |
RETURN = r""" |
| 67 |
""" |
| 68 |
|
| 69 |
EXAMPLES = r""" |
| 70 |
# If you want to use Username and Password to be authenticated by Zabbix Server |
| 71 |
- name: Set credentials to access Zabbix Server API |
| 72 |
ansible.builtin.set_fact: |
| 73 |
ansible_user: Admin |
| 74 |
ansible_httpapi_pass: zabbix |
| 75 |
|
| 76 |
# If you want to use API token to be authenticated by Zabbix Server |
| 77 |
# https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens |
| 78 |
- name: Set API token |
| 79 |
ansible.builtin.set_fact: |
| 80 |
ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895 |
| 81 |
|
| 82 |
- name: Create a value map |
| 83 |
# set task level variables as we change ansible_connection plugin here |
| 84 |
vars: |
| 85 |
ansible_network_os: community.zabbix.zabbix |
| 86 |
ansible_connection: httpapi |
| 87 |
ansible_httpapi_port: 443 |
| 88 |
ansible_httpapi_use_ssl: true |
| 89 |
ansible_httpapi_validate_certs: false |
| 90 |
ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu |
| 91 |
ansible_host: zabbix-example-fqdn.org |
| 92 |
community.zabbix.zabbix_valuemap: |
| 93 |
host_name: example_host |
| 94 |
name: Numbers |
| 95 |
mappings: |
| 96 |
- value: 1 |
| 97 |
map_to: one |
| 98 |
- value: 2 |
| 99 |
map_to: two |
| 100 |
type: 0 |
| 101 |
state: present |
| 102 |
""" |
| 103 |
|
| 104 |
from ansible.module_utils.basic import AnsibleModule |
| 105 |
|
| 106 |
from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase |
| 107 |
import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils |
| 108 |
|
| 109 |
|
| 110 |
def construct_parameters(**kwargs): |
| 111 |
"""Translates data to a format suitable for Zabbix API |
| 112 |
|
| 113 |
Args: |
| 114 |
**kwargs: Arguments passed to the module. |
| 115 |
|
| 116 |
Returns: |
| 117 |
A dictionary of arguments in a format that is understandable by Zabbix API. |
| 118 |
""" |
| 119 |
if kwargs["mappings"] is None: |
| 120 |
return dict( |
| 121 |
hostid=kwargs["hostid"], |
| 122 |
name=kwargs["name"] |
| 123 |
) |
| 124 |
|
| 125 |
return dict( |
| 126 |
hostid=kwargs["hostid"], |
| 127 |
name=kwargs["name"], |
| 128 |
mappings=[ |
| 129 |
dict( |
| 130 |
value=mapping["value"], |
| 131 |
newvalue=mapping["map_to"], |
| 132 |
type=str(mapping["type"]) |
| 133 |
) for mapping in kwargs["mappings"] |
| 134 |
] |
| 135 |
) |
| 136 |
|
| 137 |
|
| 138 |
def diff(existing, new): |
| 139 |
"""Constructs the diff for Ansible"s --diff option. |
| 140 |
|
| 141 |
Args: |
| 142 |
existing (dict): Existing valuemap data. |
| 143 |
new (dict): New valuemap data. |
| 144 |
|
| 145 |
Returns: |
| 146 |
A dictionary like {"before": existing, "after": new} |
| 147 |
with filtered empty values. |
| 148 |
""" |
| 149 |
before = {} |
| 150 |
after = {} |
| 151 |
for key in new: |
| 152 |
before[key] = existing[key] |
| 153 |
if new[key] is None: |
| 154 |
after[key] = "" |
| 155 |
else: |
| 156 |
after[key] = new[key] |
| 157 |
|
| 158 |
return {"before": before, "after": after} |
| 159 |
|
| 160 |
|
| 161 |
def get_update_params(existing_valuemap, **kwargs): |
| 162 |
"""Filters only the parameters that are different and need to be updated. |
| 163 |
|
| 164 |
Args: |
| 165 |
existing_valuemap (dict): Existing valuemap. |
| 166 |
**kwargs: Parameters for the new valuemap. |
| 167 |
|
| 168 |
Returns: |
| 169 |
A tuple where the first element is a dictionary of parameters |
| 170 |
that need to be updated and the second one is a dictionary |
| 171 |
returned by diff() function with |
| 172 |
existing valuemap data and new params passed to it. |
| 173 |
""" |
| 174 |
|
| 175 |
params_to_update = {} |
| 176 |
if sorted(existing_valuemap["mappings"], key=lambda k: k["value"]) != sorted(kwargs["mappings"], key=lambda k: k["value"]): |
| 177 |
params_to_update["mappings"] = kwargs["mappings"] |
| 178 |
return params_to_update, diff(existing_valuemap, kwargs) |
| 179 |
|
| 180 |
|
| 181 |
class ValuemapModule(ZabbixBase): |
| 182 |
def get_host_id(self, host_name): |
| 183 |
host_list = self._zapi.host.get({"filter": {"host": host_name}}) |
| 184 |
if len(host_list) < 1: |
| 185 |
self._module.fail_json(msg="Host not found: %s" % host_name) |
| 186 |
else: |
| 187 |
return host_list[0]["hostid"] |
| 188 |
|
| 189 |
def check_if_valuemap_exists(self, hostid, name): |
| 190 |
"""Checks if value map exists. |
| 191 |
|
| 192 |
Args: |
| 193 |
name: Zabbix valuemap name |
| 194 |
|
| 195 |
Returns: |
| 196 |
tuple: First element is True if valuemap exists and False otherwise. |
| 197 |
Second element is a dictionary of valuemap object if it exists. |
| 198 |
""" |
| 199 |
try: |
| 200 |
valuemap_list = self._zapi.valuemap.get({ |
| 201 |
"output": "extend", |
| 202 |
"selectMappings": "extend", |
| 203 |
"filter": {"hostid": [hostid], "name": [name]} |
| 204 |
}) |
| 205 |
if len(valuemap_list) > 0: |
| 206 |
valuemap_list = [valuemap for valuemap in valuemap_list if valuemap["uuid"] == ""] |
| 207 |
if len(valuemap_list) < 1: |
| 208 |
return False, None |
| 209 |
else: |
| 210 |
return True, valuemap_list[0] |
| 211 |
except Exception as e: |
| 212 |
self._module.fail_json(msg="Failed to get ID of the valuemap '{name}': {e}".format(name=name, e=e)) |
| 213 |
|
| 214 |
def delete(self, valuemap_id): |
| 215 |
try: |
| 216 |
return self._zapi.valuemap.delete([valuemap_id]) |
| 217 |
except Exception as e: |
| 218 |
self._module.fail_json(msg="Failed to delete valuemap '{_id}': {e}".format(_id=valuemap_id, e=e)) |
| 219 |
|
| 220 |
def update(self, **kwargs): |
| 221 |
try: |
| 222 |
self._zapi.valuemap.update(kwargs) |
| 223 |
except Exception as e: |
| 224 |
self._module.fail_json(msg="Failed to update valuemap '{_id}': {e}".format(_id=kwargs["valuemapid"], e=e)) |
| 225 |
|
| 226 |
def create(self, **kwargs): |
| 227 |
try: |
| 228 |
self._zapi.valuemap.create(kwargs) |
| 229 |
except Exception as e: |
| 230 |
self._module.fail_json(msg="Failed to create valuemap '{name}': {e}".format(name=kwargs["description"], e=e)) |
| 231 |
|
| 232 |
|
| 233 |
def main(): |
| 234 |
argument_spec = zabbix_utils.zabbix_common_argument_spec() |
| 235 |
argument_spec.update(dict( |
| 236 |
host_name=dict(type="str", required=True), |
| 237 |
name=dict(type="str", required=True), |
| 238 |
state=dict(type="str", default="present", choices=["present", "absent"]), |
| 239 |
mappings=dict( |
| 240 |
type="list", |
| 241 |
elements="dict", |
| 242 |
options=dict( |
| 243 |
value=dict(type="str", required=True), |
| 244 |
map_to=dict(type="str", required=True), |
| 245 |
type=dict(type="int", required=False, default=0) |
| 246 |
) |
| 247 |
) |
| 248 |
)) |
| 249 |
module = AnsibleModule( |
| 250 |
argument_spec=argument_spec, |
| 251 |
supports_check_mode=True, |
| 252 |
required_if=[ |
| 253 |
["state", "present", ["mappings"]], |
| 254 |
] |
| 255 |
) |
| 256 |
|
| 257 |
vm = ValuemapModule(module) |
| 258 |
|
| 259 |
host_name = module.params["host_name"] |
| 260 |
hostid = vm.get_host_id(host_name) |
| 261 |
name = module.params["name"] |
| 262 |
state = module.params["state"] |
| 263 |
mappings = module.params["mappings"] |
| 264 |
|
| 265 |
valuemap_exists, valuemap_object = vm.check_if_valuemap_exists(hostid, name) |
| 266 |
|
| 267 |
parameters = construct_parameters( |
| 268 |
hostid=hostid, |
| 269 |
name=name, |
| 270 |
mappings=mappings |
| 271 |
) |
| 272 |
|
| 273 |
if valuemap_exists: |
| 274 |
valuemap_id = valuemap_object["valuemapid"] |
| 275 |
if state == "absent": |
| 276 |
if module.check_mode: |
| 277 |
module.exit_json( |
| 278 |
changed=True, |
| 279 |
msg="Value map would have been deleted. Host name: {host_name}, Name: {name}, ID: {_id}".format( |
| 280 |
host_name=host_name, |
| 281 |
name=name, |
| 282 |
_id=valuemap_id |
| 283 |
) |
| 284 |
) |
| 285 |
valuemap_id = vm.delete(valuemap_id) |
| 286 |
module.exit_json( |
| 287 |
changed=True, |
| 288 |
msg="Value map deleted. Host name: {host_name}, Name: {name}, ID: {_id}".format( |
| 289 |
host_name=host_name, |
| 290 |
name=name, |
| 291 |
_id=valuemap_id |
| 292 |
) |
| 293 |
) |
| 294 |
else: |
| 295 |
params_to_update, diff = get_update_params(valuemap_object, **parameters) |
| 296 |
if params_to_update == {}: |
| 297 |
module.exit_json( |
| 298 |
changed=False, |
| 299 |
msg="Value map is up to date: Host name: {host_name}, Name: {name}".format( |
| 300 |
host_name=host_name, |
| 301 |
name=name |
| 302 |
) |
| 303 |
) |
| 304 |
else: |
| 305 |
if module.check_mode: |
| 306 |
module.exit_json( |
| 307 |
changed=True, |
| 308 |
diff=diff, |
| 309 |
msg="Value map would have been updated. Host name: {host_name}, Name: {name}, ID: {_id}".format( |
| 310 |
host_name=host_name, |
| 311 |
name=name, |
| 312 |
_id=valuemap_id |
| 313 |
) |
| 314 |
) |
| 315 |
valuemap_id = vm.update(valuemapid=valuemap_id, **params_to_update) |
| 316 |
module.exit_json( |
| 317 |
changed=True, |
| 318 |
diff=diff, |
| 319 |
msg="Value map updated. Host name: {host_name}, Name: {name}, ID: {_id}".format( |
| 320 |
host_name=host_name, |
| 321 |
name=name, |
| 322 |
_id=valuemap_id |
| 323 |
) |
| 324 |
) |
| 325 |
else: |
| 326 |
if state == "absent": |
| 327 |
module.exit_json(changed=False) |
| 328 |
else: |
| 329 |
if module.check_mode: |
| 330 |
module.exit_json( |
| 331 |
changed=True, |
| 332 |
msg="Value map would have been created. Host name: {host_name}, Name: {name}, ID: {_id}".format( |
| 333 |
host_name=host_name, |
| 334 |
name=name, |
| 335 |
_id=valuemap_id |
| 336 |
) |
| 337 |
) |
| 338 |
valuemap_id = vm.create(**parameters) |
| 339 |
module.exit_json( |
| 340 |
changed=True, |
| 341 |
msg="Value map created: Host name: {host_name}, Name: {name}, ID: {_id}".format( |
| 342 |
host_name=host_name, |
| 343 |
name=name, |
| 344 |
_id=valuemap_id |
| 345 |
) |
| 346 |
) |
| 347 |
|
| 348 |
|
| 349 |
if __name__ == "__main__": |
| 350 |
main() |