Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import absolute_import, division, print_function
7
8 __metaclass__ = type
9
10
11 DOCUMENTATION = r"""
12 ---
13 module: zabbix_templategroup
14 short_description: Create/delete Zabbix template groups
15 description:
16 - Create template groups if they do not exist.
17 - Delete existing template groups if they exist.
18 author:
19 - "Cove (@cove)"
20 - "Tony Minfei Ding (!UNKNOWN)"
21 - "Harrison Gu (@harrisongu)"
22 requirements:
23 - "python >= 2.6"
24 options:
25 state:
26 description:
27 - Create or delete template group.
28 required: false
29 type: str
30 default: "present"
31 choices: [ "present", "absent" ]
32 template_groups:
33 description:
34 - List of template groups to create or delete.
35 required: true
36 type: list
37 elements: str
38 aliases: [ "template_group" ]
39 propagate:
40 description:
41 - List of settings will be propagated.
42 - This module propagates permissions after creating missing template groups.
43 - This parameter is for Zabbix >= 7.0.
44 type: dict
45 suboptions:
46 permissions:
47 description:
48 - If set C(true), permissions will be propagated.
49 type: bool
50 default: false
51 extends_documentation_fragment:
52 - community.zabbix.zabbix
53
54 notes:
55 - Too many concurrent updates to the same group may cause Zabbix to return errors, see examples for a workaround if needed.
56 """
57
58 EXAMPLES = r"""
59 # If you want to use Username and Password to be authenticated by Zabbix Server
60 - name: Set credentials to access Zabbix Server API
61 ansible.builtin.set_fact:
62 ansible_user: Admin
63 ansible_httpapi_pass: zabbix
64
65 # If you want to use API token to be authenticated by Zabbix Server
66 # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens
67 - name: Set API token
68 ansible.builtin.set_fact:
69 ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895
70
71 # Base create template groups example
72 - name: Create template groups
73 # set task level variables as we change ansible_connection plugin here
74 vars:
75 ansible_network_os: community.zabbix.zabbix
76 ansible_connection: httpapi
77 ansible_httpapi_port: 443
78 ansible_httpapi_use_ssl: true
79 ansible_httpapi_validate_certs: false
80 ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
81 ansible_host: zabbix-example-fqdn.org
82 community.zabbix.zabbix_templategroup:
83 state: present
84 template_groups:
85 - Example group1
86 - Example group2
87
88 # Limit the Zabbix group creations to one template since Zabbix can return an error when doing concurrent updates
89 - name: Create template groups
90 # set task level variables as we change ansible_connection plugin here
91 vars:
92 ansible_network_os: community.zabbix.zabbix
93 ansible_connection: httpapi
94 ansible_httpapi_port: 443
95 ansible_httpapi_use_ssl: true
96 ansible_httpapi_validate_certs: false
97 ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
98 ansible_host: zabbix-example-fqdn.org
99 community.zabbix.zabbix_templategroup:
100 state: present
101 template_groups:
102 - Example group1
103 - Example group2
104 when: inventory_hostname==groups['group_name'][0]
105
106 - name: Propagate permissions to sub template group
107 vars:
108 ansible_network_os: community.zabbix.zabbix
109 ansible_connection: httpapi
110 ansible_httpapi_port: 443
111 ansible_httpapi_use_ssl: true
112 ansible_httpapi_validate_certs: false
113 ansible_zabbix_url_path: 'zabbixeu'
114 ansible_host: zabbix-example-fqdn.org
115 community.zabbix.zabbix_templategroup:
116 state: present
117 template_groups:
118 - Example group1
119 propagate:
120 permissions: true
121 """
122
123
124 from ansible.module_utils.basic import AnsibleModule
125
126 from ansible.module_utils.compat.version import LooseVersion
127
128 from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase
129 import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils
130
131
132 class TemplateGroup(ZabbixBase):
133 # create template group(s) if not exists
134 def create_template_group(self, group_names):
135 try:
136 group_add_list = []
137 for group_name in group_names:
138 result = self._zapi.templategroup.get({"filter": {"name": group_name}})
139 if not result:
140 if self._module.check_mode:
141 self._module.exit_json(changed=True)
142 self._zapi.templategroup.create({"name": group_name})
143 group_add_list.append(group_name)
144 return group_add_list
145 except Exception as e:
146 self._module.fail_json(msg="Failed to create template group(s): %s" % e)
147
148 # delete template group(s)
149 def delete_template_group(self, group_ids):
150 try:
151 if self._module.check_mode:
152 self._module.exit_json(changed=True)
153 self._zapi.templategroup.delete(group_ids)
154 except Exception as e:
155 self._module.fail_json(
156 msg="Failed to delete template group(s), Exception: %s" % e
157 )
158
159 # get group ids by name
160 def get_group_ids(self, template_groups):
161 group_ids = []
162
163 group_list = self._zapi.templategroup.get(
164 {"output": "extend", "filter": {"name": template_groups}}
165 )
166 for group in group_list:
167 group_id = group["groupid"]
168 group_ids.append(group_id)
169 return group_ids, group_list
170
171 def propagate(self, template_groups, propagate):
172 if LooseVersion(self._zbx_api_version) < LooseVersion("7.0"):
173 return False
174 group_ids, group_list = self.get_group_ids(template_groups)
175 groups = list(map(lambda group_id: {"groupid": group_id}, group_ids))
176 if self._module.check_mode:
177 self._module.exit_json(changed=True)
178 try:
179 self._zapi.templategroup.propagate(
180 {"groups": groups, "permissions": propagate["permissions"]}
181 )
182 except Exception as e:
183 self._module.fail_json(msg="Failed to propagate: %s" % e)
184 return True
185
186
187 def main():
188 argument_spec = zabbix_utils.zabbix_common_argument_spec()
189 argument_spec.update(
190 dict(
191 template_groups=dict(
192 type="list", required=True, aliases=["template_group"], elements="str"
193 ),
194 propagate=dict(
195 type="dict", options=dict(permissions=dict(type="bool", default=False))
196 ),
197 state=dict(type="str", default="present", choices=["present", "absent"]),
198 )
199 )
200 module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
201
202 template_groups = module.params["template_groups"]
203 propagate = module.params["propagate"]
204 state = module.params["state"]
205
206 templateGroup = TemplateGroup(module)
207
208 group_ids = []
209 group_list = []
210 if template_groups:
211 group_ids, group_list = templateGroup.get_group_ids(template_groups)
212
213 if state == "absent":
214 # delete template groups
215 if group_ids:
216 delete_group_names = []
217 templateGroup.delete_template_group(group_ids)
218 for group in group_list:
219 delete_group_names.append(group["name"])
220 module.exit_json(
221 changed=True,
222 result="Successfully deleted template group(s): %s."
223 % ",".join(delete_group_names),
224 )
225 else:
226 module.exit_json(changed=False, result="No template group(s) to delete.")
227 else:
228 # create template groups
229 group_add_list = templateGroup.create_template_group(template_groups)
230 propagated = False
231 if propagate is not None:
232 propagated = templateGroup.propagate(template_groups, propagate)
233
234 if len(group_add_list) > 0:
235 if propagated:
236 module.exit_json(
237 changed=True,
238 result="Successfully created template group(s) and propagated config(s) to sub template group(s)",
239 )
240 else:
241 module.exit_json(
242 changed=True,
243 result="Successfully created template group(s): %s"
244 % group_add_list,
245 )
246 else:
247 if propagated:
248 module.exit_json(
249 changed=True,
250 result="Successfully propagated config(s) to sub template group(s)",
251 )
252 else:
253 module.exit_json(changed=False)
254
255
256 if __name__ == "__main__":
257 main()