| 1 |
#!/usr/bin/env python |
| 2 |
|
| 3 |
from __future__ import absolute_import, division, print_function |
| 4 |
|
| 5 |
__metaclass__ = type |
| 6 |
|
| 7 |
import re |
| 8 |
import operator |
| 9 |
from functools import reduce |
| 10 |
from ansible_collections.community.okd.plugins.module_utils.openshift_common import ( |
| 11 |
AnsibleOpenshiftModule, |
| 12 |
) |
| 13 |
|
| 14 |
try: |
| 15 |
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.resource import ( |
| 16 |
create_definitions, |
| 17 |
) |
| 18 |
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import ( |
| 19 |
CoreException, |
| 20 |
) |
| 21 |
except ImportError: |
| 22 |
pass |
| 23 |
|
| 24 |
from ansible.module_utils._text import to_native |
| 25 |
|
| 26 |
try: |
| 27 |
from kubernetes.dynamic.exceptions import ( |
| 28 |
DynamicApiError, |
| 29 |
NotFoundError, |
| 30 |
ForbiddenError, |
| 31 |
) |
| 32 |
except ImportError as e: |
| 33 |
pass |
| 34 |
|
| 35 |
|
| 36 |
TRIGGER_ANNOTATION = "image.openshift.io/triggers" |
| 37 |
TRIGGER_CONTAINER = re.compile( |
| 38 |
r"(?P<path>.*)\[((?P<index>[0-9]+)|\?\(@\.name==[\"'\\]*(?P<name>[a-z0-9]([-a-z0-9]*[a-z0-9])?))" |
| 39 |
) |
| 40 |
|
| 41 |
|
| 42 |
class OKDRawModule(AnsibleOpenshiftModule): |
| 43 |
def __init__(self, **kwargs): |
| 44 |
super(OKDRawModule, self).__init__(**kwargs) |
| 45 |
|
| 46 |
@property |
| 47 |
def module(self): |
| 48 |
return self._module |
| 49 |
|
| 50 |
def execute_module(self): |
| 51 |
results = [] |
| 52 |
changed = False |
| 53 |
|
| 54 |
try: |
| 55 |
definitions = create_definitions(self.params) |
| 56 |
except Exception as e: |
| 57 |
msg = "Failed to load resource definition: {0}".format(e) |
| 58 |
raise CoreException(msg) from e |
| 59 |
|
| 60 |
for definition in definitions: |
| 61 |
result = {"changed": False, "result": {}} |
| 62 |
warnings = [] |
| 63 |
|
| 64 |
if self.params.get("state") != "absent": |
| 65 |
existing = None |
| 66 |
name = definition.get("metadata", {}).get("name") |
| 67 |
namespace = definition.get("metadata", {}).get("namespace") |
| 68 |
if definition.get("kind") in ["Project", "ProjectRequest"]: |
| 69 |
try: |
| 70 |
resource = self.svc.find_resource( |
| 71 |
kind=definition.get("kind"), |
| 72 |
api_version=definition.get("apiVersion", "v1"), |
| 73 |
) |
| 74 |
existing = resource.get( |
| 75 |
name=name, namespace=namespace |
| 76 |
).to_dict() |
| 77 |
except (NotFoundError, ForbiddenError): |
| 78 |
result = self.create_project_request(definition) |
| 79 |
changed |= result["changed"] |
| 80 |
results.append(result) |
| 81 |
continue |
| 82 |
except DynamicApiError as exc: |
| 83 |
self.fail_json( |
| 84 |
msg="Failed to retrieve requested object: {0}".format( |
| 85 |
exc.body |
| 86 |
), |
| 87 |
error=exc.status, |
| 88 |
status=exc.status, |
| 89 |
reason=exc.reason, |
| 90 |
) |
| 91 |
|
| 92 |
if definition.get("kind") not in ["Project", "ProjectRequest"]: |
| 93 |
try: |
| 94 |
resource = self.svc.find_resource( |
| 95 |
kind=definition.get("kind"), |
| 96 |
api_version=definition.get("apiVersion", "v1"), |
| 97 |
) |
| 98 |
existing = resource.get( |
| 99 |
name=name, namespace=namespace |
| 100 |
).to_dict() |
| 101 |
except Exception: |
| 102 |
existing = None |
| 103 |
|
| 104 |
if existing: |
| 105 |
if resource.kind == "DeploymentConfig": |
| 106 |
if definition.get("spec", {}).get("triggers"): |
| 107 |
definition = self.resolve_imagestream_triggers( |
| 108 |
existing, definition |
| 109 |
) |
| 110 |
elif ( |
| 111 |
existing["metadata"] |
| 112 |
.get("annotations", {}) |
| 113 |
.get(TRIGGER_ANNOTATION) |
| 114 |
): |
| 115 |
definition = self.resolve_imagestream_trigger_annotation( |
| 116 |
existing, definition |
| 117 |
) |
| 118 |
|
| 119 |
if self.params.get("validate") is not None: |
| 120 |
warnings = self.validate(definition) |
| 121 |
|
| 122 |
try: |
| 123 |
result = self.perform_action(definition, self.params) |
| 124 |
except Exception as e: |
| 125 |
try: |
| 126 |
error = e.result |
| 127 |
except AttributeError: |
| 128 |
error = {} |
| 129 |
try: |
| 130 |
error["reason"] = e.__cause__.reason |
| 131 |
except AttributeError: |
| 132 |
pass |
| 133 |
error["msg"] = to_native(e) |
| 134 |
if warnings: |
| 135 |
error.setdefault("warnings", []).extend(warnings) |
| 136 |
|
| 137 |
if self.params.get("continue_on_error"): |
| 138 |
result["error"] = error |
| 139 |
else: |
| 140 |
self.fail_json(**error) |
| 141 |
|
| 142 |
if warnings: |
| 143 |
result.setdefault("warnings", []).extend(warnings) |
| 144 |
changed |= result["changed"] |
| 145 |
results.append(result) |
| 146 |
|
| 147 |
if len(results) == 1: |
| 148 |
self.exit_json(**results[0]) |
| 149 |
|
| 150 |
self.exit_json(**{"changed": changed, "result": {"results": results}}) |
| 151 |
|
| 152 |
@staticmethod |
| 153 |
def get_index(desired, objects, keys): |
| 154 |
"""Iterates over keys, returns the first object from objects where the value of the key |
| 155 |
matches the value in desired |
| 156 |
""" |
| 157 |
# pylint: disable=use-a-generator |
| 158 |
# Use a generator instead 'all(desired.get(key, True) == item.get(key, False) for key in keys)' |
| 159 |
for i, item in enumerate(objects): |
| 160 |
if item and all( |
| 161 |
[desired.get(key, True) == item.get(key, False) for key in keys] |
| 162 |
): |
| 163 |
return i |
| 164 |
|
| 165 |
def resolve_imagestream_trigger_annotation(self, existing, definition): |
| 166 |
import yaml |
| 167 |
|
| 168 |
def get_from_fields(d, fields): |
| 169 |
try: |
| 170 |
return reduce(operator.getitem, fields, d) |
| 171 |
except Exception: |
| 172 |
return None |
| 173 |
|
| 174 |
def set_from_fields(d, fields, value): |
| 175 |
get_from_fields(d, fields[:-1])[fields[-1]] = value |
| 176 |
|
| 177 |
if TRIGGER_ANNOTATION in definition["metadata"].get("annotations", {}).keys(): |
| 178 |
triggers = yaml.safe_load( |
| 179 |
definition["metadata"]["annotations"][TRIGGER_ANNOTATION] or "[]" |
| 180 |
) |
| 181 |
else: |
| 182 |
triggers = yaml.safe_load( |
| 183 |
existing["metadata"] |
| 184 |
.get("annotations", "{}") |
| 185 |
.get(TRIGGER_ANNOTATION, "[]") |
| 186 |
) |
| 187 |
|
| 188 |
if not isinstance(triggers, list): |
| 189 |
return definition |
| 190 |
|
| 191 |
for trigger in triggers: |
| 192 |
if trigger.get("fieldPath"): |
| 193 |
parsed = self.parse_trigger_fieldpath(trigger["fieldPath"]) |
| 194 |
path = parsed.get("path", "").split(".") |
| 195 |
if path: |
| 196 |
existing_containers = get_from_fields(existing, path) |
| 197 |
new_containers = get_from_fields(definition, path) |
| 198 |
if parsed.get("name"): |
| 199 |
existing_index = self.get_index( |
| 200 |
{"name": parsed["name"]}, existing_containers, ["name"] |
| 201 |
) |
| 202 |
new_index = self.get_index( |
| 203 |
{"name": parsed["name"]}, new_containers, ["name"] |
| 204 |
) |
| 205 |
elif parsed.get("index") is not None: |
| 206 |
existing_index = new_index = int(parsed["index"]) |
| 207 |
else: |
| 208 |
existing_index = new_index = None |
| 209 |
if existing_index is not None and new_index is not None: |
| 210 |
if existing_index < len( |
| 211 |
existing_containers |
| 212 |
) and new_index < len(new_containers): |
| 213 |
set_from_fields( |
| 214 |
definition, |
| 215 |
path + [new_index, "image"], |
| 216 |
get_from_fields( |
| 217 |
existing, path + [existing_index, "image"] |
| 218 |
), |
| 219 |
) |
| 220 |
return definition |
| 221 |
|
| 222 |
def resolve_imagestream_triggers(self, existing, definition): |
| 223 |
existing_triggers = existing.get("spec", {}).get("triggers") |
| 224 |
new_triggers = definition["spec"]["triggers"] |
| 225 |
existing_containers = ( |
| 226 |
existing.get("spec", {}) |
| 227 |
.get("template", {}) |
| 228 |
.get("spec", {}) |
| 229 |
.get("containers", []) |
| 230 |
) |
| 231 |
new_containers = ( |
| 232 |
definition.get("spec", {}) |
| 233 |
.get("template", {}) |
| 234 |
.get("spec", {}) |
| 235 |
.get("containers", []) |
| 236 |
) |
| 237 |
for i, trigger in enumerate(new_triggers): |
| 238 |
if trigger.get("type") == "ImageChange" and trigger.get( |
| 239 |
"imageChangeParams" |
| 240 |
): |
| 241 |
names = trigger["imageChangeParams"].get("containerNames", []) |
| 242 |
for name in names: |
| 243 |
old_container_index = self.get_index( |
| 244 |
{"name": name}, existing_containers, ["name"] |
| 245 |
) |
| 246 |
new_container_index = self.get_index( |
| 247 |
{"name": name}, new_containers, ["name"] |
| 248 |
) |
| 249 |
if ( |
| 250 |
old_container_index is not None |
| 251 |
and new_container_index is not None |
| 252 |
): |
| 253 |
image = existing["spec"]["template"]["spec"]["containers"][ |
| 254 |
old_container_index |
| 255 |
]["image"] |
| 256 |
definition["spec"]["template"]["spec"]["containers"][ |
| 257 |
new_container_index |
| 258 |
]["image"] = image |
| 259 |
|
| 260 |
existing_index = self.get_index( |
| 261 |
trigger["imageChangeParams"], |
| 262 |
[x.get("imageChangeParams") for x in existing_triggers], |
| 263 |
["containerNames"], |
| 264 |
) |
| 265 |
if existing_index is not None: |
| 266 |
existing_image = ( |
| 267 |
existing_triggers[existing_index] |
| 268 |
.get("imageChangeParams", {}) |
| 269 |
.get("lastTriggeredImage") |
| 270 |
) |
| 271 |
if existing_image: |
| 272 |
definition["spec"]["triggers"][i]["imageChangeParams"][ |
| 273 |
"lastTriggeredImage" |
| 274 |
] = existing_image |
| 275 |
existing_from = ( |
| 276 |
existing_triggers[existing_index] |
| 277 |
.get("imageChangeParams", {}) |
| 278 |
.get("from", {}) |
| 279 |
) |
| 280 |
new_from = trigger["imageChangeParams"].get("from", {}) |
| 281 |
existing_namespace = existing_from.get("namespace") |
| 282 |
existing_name = existing_from.get("name", False) |
| 283 |
new_name = new_from.get("name", True) |
| 284 |
add_namespace = ( |
| 285 |
existing_namespace |
| 286 |
and "namespace" not in new_from.keys() |
| 287 |
and existing_name == new_name |
| 288 |
) |
| 289 |
if add_namespace: |
| 290 |
definition["spec"]["triggers"][i]["imageChangeParams"][ |
| 291 |
"from" |
| 292 |
]["namespace"] = existing_from["namespace"] |
| 293 |
|
| 294 |
return definition |
| 295 |
|
| 296 |
def parse_trigger_fieldpath(self, expression): |
| 297 |
parsed = TRIGGER_CONTAINER.search(expression).groupdict() |
| 298 |
if parsed.get("index"): |
| 299 |
parsed["index"] = int(parsed["index"]) |
| 300 |
return parsed |
| 301 |
|
| 302 |
def create_project_request(self, definition): |
| 303 |
definition["kind"] = "ProjectRequest" |
| 304 |
result = {"changed": False, "result": {}} |
| 305 |
resource = self.svc.find_resource( |
| 306 |
kind="ProjectRequest", api_version=definition["apiVersion"], fail=True |
| 307 |
) |
| 308 |
if not self.check_mode: |
| 309 |
try: |
| 310 |
k8s_obj = resource.create(definition) |
| 311 |
result["result"] = k8s_obj.to_dict() |
| 312 |
except DynamicApiError as exc: |
| 313 |
self.fail_json( |
| 314 |
msg="Failed to create object: {0}".format(exc.body), |
| 315 |
error=exc.status, |
| 316 |
status=exc.status, |
| 317 |
reason=exc.reason, |
| 318 |
) |
| 319 |
result["changed"] = True |
| 320 |
result["method"] = "create" |
| 321 |
return result |