Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/appliance_networking_firewall_inbound.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 # Copyright: (c) 2021, Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # template: header.j2
6 # This module is autogenerated using the ansible.content_builder.
7 # See: https://github.com/ansible-community/ansible.content_builder
8
9
10 DOCUMENTATION = r"""
11 module: appliance_networking_firewall_inbound
12 short_description: Set the ordered list of firewall rules to allow or deny traffic
13 from one or more incoming IP addresses
14 description: 'Set the ordered list of firewall rules to allow or deny traffic from
15 one or more incoming IP addresses. This overwrites the existing firewall rules
16 and creates a new rule list. Within the list of traffic rules, rules are processed
17 in order of appearance, from top to bottom. For example, the list of rules can
18 be as follows: AddressPrefixInterface NamePolicy 10.112.0.10*REJECT 10.112.0.10nic0ACCEPT In
19 the above example, the first rule drops all packets originating from 10.112.0.1
20 and'
21 deprecated:
22 removed_in: 5.0.0
23 why: This module has been moved to the L(new vmware.vmware collection,https://forum.ansible.com/t/5880)
24 alternative: Use M(vmware.vmware.vcsa_settings) instead.
25 options:
26 rules:
27 description:
28 - List of address-based firewall rules. This parameter is mandatory.
29 - 'Valid attributes are:'
30 - ' - C(address) (str): IPv4 or IPv6 address. ([''set''])'
31 - ' This key is required with [''set''].'
32 - ' - C(prefix) (int): CIDR prefix used to mask address. For example, an IPv4
33 prefix of 24 ignores the low-order 8 bits of address. ([''set''])'
34 - ' This key is required with [''set''].'
35 - ' - C(policy) (str): I(policy) enumerated type Defines firewall rule policies.
36 ([''set''])'
37 - ' This key is required with [''set''].'
38 - ' - Accepted values:'
39 - ' - ACCEPT'
40 - ' - IGNORE'
41 - ' - REJECT'
42 - ' - RETURN'
43 - ' - C(interface_name) (str): The interface to which this rule applies. An
44 empty string indicates that the rule applies to all interfaces. ([''set''])'
45 elements: dict
46 required: true
47 type: list
48 session_timeout:
49 description:
50 - 'Timeout settings for client session. '
51 - 'The maximal number of seconds for the whole operation including connection
52 establishment, request sending and response. '
53 - The default value is 300s.
54 type: float
55 version_added: 2.1.0
56 state:
57 choices:
58 - set
59 default: set
60 description: []
61 type: str
62 vcenter_hostname:
63 description:
64 - The hostname or IP address of the vSphere vCenter
65 - If the value is not specified in the task, the value of environment variable
66 C(VMWARE_HOST) will be used instead.
67 required: true
68 type: str
69 vcenter_password:
70 description:
71 - The vSphere vCenter password
72 - If the value is not specified in the task, the value of environment variable
73 C(VMWARE_PASSWORD) will be used instead.
74 required: true
75 type: str
76 vcenter_rest_log_file:
77 description:
78 - 'You can use this optional parameter to set the location of a log file. '
79 - 'This file will be used to record the HTTP REST interaction. '
80 - 'The file will be stored on the host that runs the module. '
81 - 'If the value is not specified in the task, the value of '
82 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
83 type: str
84 vcenter_username:
85 description:
86 - The vSphere vCenter username
87 - If the value is not specified in the task, the value of environment variable
88 C(VMWARE_USER) will be used instead.
89 required: true
90 type: str
91 vcenter_validate_certs:
92 default: true
93 description:
94 - Allows connection when SSL certificates are not valid. Set to C(false) when
95 certificates are not trusted.
96 - If the value is not specified in the task, the value of environment variable
97 C(VMWARE_VALIDATE_CERTS) will be used instead.
98 type: bool
99 author:
100 - Ansible Cloud Team (@ansible-collections)
101 version_added: 2.0.0
102 requirements:
103 - vSphere 7.0.3 or greater
104 - python >= 3.6
105 - aiohttp
106 notes:
107 - Tested on vSphere 7.0.3
108 """
109
110 EXAMPLES = r"""
111 - name: Ensure the rules parameter is mandatory
112 vmware.vmware_rest.appliance_networking_firewall_inbound:
113 register: result
114 failed_when:
115 - not(result.failed)
116 - result.msg == 'missing required arguments: rules'
117
118 - name: Set a firewall rule
119 vmware.vmware_rest.appliance_networking_firewall_inbound:
120 rules:
121 - address: 1.2.3.4
122 prefix: 32
123 policy: ACCEPT
124 register: result
125 """
126 RETURN = r"""
127 # content generated by the update_return_section callback# task: Ensure the rules parameter is mandatory
128 failed_when_result:
129 description: Ensure the rules parameter is mandatory
130 returned: On success
131 sample: 0
132 type: int
133 msg:
134 description: Ensure the rules parameter is mandatory
135 returned: On success
136 sample: 'missing required arguments: rules'
137 type: str
138 """
139
140
141 # This structure describes the format of the data expected by the end-points
142 PAYLOAD_FORMAT = {
143 "set": {"query": {}, "body": {"rules": "rules"}, "path": {}}
144 } # pylint: disable=line-too-long
145
146 from ansible.module_utils.basic import env_fallback
147 import os
148
149 if os.getenv("VMWARE_ENABLE_TURBO", False):
150 try:
151 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
152 AnsibleTurboModule as AnsibleModule,
153 )
154
155 AnsibleModule.collection_name = "vmware.vmware_rest"
156 except ImportError:
157 from ansible.module_utils.basic import AnsibleModule
158 else:
159 from ansible.module_utils.basic import AnsibleModule
160
161 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
162 exists,
163 gen_args,
164 get_subdevice_type,
165 open_session,
166 prepare_payload,
167 session_timeout,
168 update_changed_flag,
169 )
170
171
172 def prepare_argument_spec():
173 argument_spec = {
174 "vcenter_hostname": dict(
175 type="str",
176 required=True,
177 fallback=(env_fallback, ["VMWARE_HOST"]),
178 ),
179 "vcenter_username": dict(
180 type="str",
181 required=True,
182 fallback=(env_fallback, ["VMWARE_USER"]),
183 ),
184 "vcenter_password": dict(
185 type="str",
186 required=True,
187 no_log=True,
188 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
189 ),
190 "vcenter_validate_certs": dict(
191 type="bool",
192 required=False,
193 default=True,
194 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
195 ),
196 "vcenter_rest_log_file": dict(
197 type="str",
198 required=False,
199 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
200 ),
201 "session_timeout": dict(
202 type="float",
203 required=False,
204 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
205 ),
206 }
207
208 argument_spec["rules"] = {"required": True, "type": "list", "elements": "dict"}
209 argument_spec["state"] = {"type": "str", "choices": ["set"], "default": "set"}
210
211 return argument_spec
212
213
214 async def main():
215 required_if = list([])
216
217 module_args = prepare_argument_spec()
218 module = AnsibleModule(
219 argument_spec=module_args, required_if=required_if, supports_check_mode=False
220 )
221 if not module.params["vcenter_hostname"]:
222 module.fail_json("vcenter_hostname cannot be empty")
223 if not module.params["vcenter_username"]:
224 module.fail_json("vcenter_username cannot be empty")
225 if not module.params["vcenter_password"]:
226 module.fail_json("vcenter_password cannot be empty")
227 try:
228 session = await open_session(
229 vcenter_hostname=module.params["vcenter_hostname"],
230 vcenter_username=module.params["vcenter_username"],
231 vcenter_password=module.params["vcenter_password"],
232 validate_certs=module.params["vcenter_validate_certs"],
233 log_file=module.params["vcenter_rest_log_file"],
234 )
235 except Exception as err:
236 if hasattr(err, "get_message"):
237 module.fail_json(err.get_message())
238 else:
239 module.fail_json(str(err))
240 result = await entry_point(module, session)
241 module.exit_json(**result)
242
243
244 # template: default_module.j2
245 def build_url(params):
246 return (
247 "https://{vcenter_hostname}" "/api/appliance/networking/firewall/inbound"
248 ).format(**params)
249
250
251 async def entry_point(module, session):
252
253 if module.params["state"] == "present":
254 if "_create" in globals():
255 operation = "create"
256 else:
257 operation = "update"
258 elif module.params["state"] == "absent":
259 operation = "delete"
260 else:
261 operation = module.params["state"]
262
263 func = globals()["_" + operation]
264
265 return await func(module.params, session)
266
267
268 async def _set(params, session):
269 _in_query_parameters = PAYLOAD_FORMAT["set"]["query"].keys()
270 payload = prepare_payload(params, PAYLOAD_FORMAT["set"])
271 subdevice_type = get_subdevice_type("/api/appliance/networking/firewall/inbound")
272 if subdevice_type and not params[subdevice_type]:
273 _json = await exists(params, session, build_url(params))
274 if _json:
275 params[subdevice_type] = _json["id"]
276 _url = (
277 "https://{vcenter_hostname}" "/api/appliance/networking/firewall/inbound"
278 ).format(**params) + gen_args(params, _in_query_parameters)
279 async with session.get(_url, json=payload, **session_timeout(params)) as resp:
280 before = await resp.json()
281
282 async with session.put(_url, json=payload, **session_timeout(params)) as resp:
283 try:
284 if resp.headers["Content-Type"] == "application/json":
285 _json = await resp.json()
286 except KeyError:
287 _json = {}
288 if "value" not in _json: # 7.0.2
289 _json = {"value": _json}
290
291 # The PUT answer does not let us know if the resource has actually been
292 # modified
293 if resp.status < 300:
294 async with session.get(
295 _url, json=payload, **session_timeout(params)
296 ) as resp_get:
297 after = await resp_get.json()
298 if before == after:
299 return await update_changed_flag(after, resp_get.status, "get")
300 return await update_changed_flag(_json, resp.status, "set")
301
302
303 if __name__ == "__main__":
304 import asyncio
305
306 current_loop = asyncio.new_event_loop()
307 try:
308 asyncio.set_event_loop(current_loop)
309 current_loop.run_until_complete(main())
310 finally:
311 current_loop.close()