| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
from __future__ import absolute_import, division, print_function |
| 8 |
|
| 9 |
__metaclass__ = type |
| 10 |
|
| 11 |
|
| 12 |
DOCUMENTATION = r""" |
| 13 |
module: k8s_log |
| 14 |
|
| 15 |
short_description: Fetch logs from Kubernetes resources |
| 16 |
|
| 17 |
version_added: 0.10.0 |
| 18 |
|
| 19 |
author: |
| 20 |
- "Fabian von Feilitzsch (@fabianvf)" |
| 21 |
|
| 22 |
description: |
| 23 |
- Use the Kubernetes Python client to perform read operations on K8s log endpoints. |
| 24 |
- Authenticate using either a config file, certificates, password or token. |
| 25 |
- Supports check mode. |
| 26 |
- Analogous to `kubectl logs` or `oc logs` |
| 27 |
extends_documentation_fragment: |
| 28 |
- kubernetes.core.k8s_auth_options |
| 29 |
- kubernetes.core.k8s_name_options |
| 30 |
options: |
| 31 |
kind: |
| 32 |
description: |
| 33 |
- Use to specify an object model. |
| 34 |
- Use in conjunction with I(api_version), I(name), and I(namespace) to identify a specific object. |
| 35 |
- If using I(label_selectors), cannot be overridden. |
| 36 |
type: str |
| 37 |
default: Pod |
| 38 |
name: |
| 39 |
description: |
| 40 |
- Use to specify an object name. |
| 41 |
- Use in conjunction with I(api_version), I(kind) and I(namespace) to identify a specific object. |
| 42 |
- Only one of I(name) or I(label_selectors) may be provided. |
| 43 |
type: str |
| 44 |
label_selectors: |
| 45 |
description: |
| 46 |
- List of label selectors to use to filter results |
| 47 |
- Only one of I(name) or I(label_selectors) may be provided. |
| 48 |
type: list |
| 49 |
elements: str |
| 50 |
default: [] |
| 51 |
container: |
| 52 |
description: |
| 53 |
- Use to specify the container within a pod to grab the log from. |
| 54 |
- If there is only one container, this will default to that container. |
| 55 |
- If there is more than one container, this option is required or set I(all_containers) to C(true). |
| 56 |
- mutually exclusive with C(all_containers). |
| 57 |
required: no |
| 58 |
type: str |
| 59 |
since_seconds: |
| 60 |
description: |
| 61 |
- A relative time in seconds before the current time from which to show logs. |
| 62 |
required: no |
| 63 |
type: str |
| 64 |
version_added: 2.2.0 |
| 65 |
previous: |
| 66 |
description: |
| 67 |
- If C(true), print the logs for the previous instance of the container in a pod if it exists. |
| 68 |
required: no |
| 69 |
type: bool |
| 70 |
default: False |
| 71 |
version_added: 2.4.0 |
| 72 |
tail_lines: |
| 73 |
description: |
| 74 |
- A number of lines from the end of the logs to retrieve. |
| 75 |
required: no |
| 76 |
type: int |
| 77 |
version_added: 2.4.0 |
| 78 |
all_containers: |
| 79 |
description: |
| 80 |
- If set to C(true), retrieve all containers' logs in the pod(s). |
| 81 |
- mutually exclusive with C(container). |
| 82 |
type: bool |
| 83 |
version_added: 2.4.0 |
| 84 |
|
| 85 |
requirements: |
| 86 |
- "python >= 3.9" |
| 87 |
- "kubernetes >= 24.2.0" |
| 88 |
- "PyYAML >= 3.11" |
| 89 |
""" |
| 90 |
|
| 91 |
EXAMPLES = r""" |
| 92 |
- name: Get a log from a Pod |
| 93 |
kubernetes.core.k8s_log: |
| 94 |
name: example-1 |
| 95 |
namespace: testing |
| 96 |
register: log |
| 97 |
|
| 98 |
# This will get the log from the first Pod found matching the selector |
| 99 |
- name: Log a Pod matching a label selector |
| 100 |
kubernetes.core.k8s_log: |
| 101 |
namespace: testing |
| 102 |
label_selectors: |
| 103 |
- app=example |
| 104 |
register: log |
| 105 |
|
| 106 |
# This will get the log from a single Pod managed by this Deployment |
| 107 |
- name: Get a log from a Deployment |
| 108 |
kubernetes.core.k8s_log: |
| 109 |
api_version: apps/v1 |
| 110 |
kind: Deployment |
| 111 |
namespace: testing |
| 112 |
name: example |
| 113 |
since_seconds: "4000" |
| 114 |
register: log |
| 115 |
|
| 116 |
# This will get the log from a single Pod managed by this DeploymentConfig |
| 117 |
- name: Get a log from a DeploymentConfig |
| 118 |
kubernetes.core.k8s_log: |
| 119 |
api_version: apps.openshift.io/v1 |
| 120 |
kind: DeploymentConfig |
| 121 |
namespace: testing |
| 122 |
name: example |
| 123 |
tail_lines: 100 |
| 124 |
register: log |
| 125 |
|
| 126 |
# This will get the logs from all containers in Pod |
| 127 |
- name: Get the logs from all containers in pod |
| 128 |
kubernetes.core.k8s_log: |
| 129 |
namespace: testing |
| 130 |
name: some-pod |
| 131 |
all_containers: true |
| 132 |
""" |
| 133 |
|
| 134 |
RETURN = r""" |
| 135 |
log: |
| 136 |
type: str |
| 137 |
description: |
| 138 |
- The text log of the object |
| 139 |
returned: success |
| 140 |
log_lines: |
| 141 |
type: list |
| 142 |
description: |
| 143 |
- The log of the object, split on newlines |
| 144 |
returned: success |
| 145 |
""" |
| 146 |
|
| 147 |
|
| 148 |
import copy |
| 149 |
import json |
| 150 |
|
| 151 |
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import ( |
| 152 |
AnsibleModule, |
| 153 |
) |
| 154 |
from ansible_collections.kubernetes.core.plugins.module_utils.args_common import ( |
| 155 |
AUTH_ARG_SPEC, |
| 156 |
NAME_ARG_SPEC, |
| 157 |
) |
| 158 |
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import ( |
| 159 |
get_api_client, |
| 160 |
) |
| 161 |
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.core import ( |
| 162 |
AnsibleK8SModule, |
| 163 |
) |
| 164 |
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import ( |
| 165 |
CoreException, |
| 166 |
) |
| 167 |
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.service import ( |
| 168 |
K8sService, |
| 169 |
) |
| 170 |
|
| 171 |
try: |
| 172 |
from kubernetes.client.exceptions import ApiException |
| 173 |
except ImportError: |
| 174 |
|
| 175 |
pass |
| 176 |
|
| 177 |
|
| 178 |
def argspec(): |
| 179 |
args = copy.deepcopy(AUTH_ARG_SPEC) |
| 180 |
args.update(NAME_ARG_SPEC) |
| 181 |
args.update( |
| 182 |
dict( |
| 183 |
kind=dict(type="str", default="Pod"), |
| 184 |
container=dict(), |
| 185 |
since_seconds=dict(), |
| 186 |
label_selectors=dict(type="list", elements="str", default=[]), |
| 187 |
previous=dict(type="bool", default=False), |
| 188 |
tail_lines=dict(type="int"), |
| 189 |
all_containers=dict(type="bool"), |
| 190 |
) |
| 191 |
) |
| 192 |
return args |
| 193 |
|
| 194 |
|
| 195 |
def get_exception_message(exc): |
| 196 |
try: |
| 197 |
d = json.loads(exc.body.decode("utf8")) |
| 198 |
return d["message"] |
| 199 |
except Exception: |
| 200 |
return exc |
| 201 |
|
| 202 |
|
| 203 |
def list_containers_in_pod(svc, resource, namespace, name): |
| 204 |
try: |
| 205 |
result = svc.client.get(resource, name=name, namespace=namespace) |
| 206 |
containers = [ |
| 207 |
c["name"] for c in result.to_dict()["status"]["containerStatuses"] |
| 208 |
] |
| 209 |
return containers |
| 210 |
except Exception as exc: |
| 211 |
raise CoreException( |
| 212 |
"Unable to retrieve log from Pod due to: {0}".format( |
| 213 |
get_exception_message(exc) |
| 214 |
) |
| 215 |
) |
| 216 |
|
| 217 |
|
| 218 |
def execute_module(svc, params): |
| 219 |
name = params.get("name") |
| 220 |
namespace = params.get("namespace") |
| 221 |
label_selector = ",".join(params.get("label_selectors", {})) |
| 222 |
if name and label_selector: |
| 223 |
raise CoreException("Only one of name or label_selectors can be provided") |
| 224 |
|
| 225 |
resource = svc.find_resource(params["kind"], params["api_version"], fail=True) |
| 226 |
v1_pods = svc.find_resource("Pod", "v1", fail=True) |
| 227 |
|
| 228 |
if "log" not in resource.subresources: |
| 229 |
if not name: |
| 230 |
raise CoreException( |
| 231 |
"name must be provided for resources that do not support the log subresource" |
| 232 |
) |
| 233 |
instance = resource.get(name=name, namespace=namespace) |
| 234 |
label_selector = ",".join(extract_selectors(instance)) |
| 235 |
resource = v1_pods |
| 236 |
|
| 237 |
if label_selector: |
| 238 |
instances = v1_pods.get(namespace=namespace, label_selector=label_selector) |
| 239 |
if not instances.items: |
| 240 |
raise CoreException( |
| 241 |
"No pods in namespace {0} matched selector {1}".format( |
| 242 |
namespace, label_selector |
| 243 |
) |
| 244 |
) |
| 245 |
|
| 246 |
name = instances.items[0].metadata.name |
| 247 |
resource = v1_pods |
| 248 |
|
| 249 |
if "base" not in resource.log.urls and not name: |
| 250 |
raise CoreException( |
| 251 |
"name must be provided for resources that do not support namespaced base url" |
| 252 |
) |
| 253 |
|
| 254 |
kwargs = {} |
| 255 |
if params.get("container"): |
| 256 |
kwargs["query_params"] = {"container": params["container"]} |
| 257 |
|
| 258 |
if params.get("since_seconds"): |
| 259 |
kwargs.setdefault("query_params", {}).update( |
| 260 |
{"sinceSeconds": params["since_seconds"]} |
| 261 |
) |
| 262 |
|
| 263 |
if params.get("previous"): |
| 264 |
kwargs.setdefault("query_params", {}).update({"previous": params["previous"]}) |
| 265 |
|
| 266 |
if params.get("tail_lines"): |
| 267 |
kwargs.setdefault("query_params", {}).update( |
| 268 |
{"tailLines": params["tail_lines"]} |
| 269 |
) |
| 270 |
|
| 271 |
pod_containers = [None] |
| 272 |
if params.get("all_containers"): |
| 273 |
pod_containers = list_containers_in_pod(svc, resource, namespace, name) |
| 274 |
|
| 275 |
log = "" |
| 276 |
try: |
| 277 |
for container in pod_containers: |
| 278 |
if container is not None: |
| 279 |
kwargs.setdefault("query_params", {}).update({"container": container}) |
| 280 |
response = resource.log.get( |
| 281 |
name=name, namespace=namespace, serialize=False, **kwargs |
| 282 |
) |
| 283 |
log += response.data.decode("utf8") |
| 284 |
except ApiException as exc: |
| 285 |
if exc.reason == "Not Found": |
| 286 |
raise CoreException("Pod {0}/{1} not found.".format(namespace, name)) |
| 287 |
raise CoreException( |
| 288 |
"Unable to retrieve log from Pod due to: {0}".format( |
| 289 |
get_exception_message(exc) |
| 290 |
) |
| 291 |
) |
| 292 |
|
| 293 |
return {"changed": False, "log": log, "log_lines": log.split("\n")} |
| 294 |
|
| 295 |
|
| 296 |
def extract_selectors(instance): |
| 297 |
|
| 298 |
|
| 299 |
selectors = [] |
| 300 |
if not instance.spec.selector: |
| 301 |
raise CoreException( |
| 302 |
"{0} {1} does not support the log subresource directly, and no Pod selector was found on the object".format( |
| 303 |
"/".join(instance.group, instance.apiVersion), instance.kind |
| 304 |
) |
| 305 |
) |
| 306 |
|
| 307 |
if not ( |
| 308 |
instance.spec.selector.matchLabels or instance.spec.selector.matchExpressions |
| 309 |
): |
| 310 |
|
| 311 |
for k, v in dict(instance.spec.selector).items(): |
| 312 |
selectors.append("{0}={1}".format(k, v)) |
| 313 |
return selectors |
| 314 |
|
| 315 |
if instance.spec.selector.matchLabels: |
| 316 |
for k, v in dict(instance.spec.selector.matchLabels).items(): |
| 317 |
selectors.append("{0}={1}".format(k, v)) |
| 318 |
|
| 319 |
if instance.spec.selector.matchExpressions: |
| 320 |
for expression in instance.spec.selector.matchExpressions: |
| 321 |
operator = expression.operator |
| 322 |
|
| 323 |
if operator == "Exists": |
| 324 |
selectors.append(expression.key) |
| 325 |
elif operator == "DoesNotExist": |
| 326 |
selectors.append("!{0}".format(expression.key)) |
| 327 |
elif operator in ["In", "NotIn"]: |
| 328 |
selectors.append( |
| 329 |
"{key} {operator} {values}".format( |
| 330 |
key=expression.key, |
| 331 |
operator=operator.lower(), |
| 332 |
values="({0})".format(", ".join(expression.values)), |
| 333 |
) |
| 334 |
) |
| 335 |
else: |
| 336 |
raise CoreException( |
| 337 |
"The k8s_log module does not support the {0} matchExpression operator".format( |
| 338 |
operator.lower() |
| 339 |
) |
| 340 |
) |
| 341 |
|
| 342 |
return selectors |
| 343 |
|
| 344 |
|
| 345 |
def main(): |
| 346 |
module = AnsibleK8SModule( |
| 347 |
module_class=AnsibleModule, |
| 348 |
argument_spec=argspec(), |
| 349 |
supports_check_mode=True, |
| 350 |
mutually_exclusive=[("container", "all_containers")], |
| 351 |
) |
| 352 |
|
| 353 |
try: |
| 354 |
client = get_api_client(module=module) |
| 355 |
svc = K8sService(client, module) |
| 356 |
result = execute_module(svc, module.params) |
| 357 |
module.exit_json(**result) |
| 358 |
except CoreException as e: |
| 359 |
module.fail_from_exception(e) |
| 360 |
|
| 361 |
|
| 362 |
if __name__ == "__main__": |
| 363 |
main() |