Debian Codegraph @

ansible_collections/community/zabbix/plugins/modules/zabbix_hostmacro.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # (c) 2013-2014, Epic Games, Inc.
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_hostmacro
14 short_description: Create/update/delete Zabbix host macros
15 description:
16 - manages Zabbix host macros, it can create, update or delete them.
17 author:
18 - "Cove (@cove)"
19 - Dean Hailin Song (!UNKNOWN)
20 requirements:
21 - "python >= 3.9"
22 options:
23 host_name:
24 description:
25 - Name of the host.
26 required: true
27 type: str
28 macro_name:
29 description:
30 - Name of the host macro in zabbix native format C({$MACRO}) or simple format C(MACRO).
31 required: true
32 type: str
33 macro_value:
34 description:
35 - Value of the host macro.
36 - Required if I(state=present).
37 type: str
38 macro_type:
39 type: str
40 description:
41 - Type of the host macro.
42 - text (default)
43 required: false
44 choices: ["text", "secret", "vault"]
45 default: "text"
46 macro_description:
47 description:
48 - Text Description of the global macro.
49 type: str
50 default: ""
51 state:
52 description:
53 - State of the macro.
54 - On C(present), it will create if macro does not exist or update the macro if the associated data is different.
55 - On C(absent) will remove a macro if it exists.
56 required: false
57 choices: ["present", "absent"]
58 type: str
59 default: "present"
60 force:
61 description:
62 - Only updates an existing macro if set to C(yes).
63 default: "yes"
64 type: bool
65
66 extends_documentation_fragment:
67 - community.zabbix.zabbix
68
69 """
70
71 EXAMPLES = r"""
72 # If you want to use Username and Password to be authenticated by Zabbix Server
73 - name: Set credentials to access Zabbix Server API
74 ansible.builtin.set_fact:
75 ansible_user: Admin
76 ansible_httpapi_pass: zabbix
77
78 # If you want to use API token to be authenticated by Zabbix Server
79 # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens
80 - name: Set API token
81 ansible.builtin.set_fact:
82 ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895
83
84 - name: Create new host macro or update an existing macro's value
85 # set task level variables as we change ansible_connection plugin here
86 vars:
87 ansible_network_os: community.zabbix.zabbix
88 ansible_connection: httpapi
89 ansible_httpapi_port: 443
90 ansible_httpapi_use_ssl: true
91 ansible_httpapi_validate_certs: false
92 ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
93 ansible_host: zabbix-example-fqdn.org
94 community.zabbix.zabbix_hostmacro:
95 host_name: ExampleHost
96 macro_name: EXAMPLE.MACRO
97 macro_value: Example value
98 macro_description: Example description
99 state: present
100
101 # Values with curly brackets need to be quoted otherwise they will be interpreted as a dictionary
102 - name: Create new host macro in Zabbix native format
103 # set task level variables as we change ansible_connection plugin here
104 vars:
105 ansible_network_os: community.zabbix.zabbix
106 ansible_connection: httpapi
107 ansible_httpapi_port: 443
108 ansible_httpapi_use_ssl: true
109 ansible_httpapi_validate_certs: false
110 ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
111 ansible_host: zabbix-example-fqdn.org
112 community.zabbix.zabbix_hostmacro:
113 host_name: ExampleHost
114 macro_name: "{$EXAMPLE.MACRO}"
115 macro_value: Example value
116 macro_description: Example description
117 state: present
118
119 - name: Delete existing host macro
120 # set task level variables as we change ansible_connection plugin here
121 vars:
122 ansible_network_os: community.zabbix.zabbix
123 ansible_connection: httpapi
124 ansible_httpapi_port: 443
125 ansible_httpapi_use_ssl: true
126 ansible_httpapi_validate_certs: false
127 ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
128 ansible_host: zabbix-example-fqdn.org
129 community.zabbix.zabbix_hostmacro:
130 host_name: ExampleHost
131 macro_name: "{$EXAMPLE.MACRO}"
132 state: absent
133 """
134
135
136 from ansible.module_utils.basic import AnsibleModule
137
138 from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase
139
140 import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils
141
142
143 class HostMacro(ZabbixBase):
144 # get host id by host name
145 def get_host_id(self, host_name):
146 try:
147 host_list = self._zapi.host.get({"output": "extend", "filter": {"host": host_name}})
148 if len(host_list) < 1:
149 self._module.fail_json(msg="Host not found: %s" % host_name)
150 else:
151 host_id = host_list[0]["hostid"]
152 return host_id
153 except Exception as e:
154 self._module.fail_json(msg="Failed to get the host %s id: %s." % (host_name, e))
155
156 # get host macro
157 def get_host_macro(self, macro_name, host_id):
158 try:
159 host_macro_list = self._zapi.usermacro.get(
160 {"output": "extend", "selectSteps": "extend", "hostids": [host_id], "filter": {"macro": macro_name}})
161 if len(host_macro_list) > 0:
162 return host_macro_list[0]
163 return None
164 except Exception as e:
165 self._module.fail_json(msg="Failed to get host macro %s: %s" % (macro_name, e))
166
167 # create host macro
168 def create_host_macro(self, macro_name, macro_value, macro_type, macro_description, host_id):
169 try:
170 if self._module.check_mode:
171 self._module.exit_json(changed=True)
172 self._zapi.usermacro.create({"hostid": host_id, "macro": macro_name, "value": macro_value, "type": macro_type, "description": macro_description})
173 self._module.exit_json(changed=True, result="Successfully added host macro %s" % macro_name)
174 except Exception as e:
175 self._module.fail_json(msg="Failed to create host macro %s: %s" % (macro_name, e))
176
177 # update host macro
178 def update_host_macro(self, host_macro_obj, macro_name, macro_value, macro_type, macro_description):
179 host_macro_id = host_macro_obj["hostmacroid"]
180 if host_macro_obj["macro"] == macro_name:
181 # no change only when macro type == 0. when type = 1 or 2 zabbix will not output value of it.
182 if (host_macro_obj["type"] == "0" and macro_type == "0" and host_macro_obj["value"] == macro_value
183 and host_macro_obj["description"] == macro_description):
184 self._module.exit_json(changed=False, result="Host macro %s already up to date" % macro_name)
185 try:
186 if self._module.check_mode:
187 self._module.exit_json(changed=True)
188 self._zapi.usermacro.update({"hostmacroid": host_macro_id, "value": macro_value, "type": macro_type, "description": macro_description})
189 self._module.exit_json(changed=True, result="Successfully updated host macro %s" % macro_name)
190 except Exception as e:
191 self._module.fail_json(msg="Failed to update host macro %s: %s" % (macro_name, e))
192
193 # delete host macro
194 def delete_host_macro(self, host_macro_obj, macro_name):
195 host_macro_id = host_macro_obj["hostmacroid"]
196 try:
197 if self._module.check_mode:
198 self._module.exit_json(changed=True)
199 self._zapi.usermacro.delete([host_macro_id])
200 self._module.exit_json(changed=True, result="Successfully deleted host macro %s" % macro_name)
201 except Exception as e:
202 self._module.fail_json(msg="Failed to delete host macro %s: %s" % (macro_name, e))
203
204
205 def normalize_macro_name(macro_name):
206 # Zabbix handles macro names in upper case characters
207 if ":" in macro_name:
208 macro_name = ":".join([macro_name.split(":")[0].upper(), ":".join(macro_name.split(":")[1:])])
209 else:
210 macro_name = macro_name.upper()
211
212 # Valid format for macro is {$MACRO}
213 if not macro_name.startswith("{$"):
214 macro_name = "{$" + macro_name
215 if not macro_name.endswith("}"):
216 macro_name = macro_name + "}"
217
218 return macro_name
219
220
221 def main():
222 argument_spec = zabbix_utils.zabbix_common_argument_spec()
223 argument_spec.update(dict(
224 host_name=dict(type="str", required=True),
225 macro_name=dict(type="str", required=True),
226 macro_value=dict(type="str", required=False),
227 macro_type=dict(type="str", default="text", choices=["text", "secret", "vault"]),
228 macro_description=dict(type="str", default=""),
229 state=dict(type="str", default="present", choices=["present", "absent"]),
230 force=dict(type="bool", default=True)
231 ))
232 module = AnsibleModule(
233 argument_spec=argument_spec,
234 required_if=[
235 ["state", "present", ["macro_value"]]
236 ],
237 supports_check_mode=True
238 )
239
240 host_name = module.params["host_name"]
241 macro_name = normalize_macro_name(module.params["macro_name"])
242 macro_value = module.params["macro_value"]
243 macro_description = module.params["macro_description"]
244 state = module.params["state"]
245 force = module.params["force"]
246 if module.params["macro_type"] == "secret":
247 macro_type = "1"
248 elif module.params["macro_type"] == "vault":
249 macro_type = "2"
250 else:
251 macro_type = "0"
252
253 host_macro_class_obj = HostMacro(module)
254
255 if host_name:
256 host_id = host_macro_class_obj.get_host_id(host_name)
257 host_macro_obj = host_macro_class_obj.get_host_macro(macro_name, host_id)
258
259 if state == "absent":
260 if not host_macro_obj:
261 module.exit_json(changed=False, msg="Host Macro %s does not exist" % macro_name)
262 else:
263 # delete a macro
264 host_macro_class_obj.delete_host_macro(host_macro_obj, macro_name)
265 else:
266 if not host_macro_obj:
267 # create host macro
268 host_macro_class_obj.create_host_macro(macro_name, macro_value, macro_type, macro_description, host_id)
269 elif force:
270 # update host macro
271 host_macro_class_obj.update_host_macro(host_macro_obj, macro_name, macro_value, macro_type, macro_description)
272 else:
273 module.exit_json(changed=False, result="Host macro %s already exists and force is set to no" % macro_name)
274
275
276 if __name__ == "__main__":
277 main()