Debian Codegraph @

ansible_collections/community/okd/plugins/modules/openshift_route.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2020, Red Hat
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 # STARTREMOVE (downstream)
12 DOCUMENTATION = r"""
13 module: openshift_route
14
15 short_description: Expose a Service as an OpenShift Route.
16
17 version_added: "0.3.0"
18
19 author: "Fabian von Feilitzsch (@fabianvf)"
20
21 description:
22 - Looks up a Service and creates a new Route based on it.
23 - Analogous to `oc expose` and `oc create route` for creating Routes, but does not support creating Services.
24 - For creating Services from other resources, see kubernetes.core.k8s.
25
26 extends_documentation_fragment:
27 - kubernetes.core.k8s_auth_options
28 - kubernetes.core.k8s_wait_options
29 - kubernetes.core.k8s_state_options
30
31 requirements:
32 - "python >= 3.6"
33 - "kubernetes >= 12.0.0"
34 - "PyYAML >= 3.11"
35
36 options:
37 service:
38 description:
39 - The name of the service to expose.
40 - Required when I(state) is not absent.
41 type: str
42 aliases: ['svc']
43 namespace:
44 description:
45 - The namespace of the resource being targeted.
46 - The Route will be created in this namespace as well.
47 required: yes
48 type: str
49 labels:
50 description:
51 - Specify the labels to apply to the created Route.
52 - 'A set of key: value pairs.'
53 type: dict
54 annotations:
55 description:
56 - Specify the Route Annotations.
57 - 'A set of key: value pairs.'
58 type: dict
59 version_added: "2.1.0"
60 name:
61 description:
62 - The desired name of the Route to be created.
63 - Defaults to the value of I(service)
64 type: str
65 hostname:
66 description:
67 - The hostname for the Route.
68 type: str
69 path:
70 description:
71 - The path for the Route
72 type: str
73 wildcard_policy:
74 description:
75 - The wildcard policy for the hostname.
76 - Currently only Subdomain is supported.
77 - If not provided, the default of None will be used.
78 choices:
79 - Subdomain
80 type: str
81 port:
82 description:
83 - Name or number of the port the Route will route traffic to.
84 type: str
85 tls:
86 description:
87 - TLS configuration for the newly created route.
88 - Only used when I(termination) is set.
89 type: dict
90 suboptions:
91 ca_certificate:
92 description:
93 - Path to a CA certificate file on the target host.
94 - Not supported when I(termination) is set to passthrough.
95 type: str
96 certificate:
97 description:
98 - Path to a certificate file on the target host.
99 - Not supported when I(termination) is set to passthrough.
100 type: str
101 destination_ca_certificate:
102 description:
103 - Path to a CA certificate file used for securing the connection.
104 - Only used when I(termination) is set to reencrypt.
105 - Defaults to the Service CA.
106 type: str
107 key:
108 description:
109 - Path to a key file on the target host.
110 - Not supported when I(termination) is set to passthrough.
111 type: str
112 insecure_policy:
113 description:
114 - Sets the InsecureEdgeTerminationPolicy for the Route.
115 - Not supported when I(termination) is set to reencrypt.
116 - When I(termination) is set to passthrough, only redirect is supported.
117 - If not provided, insecure traffic will be disallowed.
118 type: str
119 choices:
120 - allow
121 - redirect
122 - disallow
123 default: disallow
124 termination:
125 description:
126 - The termination type of the Route.
127 - If left empty no termination type will be set, and the route will be insecure.
128 - When set to insecure I(tls) will be ignored.
129 choices:
130 - edge
131 - passthrough
132 - reencrypt
133 - insecure
134 default: insecure
135 type: str
136 """
137
138 EXAMPLES = r"""
139 - name: Create hello-world deployment
140 community.okd.k8s:
141 definition:
142 apiVersion: apps/v1
143 kind: Deployment
144 metadata:
145 name: hello-kubernetes
146 namespace: default
147 spec:
148 replicas: 3
149 selector:
150 matchLabels:
151 app: hello-kubernetes
152 template:
153 metadata:
154 labels:
155 app: hello-kubernetes
156 spec:
157 containers:
158 - name: hello-kubernetes
159 image: paulbouwer/hello-kubernetes:1.8
160 ports:
161 - containerPort: 8080
162
163 - name: Create Service for the hello-world deployment
164 community.okd.k8s:
165 definition:
166 apiVersion: v1
167 kind: Service
168 metadata:
169 name: hello-kubernetes
170 namespace: default
171 spec:
172 ports:
173 - port: 80
174 targetPort: 8080
175 selector:
176 app: hello-kubernetes
177
178 - name: Expose the insecure hello-world service externally
179 community.okd.openshift_route:
180 service: hello-kubernetes
181 namespace: default
182 insecure_policy: allow
183 annotations:
184 haproxy.router.openshift.io/balance: roundrobin
185 register: route
186 """
187
188 RETURN = r"""
189 result:
190 description:
191 - The Route object that was created or updated. Will be empty in the case of deletion.
192 returned: success
193 type: complex
194 contains:
195 apiVersion:
196 description: The versioned schema of this representation of an object.
197 returned: success
198 type: str
199 kind:
200 description: Represents the REST resource this object represents.
201 returned: success
202 type: str
203 metadata:
204 description: Standard object metadata. Includes name, namespace, annotations, labels, etc.
205 returned: success
206 type: complex
207 contains:
208 name:
209 description: The name of the created Route
210 type: str
211 namespace:
212 description: The namespace of the create Route
213 type: str
214 spec:
215 description: Specification for the Route
216 returned: success
217 type: complex
218 contains:
219 host:
220 description: Host is an alias/DNS that points to the service.
221 type: str
222 path:
223 description: Path that the router watches for, to route traffic for to the service.
224 type: str
225 port:
226 description: Defines a port mapping from a router to an endpoint in the service endpoints.
227 type: complex
228 contains:
229 targetPort:
230 description: The target port on pods selected by the service this route points to.
231 type: str
232 tls:
233 description: Defines config used to secure a route and provide termination.
234 type: complex
235 contains:
236 caCertificate:
237 description: Provides the cert authority certificate contents.
238 type: str
239 certificate:
240 description: Provides certificate contents.
241 type: str
242 destinationCACertificate:
243 description: Provides the contents of the ca certificate of the final destination.
244 type: str
245 insecureEdgeTerminationPolicy:
246 description: Indicates the desired behavior for insecure connections to a route.
247 type: str
248 key:
249 description: Provides key file contents.
250 type: str
251 termination:
252 description: Indicates termination type.
253 type: str
254 to:
255 description: Specifies the target that resolve into endpoints.
256 type: complex
257 contains:
258 kind:
259 description: The kind of target that the route is referring to. Currently, only 'Service' is allowed.
260 type: str
261 name:
262 description: Name of the service/target that is being referred to. e.g. name of the service.
263 type: str
264 weight:
265 description: Specifies the target's relative weight against other target reference objects.
266 type: int
267 wildcardPolicy:
268 description: Wildcard policy if any for the route.
269 type: str
270 status:
271 description: Current status details for the Route
272 returned: success
273 type: complex
274 contains:
275 ingress:
276 description: List of places where the route may be exposed.
277 type: complex
278 contains:
279 conditions:
280 description: Array of status conditions for the Route ingress.
281 type: complex
282 contains:
283 type:
284 description: The type of the condition. Currently only 'Ready'.
285 type: str
286 status:
287 description: The status of the condition. Can be True, False, Unknown.
288 type: str
289 host:
290 description: The host string under which the route is exposed.
291 type: str
292 routerCanonicalHostname:
293 description: The external host name for the router that can be used as a CNAME for the host requested for this route. May not be set.
294 type: str
295 routerName:
296 description: A name chosen by the router to identify itself.
297 type: str
298 wildcardPolicy:
299 description: The wildcard policy that was allowed where this route is exposed.
300 type: str
301 duration:
302 description: elapsed time of task in seconds
303 returned: when C(wait) is true
304 type: int
305 sample: 48
306 """
307 # ENDREMOVE (downstream)
308
309 import copy
310
311 from ansible.module_utils._text import to_native
312
313 from ansible_collections.community.okd.plugins.module_utils.openshift_common import (
314 AnsibleOpenshiftModule,
315 )
316
317 try:
318 from ansible_collections.kubernetes.core.plugins.module_utils.k8s.runner import (
319 perform_action,
320 )
321 from ansible_collections.kubernetes.core.plugins.module_utils.k8s.waiter import (
322 Waiter,
323 )
324 from ansible_collections.kubernetes.core.plugins.module_utils.args_common import (
325 AUTH_ARG_SPEC,
326 WAIT_ARG_SPEC,
327 COMMON_ARG_SPEC,
328 )
329 except ImportError as e:
330 pass
331 AUTH_ARG_SPEC = WAIT_ARG_SPEC = COMMON_ARG_SPEC = {}
332
333 try:
334 from kubernetes.dynamic.exceptions import DynamicApiError, NotFoundError
335 except ImportError:
336 pass
337
338
339 class OpenShiftRoute(AnsibleOpenshiftModule):
340 def __init__(self):
341 super(OpenShiftRoute, self).__init__(
342 argument_spec=self.argspec,
343 supports_check_mode=True,
344 )
345
346 self.append_hash = False
347 self.apply = False
348 self.warnings = []
349 self.params["merge_type"] = None
350
351 @property
352 def argspec(self):
353 spec = copy.deepcopy(AUTH_ARG_SPEC)
354 spec.update(copy.deepcopy(WAIT_ARG_SPEC))
355 spec.update(copy.deepcopy(COMMON_ARG_SPEC))
356
357 spec["service"] = dict(type="str", aliases=["svc"])
358 spec["namespace"] = dict(required=True, type="str")
359 spec["labels"] = dict(type="dict")
360 spec["name"] = dict(type="str")
361 spec["hostname"] = dict(type="str")
362 spec["path"] = dict(type="str")
363 spec["wildcard_policy"] = dict(choices=["Subdomain"], type="str")
364 spec["port"] = dict(type="str")
365 spec["tls"] = dict(
366 type="dict",
367 options=dict(
368 ca_certificate=dict(type="str"),
369 certificate=dict(type="str"),
370 destination_ca_certificate=dict(type="str"),
371 key=dict(type="str", no_log=False),
372 insecure_policy=dict(
373 type="str",
374 choices=["allow", "redirect", "disallow"],
375 default="disallow",
376 ),
377 ),
378 )
379 spec["termination"] = dict(
380 choices=["edge", "passthrough", "reencrypt", "insecure"], default="insecure"
381 )
382 spec["annotations"] = dict(type="dict")
383
384 return spec
385
386 def execute_module(self):
387 service_name = self.params.get("service")
388 namespace = self.params["namespace"]
389 termination_type = self.params.get("termination")
390 if termination_type == "insecure":
391 termination_type = None
392 state = self.params.get("state")
393
394 if state != "absent" and not service_name:
395 self.fail_json("If 'state' is not 'absent' then 'service' must be provided")
396
397 # We need to do something a little wonky to wait if the user doesn't supply a custom condition
398 custom_wait = (
399 self.params.get("wait")
400 and not self.params.get("wait_condition")
401 and state != "absent"
402 )
403 if custom_wait:
404 # Don't use default wait logic in perform_action
405 self.params["wait"] = False
406
407 route_name = self.params.get("name") or service_name
408 labels = self.params.get("labels")
409 hostname = self.params.get("hostname")
410 path = self.params.get("path")
411 wildcard_policy = self.params.get("wildcard_policy")
412 port = self.params.get("port")
413 annotations = self.params.get("annotations")
414
415 if termination_type and self.params.get("tls"):
416 tls_ca_cert = self.params["tls"].get("ca_certificate")
417 tls_cert = self.params["tls"].get("certificate")
418 tls_dest_ca_cert = self.params["tls"].get("destination_ca_certificate")
419 tls_key = self.params["tls"].get("key")
420 tls_insecure_policy = self.params["tls"].get("insecure_policy")
421 if tls_insecure_policy == "disallow":
422 tls_insecure_policy = None
423 else:
424 tls_ca_cert = tls_cert = tls_dest_ca_cert = tls_key = (
425 tls_insecure_policy
426 ) = None
427
428 route = {
429 "apiVersion": "route.openshift.io/v1",
430 "kind": "Route",
431 "metadata": {
432 "name": route_name,
433 "namespace": namespace,
434 "labels": labels,
435 },
436 "spec": {},
437 }
438
439 if annotations:
440 route["metadata"]["annotations"] = annotations
441
442 if state != "absent":
443 route["spec"] = self.build_route_spec(
444 service_name,
445 namespace,
446 port=port,
447 wildcard_policy=wildcard_policy,
448 hostname=hostname,
449 path=path,
450 termination_type=termination_type,
451 tls_insecure_policy=tls_insecure_policy,
452 tls_ca_cert=tls_ca_cert,
453 tls_cert=tls_cert,
454 tls_key=tls_key,
455 tls_dest_ca_cert=tls_dest_ca_cert,
456 )
457
458 result = perform_action(self.svc, route, self.params)
459 timeout = self.params.get("wait_timeout")
460 sleep = self.params.get("wait_sleep")
461 if custom_wait:
462 v1_routes = self.find_resource("Route", "route.openshift.io/v1", fail=True)
463 waiter = Waiter(self.client, v1_routes, wait_predicate)
464 success, result["result"], result["duration"] = waiter.wait(
465 timeout=timeout, sleep=sleep, name=route_name, namespace=namespace
466 )
467
468 self.exit_json(**result)
469
470 def build_route_spec(
471 self,
472 service_name,
473 namespace,
474 port=None,
475 wildcard_policy=None,
476 hostname=None,
477 path=None,
478 termination_type=None,
479 tls_insecure_policy=None,
480 tls_ca_cert=None,
481 tls_cert=None,
482 tls_key=None,
483 tls_dest_ca_cert=None,
484 ):
485 v1_services = self.find_resource("Service", "v1", fail=True)
486 try:
487 target_service = v1_services.get(name=service_name, namespace=namespace)
488 except NotFoundError:
489 if not port:
490 self.fail_json(
491 msg="You need to provide the 'port' argument when exposing a non-existent service"
492 )
493 target_service = None
494 except DynamicApiError as exc:
495 self.fail_json(
496 msg="Failed to retrieve service to be exposed: {0}".format(exc.body),
497 error=exc.status,
498 status=exc.status,
499 reason=exc.reason,
500 )
501 except Exception as exc:
502 self.fail_json(
503 msg="Failed to retrieve service to be exposed: {0}".format(
504 to_native(exc)
505 ),
506 error="",
507 status="",
508 reason="",
509 )
510
511 route_spec = {
512 "tls": {},
513 "to": {
514 "kind": "Service",
515 "name": service_name,
516 },
517 "port": {
518 "targetPort": self.set_port(target_service, port),
519 },
520 "wildcardPolicy": wildcard_policy,
521 }
522
523 # Want to conditionally add these so we don't overwrite what is automically added when nothing is provided
524 if termination_type:
525 route_spec["tls"] = dict(termination=termination_type.capitalize())
526 if tls_insecure_policy:
527 if termination_type == "edge":
528 route_spec["tls"][
529 "insecureEdgeTerminationPolicy"
530 ] = tls_insecure_policy.capitalize()
531 elif termination_type == "passthrough":
532 if tls_insecure_policy != "redirect":
533 self.fail_json(
534 "'redirect' is the only supported insecureEdgeTerminationPolicy for passthrough routes"
535 )
536 route_spec["tls"][
537 "insecureEdgeTerminationPolicy"
538 ] = tls_insecure_policy.capitalize()
539 elif termination_type == "reencrypt":
540 self.fail_json(
541 "'tls.insecure_policy' is not supported with reencrypt routes"
542 )
543 else:
544 route_spec["tls"]["insecureEdgeTerminationPolicy"] = None
545 if tls_ca_cert:
546 if termination_type == "passthrough":
547 self.fail_json(
548 "'tls.ca_certificate' is not supported with passthrough routes"
549 )
550 route_spec["tls"]["caCertificate"] = tls_ca_cert
551 if tls_cert:
552 if termination_type == "passthrough":
553 self.fail_json(
554 "'tls.certificate' is not supported with passthrough routes"
555 )
556 route_spec["tls"]["certificate"] = tls_cert
557 if tls_key:
558 if termination_type == "passthrough":
559 self.fail_json("'tls.key' is not supported with passthrough routes")
560 route_spec["tls"]["key"] = tls_key
561 if tls_dest_ca_cert:
562 if termination_type != "reencrypt":
563 self.fail_json(
564 "'destination_certificate' is only valid for reencrypt routes"
565 )
566 route_spec["tls"]["destinationCACertificate"] = tls_dest_ca_cert
567 else:
568 route_spec["tls"] = None
569 if hostname:
570 route_spec["host"] = hostname
571 if path:
572 route_spec["path"] = path
573
574 return route_spec
575
576 def set_port(self, service, port_arg):
577 if port_arg:
578 return port_arg
579 for p in service.spec.ports:
580 if p.protocol == "TCP":
581 if p.name is not None:
582 return p.name
583 return p.targetPort
584 return None
585
586
587 def wait_predicate(route):
588 if not (route.status and route.status.ingress):
589 return False
590 for ingress in route.status.ingress:
591 match = [x for x in ingress.conditions if x.type == "Admitted"]
592 if not match:
593 return False
594 match = match[0]
595 if match.status != "True":
596 return False
597 return True
598
599
600 def main():
601 OpenShiftRoute().run_module()
602
603
604 if __name__ == "__main__":
605 main()