| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
from __future__ import absolute_import, division, print_function |
| 7 |
|
| 8 |
__metaclass__ = type |
| 9 |
|
| 10 |
|
| 11 |
DOCUMENTATION = r""" |
| 12 |
module: k8s_json_patch |
| 13 |
|
| 14 |
short_description: Apply JSON patch operations to existing objects |
| 15 |
|
| 16 |
description: |
| 17 |
- This module is used to apply RFC 6902 JSON patch operations only. |
| 18 |
- Use the M(kubernetes.core.k8s) module for strategic merge or JSON merge operations. |
| 19 |
- The jsonpatch library is required for check mode. |
| 20 |
|
| 21 |
version_added: 2.0.0 |
| 22 |
|
| 23 |
author: |
| 24 |
- Mike Graves (@gravesm) |
| 25 |
|
| 26 |
options: |
| 27 |
api_version: |
| 28 |
description: |
| 29 |
- Use to specify the API version. |
| 30 |
- Use in conjunction with I(kind), I(name), and I(namespace) to identify a specific object. |
| 31 |
type: str |
| 32 |
default: v1 |
| 33 |
aliases: |
| 34 |
- api |
| 35 |
- version |
| 36 |
hidden_fields: |
| 37 |
description: |
| 38 |
- List of fields to hide from the diff output. |
| 39 |
- This is useful for fields that are not relevant to the patch operation, such as `metadata.managedFields`. |
| 40 |
type: list |
| 41 |
elements: str |
| 42 |
default: [] |
| 43 |
version_added: 6.1.0 |
| 44 |
kind: |
| 45 |
description: |
| 46 |
- Use to specify an object model. |
| 47 |
- Use in conjunction with I(api_version), I(name), and I(namespace) to identify a specific object. |
| 48 |
type: str |
| 49 |
required: yes |
| 50 |
namespace: |
| 51 |
description: |
| 52 |
- Use to specify an object namespace. |
| 53 |
- Use in conjunction with I(api_version), I(kind), and I(name) to identify a specific object. |
| 54 |
type: str |
| 55 |
name: |
| 56 |
description: |
| 57 |
- Use to specify an object name. |
| 58 |
- Use in conjunction with I(api_version), I(kind), and I(namespace) to identify a specific object. |
| 59 |
type: str |
| 60 |
required: yes |
| 61 |
patch: |
| 62 |
description: |
| 63 |
- List of JSON patch operations. |
| 64 |
required: yes |
| 65 |
type: list |
| 66 |
elements: dict |
| 67 |
|
| 68 |
extends_documentation_fragment: |
| 69 |
- kubernetes.core.k8s_auth_options |
| 70 |
- kubernetes.core.k8s_wait_options |
| 71 |
|
| 72 |
requirements: |
| 73 |
- "python >= 3.9" |
| 74 |
- "kubernetes >= 24.2.0" |
| 75 |
- "PyYAML >= 3.11" |
| 76 |
- "jsonpatch" |
| 77 |
""" |
| 78 |
|
| 79 |
EXAMPLES = r""" |
| 80 |
- name: Apply multiple patch operations to an existing Pod |
| 81 |
kubernetes.core.k8s_json_patch: |
| 82 |
kind: Pod |
| 83 |
namespace: testing |
| 84 |
name: mypod |
| 85 |
patch: |
| 86 |
- op: add |
| 87 |
path: /metadata/labels/app |
| 88 |
value: myapp |
| 89 |
- op: replace |
| 90 |
path: /spec/containers/0/image |
| 91 |
value: nginx |
| 92 |
""" |
| 93 |
|
| 94 |
RETURN = r""" |
| 95 |
result: |
| 96 |
description: The modified object. |
| 97 |
returned: success |
| 98 |
type: dict |
| 99 |
contains: |
| 100 |
api_version: |
| 101 |
description: The versioned schema of this representation of an object. |
| 102 |
returned: success |
| 103 |
type: str |
| 104 |
kind: |
| 105 |
description: The REST resource this object represents. |
| 106 |
returned: success |
| 107 |
type: str |
| 108 |
metadata: |
| 109 |
description: Standard object metadata. Includes name, namespace, annotations, labels, etc. |
| 110 |
returned: success |
| 111 |
type: dict |
| 112 |
spec: |
| 113 |
description: Specific attributes of the object. Will vary based on the I(api_version) and I(kind). |
| 114 |
returned: success |
| 115 |
type: dict |
| 116 |
status: |
| 117 |
description: Current status details for the object. |
| 118 |
returned: success |
| 119 |
type: dict |
| 120 |
duration: |
| 121 |
description: Elapsed time of task in seconds. |
| 122 |
returned: when C(wait) is true |
| 123 |
type: int |
| 124 |
sample: 48 |
| 125 |
error: |
| 126 |
description: The error when patching the object. |
| 127 |
returned: error |
| 128 |
type: dict |
| 129 |
sample: { |
| 130 |
"msg": "Failed to import the required Python library (jsonpatch) ...", |
| 131 |
"exception": "Traceback (most recent call last): ..." |
| 132 |
} |
| 133 |
""" |
| 134 |
|
| 135 |
import copy |
| 136 |
import traceback |
| 137 |
|
| 138 |
from ansible.module_utils.basic import missing_required_lib |
| 139 |
from ansible.module_utils.common.text.converters import to_native |
| 140 |
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import ( |
| 141 |
AnsibleModule, |
| 142 |
) |
| 143 |
from ansible_collections.kubernetes.core.plugins.module_utils.args_common import ( |
| 144 |
AUTH_ARG_SPEC, |
| 145 |
WAIT_ARG_SPEC, |
| 146 |
) |
| 147 |
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import ( |
| 148 |
get_api_client, |
| 149 |
) |
| 150 |
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.core import ( |
| 151 |
AnsibleK8SModule, |
| 152 |
) |
| 153 |
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import ( |
| 154 |
CoreException, |
| 155 |
) |
| 156 |
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.service import ( |
| 157 |
diff_objects, |
| 158 |
hide_fields, |
| 159 |
) |
| 160 |
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.waiter import ( |
| 161 |
get_waiter, |
| 162 |
) |
| 163 |
|
| 164 |
try: |
| 165 |
from kubernetes.dynamic.exceptions import DynamicApiError |
| 166 |
except ImportError: |
| 167 |
|
| 168 |
pass |
| 169 |
|
| 170 |
JSON_PATCH_IMPORT_ERR = None |
| 171 |
try: |
| 172 |
import jsonpatch |
| 173 |
|
| 174 |
HAS_JSON_PATCH = True |
| 175 |
except ImportError: |
| 176 |
HAS_JSON_PATCH = False |
| 177 |
JSON_PATCH_IMPORT_ERR = traceback.format_exc() |
| 178 |
|
| 179 |
|
| 180 |
JSON_PATCH_ARGS = { |
| 181 |
"api_version": {"default": "v1", "aliases": ["api", "version"]}, |
| 182 |
"kind": {"type": "str", "required": True}, |
| 183 |
"namespace": {"type": "str"}, |
| 184 |
"name": {"type": "str", "required": True}, |
| 185 |
"patch": {"type": "list", "required": True, "elements": "dict"}, |
| 186 |
"hidden_fields": {"type": "list", "elements": "str", "default": []}, |
| 187 |
} |
| 188 |
|
| 189 |
|
| 190 |
def json_patch(existing, patch): |
| 191 |
if not HAS_JSON_PATCH: |
| 192 |
error = { |
| 193 |
"msg": missing_required_lib("jsonpatch"), |
| 194 |
"exception": JSON_PATCH_IMPORT_ERR, |
| 195 |
} |
| 196 |
return None, error |
| 197 |
try: |
| 198 |
patch = jsonpatch.JsonPatch(patch) |
| 199 |
patched = patch.apply(existing) |
| 200 |
return patched, None |
| 201 |
except jsonpatch.InvalidJsonPatch as e: |
| 202 |
error = {"msg": "Invalid JSON patch", "exception": e} |
| 203 |
return None, error |
| 204 |
except jsonpatch.JsonPatchConflict as e: |
| 205 |
error = {"msg": "Patch could not be applied due to a conflict", "exception": e} |
| 206 |
return None, error |
| 207 |
|
| 208 |
|
| 209 |
def execute_module(module, client): |
| 210 |
kind = module.params.get("kind") |
| 211 |
api_version = module.params.get("api_version") |
| 212 |
name = module.params.get("name") |
| 213 |
namespace = module.params.get("namespace") |
| 214 |
patch = module.params.get("patch") |
| 215 |
|
| 216 |
hidden_fields = module.params.get("hidden_fields") |
| 217 |
wait = module.params.get("wait") |
| 218 |
wait_sleep = module.params.get("wait_sleep") |
| 219 |
wait_timeout = module.params.get("wait_timeout") |
| 220 |
wait_condition = None |
| 221 |
if module.params.get("wait_condition") and module.params.get("wait_condition").get( |
| 222 |
"type" |
| 223 |
): |
| 224 |
wait_condition = module.params["wait_condition"] |
| 225 |
|
| 226 |
def build_error_msg(kind, name, msg): |
| 227 |
return "%s %s: %s" % (kind, name, msg) |
| 228 |
|
| 229 |
resource = client.resource(kind, api_version) |
| 230 |
|
| 231 |
try: |
| 232 |
existing = client.get(resource, name=name, namespace=namespace) |
| 233 |
except DynamicApiError as exc: |
| 234 |
msg = "Failed to retrieve requested object: {0}".format(exc.body) |
| 235 |
module.fail_json( |
| 236 |
msg=build_error_msg(kind, name, msg), |
| 237 |
error=exc.status, |
| 238 |
status=exc.status, |
| 239 |
reason=exc.reason, |
| 240 |
) |
| 241 |
except ValueError as exc: |
| 242 |
msg = "Failed to retrieve requested object: {0}".format(to_native(exc)) |
| 243 |
module.fail_json( |
| 244 |
msg=build_error_msg(kind, name, msg), error="", status="", reason="" |
| 245 |
) |
| 246 |
|
| 247 |
if module.check_mode and not client.dry_run: |
| 248 |
obj, error = json_patch(existing.to_dict(), patch) |
| 249 |
if error: |
| 250 |
module.fail_json(**error) |
| 251 |
else: |
| 252 |
params = {} |
| 253 |
if module.check_mode: |
| 254 |
params["dry_run"] = "All" |
| 255 |
try: |
| 256 |
obj = client.patch( |
| 257 |
resource, |
| 258 |
patch, |
| 259 |
name=name, |
| 260 |
namespace=namespace, |
| 261 |
content_type="application/json-patch+json", |
| 262 |
**params |
| 263 |
).to_dict() |
| 264 |
except DynamicApiError as exc: |
| 265 |
msg = "Failed to patch existing object: {0}".format(exc.body) |
| 266 |
module.fail_json( |
| 267 |
msg=msg, error=exc.status, status=exc.status, reason=exc.reason |
| 268 |
) |
| 269 |
except Exception as exc: |
| 270 |
msg = "Failed to patch existing object: {0}".format(exc) |
| 271 |
module.fail_json(msg=msg, error=to_native(exc), status="", reason="") |
| 272 |
|
| 273 |
success = True |
| 274 |
result = {"result": hide_fields(obj, hidden_fields)} |
| 275 |
if wait and not module.check_mode: |
| 276 |
waiter = get_waiter(client, resource, condition=wait_condition) |
| 277 |
success, result["result"], result["duration"] = waiter.wait( |
| 278 |
wait_timeout, wait_sleep, name, namespace |
| 279 |
) |
| 280 |
match, diffs = diff_objects(existing.to_dict(), obj, hidden_fields) |
| 281 |
result["changed"] = not match |
| 282 |
if module._diff: |
| 283 |
result["diff"] = diffs |
| 284 |
|
| 285 |
if not success: |
| 286 |
msg = "Resource update timed out" |
| 287 |
module.fail_json(msg=msg, **result) |
| 288 |
|
| 289 |
module.exit_json(**result) |
| 290 |
|
| 291 |
|
| 292 |
def main(): |
| 293 |
args = copy.deepcopy(AUTH_ARG_SPEC) |
| 294 |
args.update(copy.deepcopy(WAIT_ARG_SPEC)) |
| 295 |
args.update(JSON_PATCH_ARGS) |
| 296 |
module = AnsibleK8SModule( |
| 297 |
module_class=AnsibleModule, argument_spec=args, supports_check_mode=True |
| 298 |
) |
| 299 |
try: |
| 300 |
client = get_api_client(module) |
| 301 |
execute_module(module, client) |
| 302 |
except CoreException as e: |
| 303 |
module.fail_from_exception(e) |
| 304 |
|
| 305 |
|
| 306 |
if __name__ == "__main__": |
| 307 |
main() |