Debian Codegraph @

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