mirror of
https://github.com/ansible-collections/kubernetes.core.git
synced 2026-11-21 14:48:37 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2e5f3198fc | ||
|
|
819adf3e4b | ||
|
|
e91b3171ea | ||
|
|
693e80389b | ||
|
|
53cb65a740 | ||
|
|
a2803df8e8 | ||
|
|
1016f80aee | ||
|
|
90e868aa37 | ||
|
|
864c7addd1 | ||
|
|
021ffbfec2 | ||
|
|
b40a401ec2 | ||
|
|
e620b92b49 | ||
|
|
40123060c1 | ||
|
|
d44a8501e6 | ||
|
|
c3f7a453fd | ||
|
|
5c06a554a8 | ||
|
|
20b9c3fb7f | ||
|
|
7b17313ace | ||
|
|
569bae6593 | ||
|
|
da42348358 | ||
|
|
79e98c3d6e | ||
|
|
477bb79305 | ||
|
|
fd65a4f09e | ||
|
|
b9749c94f9 |
@@ -0,0 +1,20 @@
|
||||
---
|
||||
name: Run collection certification checks
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- stable-*
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: cert-ver-${{ github.head_ref || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
call:
|
||||
uses: ansible-collections/partner-certification-checker/.github/workflows/certification-reusable.yml@f4bf7ba4d3f008b2db8fc6a812fa3f89fdf42c2e # v4.1.0
|
||||
@@ -56,15 +56,24 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
# Ref must match a branch/tag on github.com/ansible/ansible (e.g. stable-2.18, not 2.18).
|
||||
ansible-version: ["stable-2.18", "milestone"]
|
||||
#
|
||||
ansible-version: ["stable-2.18", "stable-2.21", "milestone"]
|
||||
enable-turbo-mode: [true, false]
|
||||
python-version: ["3.12", "3.13"]
|
||||
exclude:
|
||||
# stable-2.18 is used mainly because turbo mode, no reason to test it with turbo mode disabled
|
||||
- ansible-version: "stable-2.18"
|
||||
enable-turbo-mode: false
|
||||
# turbo mode is supported only by ansible<2.19
|
||||
- ansible-version: "milestone"
|
||||
enable-turbo-mode: true
|
||||
# stable-2.18 supports 3.12; milestone (devel) requires >=3.13
|
||||
- ansible-version: "stable-2.21"
|
||||
enable-turbo-mode: true
|
||||
# stable-2.18 supports 3.12
|
||||
- ansible-version: "stable-2.18"
|
||||
python-version: "3.13"
|
||||
- ansible-version: "stable-2.21"
|
||||
python-version: "3.12"
|
||||
- ansible-version: "milestone"
|
||||
python-version: "3.12"
|
||||
workflow-id: ${{ fromJson(needs.splitter.outputs.test_jobs) }}
|
||||
|
||||
@@ -4,6 +4,48 @@ Kubernetes Collection Release Notes
|
||||
|
||||
.. contents:: Topics
|
||||
|
||||
v6.6.0
|
||||
======
|
||||
|
||||
Minor Changes
|
||||
-------------
|
||||
|
||||
- Remove the remaining ``ansible.module_utils.six`` import to avoid deprecation warnings, replacing it with the Python standard library equivalent (https://github.com/ansible-collections/kubernetes.core/pull/1197).
|
||||
- helm - Add ``wait_for_jobs`` option to wait for all Jobs to complete before marking a Helm release as successful. Requires Helm >= 3.5.0 (https://github.com/ansible-collections/kubernetes.core/pull/1140).
|
||||
- helm - add the ``cleanup_on_fail`` option, mapping to the ``--cleanup-on-fail`` flag, to allow deletion of new resources created during a failed upgrade. It complements ``atomic`` and can be combined with it, but cannot be used with ``replace``, since that deploys through ``helm install`` which does not accept the flag (https://github.com/ansible-collections/kubernetes.core/pull/1206).
|
||||
- helm - warn when ``reuse_values`` or ``reset_then_reuse_values`` is requested in a combination helm ignores, which happens by default because ``reset_values`` defaults to ``true``, and whenever either is combined with ``replace``. The option descriptions and the examples now state that ``reset_values`` has to be set to ``false`` for either option to take effect (https://github.com/ansible-collections/kubernetes.core/pull/1230).
|
||||
- k8s lookup - warn when ``ENABLE_TURBO_MODE`` is set but the ``cloud.common`` collection is not installed, instead of silently falling back to the standard lookup base (https://github.com/ansible-collections/kubernetes.core/pull/1242).
|
||||
- k8s_cp - Add the ``copy_timeout`` option (default 300 seconds) bounding how long the module will spend streaming an archive to a pod and waiting for the remote ``tar`` to finish, so that a stalled copy fails instead of hanging indefinitely (https://github.com/ansible-collections/kubernetes.core/pull/1217).
|
||||
- k8s_cp - Stream the tar archive to the pod chunk by chunk instead of building the whole archive in memory first, which cuts peak memory use when copying large files (https://github.com/ansible-collections/kubernetes.core/pull/1217).
|
||||
- k8s_cp - When copying to a pod, the module now also uses ``/bin/sh`` and ``head`` in the container, when present, to confirm the copy completed. Containers without them keep the previous behaviour and get a warning that completion could not be verified (https://github.com/ansible-collections/kubernetes.core/pull/1217).
|
||||
- k8s_info - Support for metadata-only fetches in k8s_info module (https://github.com/ansible-collections/kubernetes.core/pull/1030)
|
||||
- meta - Add ``helm_plugin`` and ``helm_plugin_info`` to the ``helm`` action group, and ``k8s_taint`` to the ``k8s`` action group, so that ``module_defaults`` set on those groups applies to them (https://github.com/ansible-collections/kubernetes.core/pull/1216).
|
||||
- use `collections.abc` instead of deprecated `ansible.module_utils.common._collections_compat` (https://github.com/ansible-collections/kubernetes.core/pull/1057).
|
||||
- waiter - Add ``job_complete`` predicate to support waiting for Job resources to reach ``Complete`` or ``Failed`` condition (https://github.com/ansible-collections/kubernetes.core/issues/1201).
|
||||
|
||||
Deprecated Features
|
||||
-------------------
|
||||
|
||||
- Ansible Turbo mode (``ENABLE_TURBO_MODE``) has been deprecated and will be removed in release 8.0.0, as it depends on the ``cloud.common`` collection, which is being retired (https://github.com/ansible-collections/kubernetes.core/pull/1242).
|
||||
- helm - the ``status.values`` return value has been deprecated and will be removed in version 8.0.0. Use ``status.release_values`` instead (https://github.com/ansible-collections/kubernetes.core/issues/1239).
|
||||
- helm - the ``wait_timeout`` parameter has been deprecated and will be removed in version 7.0.0. Use ``timeout`` instead (https://github.com/ansible-collections/kubernetes.core/issues/1239).
|
||||
- helm_info - the ``status.values`` return value has been deprecated and will be removed in version 8.0.0. Use ``status.release_values`` instead (https://github.com/ansible-collections/kubernetes.core/issues/1239).
|
||||
- k8s_exec - the ``return_code`` return value has been deprecated and will be removed in version 7.0.0. Use ``rc`` instead (https://github.com/ansible-collections/kubernetes.core/issues/1239).
|
||||
- k8s_service - the ``merge_type=json`` option has been deprecated and will be removed in version 7.0.0. Use ``kubernetes.core.k8s_json_patch`` module instead (https://github.com/ansible-collections/kubernetes.core/issues/1239).
|
||||
|
||||
Bugfixes
|
||||
--------
|
||||
|
||||
- Ansible Turbo mode - ignore ``ENABLE_TURBO_MODE`` on ansible-core 2.19.0 and later, where the ``cloud.common`` collection is not supported, and fall back to the standard ``AnsibleModule`` instead of failing with ``byte indices must be integers or slices, not str`` (https://github.com/ansible-collections/kubernetes.core/pull/1242).
|
||||
- helm - do not pass the upgrade-only ``--reuse-values`` and ``--reset-then-reuse-values`` flags to ``helm install``, which rejected them with ``unknown flag`` whenever ``reuse_values`` or ``reset_then_reuse_values`` was combined with ``replace`` (https://github.com/ansible-collections/kubernetes.core/pull/1230).
|
||||
- helm - fix the ``reuse_values`` example, which set only ``reuse_values=true``. ``reset_values`` defaults to ``true`` and helm ignores ``--reuse-values`` whenever ``--reset-values`` is passed, so following the example reset the release values instead of reusing them (https://github.com/ansible-collections/kubernetes.core/pull/1230).
|
||||
- helm - skip Helm's OCI registry progress messages when parsing the output of ``helm show chart``. As of Helm 4.2.1 these are printed to stdout instead of stderr (https://github.com/helm/helm/pull/32056), which made installing a chart from an OCI registry fail with a YAML scanner error when the chart version contained a ``+`` (https://github.com/ansible-collections/kubernetes.core/pull/1223).
|
||||
- helm_repository - normalize both sides of the repository URL comparison, so that a repository already registered with a trailing slash is recognized as matching instead of failing with ``Repository already have a repository named <name>`` (https://github.com/ansible-collections/kubernetes.core/pull/1236).
|
||||
- helm_template - strip Helm's OCI registry progress messages from the returned ``stdout``, which is documented to contain only the rendered templates (https://github.com/ansible-collections/kubernetes.core/pull/1223).
|
||||
- k8s lookup - ignore ``ENABLE_TURBO_MODE`` on ansible-core 2.19.0 and later, where the ``cloud.common`` collection is not supported. Fall back to the standard ``LookupBase`` instead of failing with a traceback (https://github.com/ansible-collections/kubernetes.core/pull/1253).
|
||||
- k8s_cp - Fix silent truncation when copying to a pod. The module closed the exec connection immediately after writing the last chunk of the tar archive, which killed the remote ``tar`` before it had finished extracting, and never checked the process exit status, so a partial copy was reported as a success. The archive is now bounded with ``head -c`` so ``tar`` gets a clean EOF and exits on its own, and the module waits for that exit and fails on a non-zero status (https://github.com/ansible-collections/kubernetes.core/pull/1217).
|
||||
- k8s_info - Handle empty template output gracefully by returning ``changed=false`` instead of failing when Jinja2 template renders to an empty string (https://github.com/ansible-collections/kubernetes.core/issues/1042).
|
||||
|
||||
v6.5.0
|
||||
======
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# Also needs to be updated in galaxy.yml
|
||||
VERSION = 6.5.0
|
||||
VERSION = 6.6.0
|
||||
|
||||
TEST_ARGS ?= ""
|
||||
PYTHON_VERSION ?= `python -c 'import platform; print(".".join(platform.python_version_tuple()[0:2]))'`
|
||||
|
||||
@@ -22,7 +22,7 @@ Click on the name of a plugin or module to view that content's documentation:
|
||||
### Connection plugins
|
||||
Name | Description
|
||||
--- | ---
|
||||
[kubernetes.core.kubectl](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.kubectl_connection.rst)|Execute tasks in pods running on Kubernetes.
|
||||
[kubernetes.core.kubectl](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.kubectl_connection.rst)|Execute tasks in pods running on Kubernetes.
|
||||
|
||||
### K8s filter plugins
|
||||
Name | Description
|
||||
@@ -32,33 +32,33 @@ kubernetes.core.k8s_config_resource_name|Generate resource name for the given re
|
||||
### Lookup plugins
|
||||
Name | Description
|
||||
--- | ---
|
||||
[kubernetes.core.k8s](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_lookup.rst)|Query the K8s API
|
||||
[kubernetes.core.kustomize](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.kustomize_lookup.rst)|Build a set of kubernetes resources using a 'kustomization.yaml' file.
|
||||
[kubernetes.core.k8s](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_lookup.rst)|Query the K8s API
|
||||
[kubernetes.core.kustomize](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.kustomize_lookup.rst)|Build a set of kubernetes resources using a 'kustomization.yaml' file.
|
||||
|
||||
### Modules
|
||||
Name | Description
|
||||
--- | ---
|
||||
[kubernetes.core.helm](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.helm_module.rst)|Manages Kubernetes packages with the Helm package manager
|
||||
[kubernetes.core.helm_info](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.helm_info_module.rst)|Get information from Helm package deployed inside the cluster
|
||||
[kubernetes.core.helm_plugin](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.helm_plugin_module.rst)|Manage Helm plugins
|
||||
[kubernetes.core.helm_plugin_info](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.helm_plugin_info_module.rst)|Gather information about Helm plugins
|
||||
[kubernetes.core.helm_pull](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.helm_pull_module.rst)|download a chart from a repository and (optionally) unpack it in local directory.
|
||||
[kubernetes.core.helm_registry_auth](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.helm_registry_auth_module.rst)|Helm registry authentication module
|
||||
[kubernetes.core.helm_repository](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.helm_repository_module.rst)|Manage Helm repositories.
|
||||
[kubernetes.core.helm_template](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.helm_template_module.rst)|Render chart templates
|
||||
[kubernetes.core.k8s](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_module.rst)|Manage Kubernetes (K8s) objects
|
||||
[kubernetes.core.k8s_cluster_info](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_cluster_info_module.rst)|Describe Kubernetes (K8s) cluster, APIs available and their respective versions
|
||||
[kubernetes.core.k8s_cp](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_cp_module.rst)|Copy files and directories to and from pod.
|
||||
[kubernetes.core.k8s_drain](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_drain_module.rst)|Drain, Cordon, or Uncordon node in k8s cluster
|
||||
[kubernetes.core.k8s_exec](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_exec_module.rst)|Execute command in Pod
|
||||
[kubernetes.core.k8s_info](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_info_module.rst)|Describe Kubernetes (K8s) objects
|
||||
[kubernetes.core.k8s_json_patch](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_json_patch_module.rst)|Apply JSON patch operations to existing objects
|
||||
[kubernetes.core.k8s_log](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_log_module.rst)|Fetch logs from Kubernetes resources
|
||||
[kubernetes.core.k8s_rollback](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_rollback_module.rst)|Rollback Kubernetes (K8S) Deployments and DaemonSets
|
||||
[kubernetes.core.k8s_scale](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_scale_module.rst)|Set a new size for a Deployment, ReplicaSet, Replication Controller, or Job.
|
||||
[kubernetes.core.k8s_service](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_service_module.rst)|Manage Services on Kubernetes
|
||||
[kubernetes.core.k8s_taint](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_taint_module.rst)|Taint a node in a Kubernetes/OpenShift cluster
|
||||
[kubernetes.core.kubeconfig](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.kubeconfig_module.rst)|Generate, update, and optionally write Kubernetes kubeconfig files
|
||||
[kubernetes.core.helm](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.helm_module.rst)|Manages Kubernetes packages with the Helm package manager
|
||||
[kubernetes.core.helm_info](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.helm_info_module.rst)|Get information from Helm package deployed inside the cluster
|
||||
[kubernetes.core.helm_plugin](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.helm_plugin_module.rst)|Manage Helm plugins
|
||||
[kubernetes.core.helm_plugin_info](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.helm_plugin_info_module.rst)|Gather information about Helm plugins
|
||||
[kubernetes.core.helm_pull](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.helm_pull_module.rst)|download a chart from a repository and (optionally) unpack it in local directory.
|
||||
[kubernetes.core.helm_registry_auth](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.helm_registry_auth_module.rst)|Helm registry authentication module
|
||||
[kubernetes.core.helm_repository](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.helm_repository_module.rst)|Manage Helm repositories.
|
||||
[kubernetes.core.helm_template](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.helm_template_module.rst)|Render chart templates
|
||||
[kubernetes.core.k8s](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_module.rst)|Manage Kubernetes (K8s) objects
|
||||
[kubernetes.core.k8s_cluster_info](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_cluster_info_module.rst)|Describe Kubernetes (K8s) cluster, APIs available and their respective versions
|
||||
[kubernetes.core.k8s_cp](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_cp_module.rst)|Copy files and directories to and from pod.
|
||||
[kubernetes.core.k8s_drain](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_drain_module.rst)|Drain, Cordon, or Uncordon node in k8s cluster
|
||||
[kubernetes.core.k8s_exec](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_exec_module.rst)|Execute command in Pod
|
||||
[kubernetes.core.k8s_info](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_info_module.rst)|Describe Kubernetes (K8s) objects
|
||||
[kubernetes.core.k8s_json_patch](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_json_patch_module.rst)|Apply JSON patch operations to existing objects
|
||||
[kubernetes.core.k8s_log](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_log_module.rst)|Fetch logs from Kubernetes resources
|
||||
[kubernetes.core.k8s_rollback](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_rollback_module.rst)|Rollback Kubernetes (K8S) Deployments and DaemonSets
|
||||
[kubernetes.core.k8s_scale](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_scale_module.rst)|Set a new size for a Deployment, ReplicaSet, Replication Controller, or Job.
|
||||
[kubernetes.core.k8s_service](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_service_module.rst)|Manage Services on Kubernetes
|
||||
[kubernetes.core.k8s_taint](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_taint_module.rst)|Taint a node in a Kubernetes/OpenShift cluster
|
||||
[kubernetes.core.kubeconfig](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.kubeconfig_module.rst)|Generate, update, and optionally write Kubernetes kubeconfig files
|
||||
|
||||
<!--end collection content-->
|
||||
|
||||
@@ -100,7 +100,7 @@ You can also include it in a `requirements.yml` file and install it via `ansible
|
||||
---
|
||||
collections:
|
||||
- name: kubernetes.core
|
||||
version: 6.5.0
|
||||
version: 6.6.0
|
||||
```
|
||||
|
||||
### Installing the Kubernetes Python Library
|
||||
@@ -181,7 +181,9 @@ For documentation on how to use individual modules and other content included in
|
||||
|
||||
## Ansible Turbo Mode Tech Preview
|
||||
|
||||
> **Note:** Ansible Turbo mode is supported only with ``ansible-core`` versions **lower than 2.19**. Starting from ``ansible-core`` 2.19, the ``cloud.common`` collection is no longer supported, and therefore Ansible Turbo mode is also not supported in ``kubernetes.core``. If ``ENABLE_TURBO_MODE`` is set to ``1`` (or any truthy value) with ``ansible-core >= 2.19.0``, it may lead to fails.
|
||||
> **Deprecated:** Ansible Turbo mode (`ENABLE_TURBO_MODE`) is deprecated and will be removed in a future major release (planned for 8.0.0), since it depends on the `cloud.common` collection, which is being retired. Setting `ENABLE_TURBO_MODE` will keep emitting a deprecation warning until support is removed, at which point the variable will have no effect.
|
||||
|
||||
> **Note:** Ansible Turbo mode is supported only with ``ansible-core`` versions **lower than 2.19**. Starting from ``ansible-core`` 2.19, the ``cloud.common`` collection is no longer supported, and therefore Ansible Turbo mode is also not supported in ``kubernetes.core``. If ``ENABLE_TURBO_MODE`` is set to ``1`` (or any truthy value) with ``ansible-core >= 2.19.0``, Turbo mode is ignored and a warning is emitted; modules run without it.
|
||||
|
||||
The ``kubernetes.core`` collection supports Ansible Turbo mode as a tech preview via the ``cloud.common`` collection (requires `ansible-core < 2.19`). By default, this feature is disabled. To enable Turbo mode for modules, set the environment variable `ENABLE_TURBO_MODE=1` on the managed node. For example:
|
||||
|
||||
|
||||
@@ -1251,3 +1251,112 @@ releases:
|
||||
name: kubeconfig
|
||||
namespace: ''
|
||||
release_date: '2026-07-08'
|
||||
6.6.0:
|
||||
changes:
|
||||
bugfixes:
|
||||
- Ansible Turbo mode - ignore ``ENABLE_TURBO_MODE`` on ansible-core 2.19.0 and
|
||||
later, where the ``cloud.common`` collection is not supported, and fall back
|
||||
to the standard ``AnsibleModule`` instead of failing with ``byte indices must
|
||||
be integers or slices, not str`` (https://github.com/ansible-collections/kubernetes.core/pull/1242).
|
||||
- helm - do not pass the upgrade-only ``--reuse-values`` and ``--reset-then-reuse-values``
|
||||
flags to ``helm install``, which rejected them with ``unknown flag`` whenever
|
||||
``reuse_values`` or ``reset_then_reuse_values`` was combined with ``replace``
|
||||
(https://github.com/ansible-collections/kubernetes.core/pull/1230).
|
||||
- helm - fix the ``reuse_values`` example, which set only ``reuse_values=true``.
|
||||
``reset_values`` defaults to ``true`` and helm ignores ``--reuse-values``
|
||||
whenever ``--reset-values`` is passed, so following the example reset the
|
||||
release values instead of reusing them (https://github.com/ansible-collections/kubernetes.core/pull/1230).
|
||||
- helm - skip Helm's OCI registry progress messages when parsing the output
|
||||
of ``helm show chart``. As of Helm 4.2.1 these are printed to stdout instead
|
||||
of stderr (https://github.com/helm/helm/pull/32056), which made installing
|
||||
a chart from an OCI registry fail with a YAML scanner error when the chart
|
||||
version contained a ``+`` (https://github.com/ansible-collections/kubernetes.core/pull/1223).
|
||||
- helm_repository - normalize both sides of the repository URL comparison, so
|
||||
that a repository already registered with a trailing slash is recognized as
|
||||
matching instead of failing with ``Repository already have a repository named
|
||||
<name>`` (https://github.com/ansible-collections/kubernetes.core/pull/1236).
|
||||
- helm_template - strip Helm's OCI registry progress messages from the returned
|
||||
``stdout``, which is documented to contain only the rendered templates (https://github.com/ansible-collections/kubernetes.core/pull/1223).
|
||||
- k8s lookup - ignore ``ENABLE_TURBO_MODE`` on ansible-core 2.19.0 and later,
|
||||
where the ``cloud.common`` collection is not supported. Fall back to the standard
|
||||
``LookupBase`` instead of failing with a traceback (https://github.com/ansible-collections/kubernetes.core/pull/1253).
|
||||
- k8s_cp - Fix silent truncation when copying to a pod. The module closed the
|
||||
exec connection immediately after writing the last chunk of the tar archive,
|
||||
which killed the remote ``tar`` before it had finished extracting, and never
|
||||
checked the process exit status, so a partial copy was reported as a success.
|
||||
The archive is now bounded with ``head -c`` so ``tar`` gets a clean EOF and
|
||||
exits on its own, and the module waits for that exit and fails on a non-zero
|
||||
status (https://github.com/ansible-collections/kubernetes.core/pull/1217).
|
||||
- k8s_info - Handle empty template output gracefully by returning ``changed=false``
|
||||
instead of failing when Jinja2 template renders to an empty string (https://github.com/ansible-collections/kubernetes.core/issues/1042).
|
||||
deprecated_features:
|
||||
- Ansible Turbo mode (``ENABLE_TURBO_MODE``) has been deprecated and will be
|
||||
removed in release 8.0.0, as it depends on the ``cloud.common`` collection,
|
||||
which is being retired (https://github.com/ansible-collections/kubernetes.core/pull/1242).
|
||||
- helm - the ``status.values`` return value has been deprecated and will be
|
||||
removed in version 8.0.0. Use ``status.release_values`` instead (https://github.com/ansible-collections/kubernetes.core/issues/1239).
|
||||
- helm - the ``wait_timeout`` parameter has been deprecated and will be removed
|
||||
in version 7.0.0. Use ``timeout`` instead (https://github.com/ansible-collections/kubernetes.core/issues/1239).
|
||||
- helm_info - the ``status.values`` return value has been deprecated and will
|
||||
be removed in version 8.0.0. Use ``status.release_values`` instead (https://github.com/ansible-collections/kubernetes.core/issues/1239).
|
||||
- k8s_exec - the ``return_code`` return value has been deprecated and will be
|
||||
removed in version 7.0.0. Use ``rc`` instead (https://github.com/ansible-collections/kubernetes.core/issues/1239).
|
||||
- k8s_service - the ``merge_type=json`` option has been deprecated and will
|
||||
be removed in version 7.0.0. Use ``kubernetes.core.k8s_json_patch`` module
|
||||
instead (https://github.com/ansible-collections/kubernetes.core/issues/1239).
|
||||
minor_changes:
|
||||
- Remove the remaining ``ansible.module_utils.six`` import to avoid deprecation
|
||||
warnings, replacing it with the Python standard library equivalent (https://github.com/ansible-collections/kubernetes.core/pull/1197).
|
||||
- helm - Add ``wait_for_jobs`` option to wait for all Jobs to complete before
|
||||
marking a Helm release as successful. Requires Helm >= 3.5.0 (https://github.com/ansible-collections/kubernetes.core/pull/1140).
|
||||
- helm - add the ``cleanup_on_fail`` option, mapping to the ``--cleanup-on-fail``
|
||||
flag, to allow deletion of new resources created during a failed upgrade.
|
||||
It complements ``atomic`` and can be combined with it, but cannot be used
|
||||
with ``replace``, since that deploys through ``helm install`` which does not
|
||||
accept the flag (https://github.com/ansible-collections/kubernetes.core/pull/1206).
|
||||
- helm - warn when ``reuse_values`` or ``reset_then_reuse_values`` is requested
|
||||
in a combination helm ignores, which happens by default because ``reset_values``
|
||||
defaults to ``true``, and whenever either is combined with ``replace``. The
|
||||
option descriptions and the examples now state that ``reset_values`` has to
|
||||
be set to ``false`` for either option to take effect (https://github.com/ansible-collections/kubernetes.core/pull/1230).
|
||||
- k8s lookup - warn when ``ENABLE_TURBO_MODE`` is set but the ``cloud.common``
|
||||
collection is not installed, instead of silently falling back to the standard
|
||||
lookup base (https://github.com/ansible-collections/kubernetes.core/pull/1242).
|
||||
- k8s_cp - Add the ``copy_timeout`` option (default 300 seconds) bounding how
|
||||
long the module will spend streaming an archive to a pod and waiting for the
|
||||
remote ``tar`` to finish, so that a stalled copy fails instead of hanging
|
||||
indefinitely (https://github.com/ansible-collections/kubernetes.core/pull/1217).
|
||||
- k8s_cp - Stream the tar archive to the pod chunk by chunk instead of building
|
||||
the whole archive in memory first, which cuts peak memory use when copying
|
||||
large files (https://github.com/ansible-collections/kubernetes.core/pull/1217).
|
||||
- k8s_cp - When copying to a pod, the module now also uses ``/bin/sh`` and ``head``
|
||||
in the container, when present, to confirm the copy completed. Containers
|
||||
without them keep the previous behaviour and get a warning that completion
|
||||
could not be verified (https://github.com/ansible-collections/kubernetes.core/pull/1217).
|
||||
- k8s_info - Support for metadata-only fetches in k8s_info module (https://github.com/ansible-collections/kubernetes.core/pull/1030)
|
||||
- meta - Add ``helm_plugin`` and ``helm_plugin_info`` to the ``helm`` action
|
||||
group, and ``k8s_taint`` to the ``k8s`` action group, so that ``module_defaults``
|
||||
set on those groups applies to them (https://github.com/ansible-collections/kubernetes.core/pull/1216).
|
||||
- use `collections.abc` instead of deprecated `ansible.module_utils.common._collections_compat`
|
||||
(https://github.com/ansible-collections/kubernetes.core/pull/1057).
|
||||
- waiter - Add ``job_complete`` predicate to support waiting for Job resources
|
||||
to reach ``Complete`` or ``Failed`` condition (https://github.com/ansible-collections/kubernetes.core/issues/1201).
|
||||
fragments:
|
||||
- 1253-k8s-lookup-turbo-version-check.yml
|
||||
- 20250108-fix-empty-template-output.yaml
|
||||
- 20251027-metadata-only-fetches.yaml
|
||||
- 20260109-fix-deprecated-calls.yaml
|
||||
- 20260723-remove-module-utils-six.yaml
|
||||
- 20260805-add-job-wait-condition.yaml
|
||||
- 20260807-helm-cleanup-on-fail.yaml
|
||||
- 20260807-helm-wait-for-jobs.yaml
|
||||
- 20260812-action-groups.yaml
|
||||
- 20260813-k8s-cp-truncation.yaml
|
||||
- 20260817-helm-oci-registry-progress-on-stdout.yml
|
||||
- 20260826-helm-value-reuse-options.yaml
|
||||
- 20260908-helm-repository-trailing-slash.yaml
|
||||
- 20260911-deprecate-status-values.yaml
|
||||
- 20260911-update-deprecation-notices.yaml
|
||||
- deprecate-enable-turbo-mode.yml
|
||||
- fix-ansible-lint-warnings.yaml
|
||||
release_date: '2026-09-16'
|
||||
|
||||
@@ -12,12 +12,19 @@ Following document provides overview of Ansible Turbo mode in ``kubernetes.core`
|
||||
:depth: 1
|
||||
|
||||
|
||||
.. warning::
|
||||
Ansible Turbo mode is **deprecated** and will be removed in a future major release
|
||||
(planned for 8.0.0), as it depends on the ``cloud.common`` collection, which is being
|
||||
retired. Setting ``ENABLE_TURBO_MODE`` now emits a deprecation warning; once support is
|
||||
removed, the variable will have no effect. Start planning your migration away from
|
||||
Turbo mode.
|
||||
|
||||
.. warning::
|
||||
Ansible Turbo mode is supported only with ``ansible-core`` versions **lower than 2.19**.
|
||||
Starting from ``ansible-core`` 2.19, the ``cloud.common`` collection is no longer supported,
|
||||
and therefore Ansible Turbo mode is also not supported in ``kubernetes.core``.
|
||||
If ``ENABLE_TURBO_MODE`` is set to ``1`` (or any truthy value) with ``ansible-core >= 2.19.0``,
|
||||
it may lead to failures.
|
||||
Turbo mode is ignored and a warning is emitted; modules run without it.
|
||||
|
||||
Synopsis
|
||||
--------
|
||||
|
||||
@@ -42,6 +42,92 @@ Basic authentication is also supported using the ``username`` and ``password`` o
|
||||
|
||||
To disable SSL certificate verification, set ``verify_ssl`` to false.
|
||||
|
||||
Sharing options across tasks with action groups
|
||||
===============================================
|
||||
|
||||
Repeating the same authentication options on every task gets verbose quickly. The collection
|
||||
defines two `action groups <https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_module_defaults.html#module-defaults-groups>`_
|
||||
so you can set them once with ``module_defaults``:
|
||||
|
||||
``kubernetes.core.k8s``
|
||||
Modules that talk to the Kubernetes API and accept the standard authentication options
|
||||
(``kubeconfig``, ``context``, ``host``, ``api_key``, ``validate_certs``, and so on):
|
||||
``k8s``, ``k8s_cluster_info``, ``k8s_cp``, ``k8s_drain``, ``k8s_exec``, ``k8s_info``,
|
||||
``k8s_json_patch``, ``k8s_log``, ``k8s_rollback``, ``k8s_scale``, ``k8s_service``, and
|
||||
``k8s_taint``.
|
||||
|
||||
``kubernetes.core.helm``
|
||||
Modules that shell out to the ``helm`` binary and accept its shared authentication
|
||||
options (``binary_path``, ``kubeconfig``, ``context``, ``host``, ``api_key``,
|
||||
``ca_cert``, ``validate_certs``): ``helm``, ``helm_info``, ``helm_plugin``,
|
||||
``helm_plugin_info``, and ``helm_repository``.
|
||||
|
||||
Prefix the group name with ``group/`` to use it:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
- hosts: localhost
|
||||
module_defaults:
|
||||
group/kubernetes.core.k8s:
|
||||
kubeconfig: /path/to/kubeconfig
|
||||
context: staging
|
||||
group/kubernetes.core.helm:
|
||||
binary_path: /path/to/helm
|
||||
kubeconfig: /path/to/kubeconfig
|
||||
context: staging
|
||||
tasks:
|
||||
- name: Create a namespace
|
||||
kubernetes.core.k8s:
|
||||
definition:
|
||||
apiVersion: v1
|
||||
kind: Namespace
|
||||
metadata:
|
||||
name: monitoring
|
||||
|
||||
- name: Read it back
|
||||
kubernetes.core.k8s_info:
|
||||
kind: Namespace
|
||||
name: monitoring
|
||||
|
||||
- name: Add the prometheus chart repository
|
||||
kubernetes.core.helm_repository:
|
||||
name: prometheus-community
|
||||
repo_url: https://prometheus-community.github.io/helm-charts
|
||||
|
||||
- name: Deploy the kube-prometheus-stack chart
|
||||
kubernetes.core.helm:
|
||||
name: kube-prometheus-stack
|
||||
chart_ref: prometheus-community/kube-prometheus-stack
|
||||
release_namespace: monitoring
|
||||
|
||||
- name: Collect the releases in that namespace
|
||||
kubernetes.core.helm_info:
|
||||
name: kube-prometheus-stack
|
||||
release_namespace: monitoring
|
||||
|
||||
Every task picks up ``kubeconfig`` and ``context`` from its group without repeating them, the
|
||||
``helm`` modules additionally pick up ``binary_path``, and an option set on an individual task
|
||||
still wins over the group default.
|
||||
|
||||
.. note::
|
||||
|
||||
Always write the group name fully qualified as ``group/kubernetes.core.k8s``. A bare
|
||||
``group/k8s`` refers to the legacy ``k8s`` group that ansible-core defined back when the
|
||||
Kubernetes modules shipped in core itself. The two are not the same group, and the legacy
|
||||
one does not cover the modules in this collection.
|
||||
|
||||
Some modules are deliberately **not** in these groups because they do not accept the shared
|
||||
authentication options, and including them would make ``module_defaults`` fail for everyone
|
||||
using the group:
|
||||
|
||||
- ``helm_pull`` and ``helm_template`` accept only ``binary_path``.
|
||||
- ``helm_registry_auth`` accepts ``binary_path`` and its own ``host``, which is an OCI
|
||||
registry URL rather than a Kubernetes API server.
|
||||
- ``kubeconfig`` writes a kubeconfig file locally and takes no cluster connection options.
|
||||
|
||||
Pass options to those modules directly, or give them their own per-module ``module_defaults``
|
||||
entry.
|
||||
|
||||
Reporting an issue
|
||||
==================
|
||||
|
||||
|
||||
@@ -488,7 +488,7 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
|
||||
<td>always</td>
|
||||
<td>
|
||||
<div>Dict of Values used to deploy</div>
|
||||
<div>This return value has been deprecated and will be removed in a release after 2027-01-08. Use RV(status.release_values) instead.</div>
|
||||
<div>This return value has been deprecated and will be removed in version 8.0.0. Use RV(status.release_values) instead.</div>
|
||||
<br/>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@@ -157,6 +157,29 @@ Parameters
|
||||
<div>Chart version to install. If this is not specified, the latest version is installed.</div>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="2">
|
||||
<div class="ansibleOptionAnchor" id="parameter-"></div>
|
||||
<b>cleanup_on_fail</b>
|
||||
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
|
||||
<div style="font-size: small">
|
||||
<span style="color: purple">boolean</span>
|
||||
</div>
|
||||
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.6.0</div>
|
||||
</td>
|
||||
<td>
|
||||
<ul style="margin: 0; padding: 0"><b>Choices:</b>
|
||||
<li><div style="color: blue"><b>no</b> ←</div></li>
|
||||
<li>yes</li>
|
||||
</ul>
|
||||
</td>
|
||||
<td>
|
||||
<div>Allow deletion of new resources created during a failed upgrade.</div>
|
||||
<div>Maps to the <code>--cleanup-on-fail</code> flag, which is available since helm 3.0.0 and was not renamed in Helm v4.</div>
|
||||
<div>Complements O(atomic) rather than replacing it, and the two can be combined so that a rollback also drops resources orphaned by the failed upgrade.</div>
|
||||
<div>Helm only accepts this flag on <code>helm upgrade</code>, so it cannot be used together with O(replace), which deploys through <code>helm install</code>.</div>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="2">
|
||||
<div class="ansibleOptionAnchor" id="parameter-"></div>
|
||||
@@ -522,7 +545,9 @@ Parameters
|
||||
</td>
|
||||
<td>
|
||||
<div>When upgrading package, reset the values to the ones built into the chart, apply the last release's values and merge in any overrides from parameters O(release_values), O(values_files) or O(set_values).</div>
|
||||
<div>If O(reset_values) or O(reuse_values) is set to V(True), this is ignored.</div>
|
||||
<div>Helm ignores this when <code>--reset-values</code> or <code>--reuse-values</code> is passed. Since O(reset_values) defaults to V(true), it has to be set to V(false), and O(reuse_values) left unset or V(false), for this option to take any effect.</div>
|
||||
<div><code>helm install</code> does not accept <code>--reset-then-reuse-values</code>, so this option is ignored when O(replace) is set.</div>
|
||||
<div>The module warns whenever one of those combinations makes this option a no-op.</div>
|
||||
<div>This feature requires helm diff >= 3.9.12.</div>
|
||||
</td>
|
||||
</tr>
|
||||
@@ -544,6 +569,7 @@ Parameters
|
||||
</td>
|
||||
<td>
|
||||
<div>When upgrading package, reset the values to the ones built into the chart.</div>
|
||||
<div>Defaults to V(true), which makes helm ignore O(reuse_values) and O(reset_then_reuse_values). Set it to V(false) to use either of them.</div>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
@@ -563,8 +589,10 @@ Parameters
|
||||
</ul>
|
||||
</td>
|
||||
<td>
|
||||
<div>When upgrading package, specifies wether to reuse the last release's values and merge in any overrides from parameters <em>release_values</em>, <em>values_files</em> or <em>set_values</em>.</div>
|
||||
<div>If <em>reset_values</em> is set to <code>True</code>, this is ignored.</div>
|
||||
<div>When upgrading package, specifies whether to reuse the last release's values and merge in any overrides from parameters O(release_values), O(values_files) or O(set_values).</div>
|
||||
<div>Helm ignores this when <code>--reset-values</code> is passed. Since O(reset_values) defaults to V(true), it has to be set to V(false) for this option to take any effect.</div>
|
||||
<div><code>helm install</code> does not accept <code>--reuse-values</code>, so this option is ignored when O(replace) is set.</div>
|
||||
<div>The module warns whenever one of those combinations makes this option a no-op.</div>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
@@ -811,6 +839,28 @@ Parameters
|
||||
<div>When <em>release_state</em> is set to <code>absent</code>, will wait until all the resources are deleted before returning. It will wait for as long as <em>wait_timeout</em>. This feature requires helm>=3.7.0. Added in version 2.3.0.</div>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="2">
|
||||
<div class="ansibleOptionAnchor" id="parameter-"></div>
|
||||
<b>wait_for_jobs</b>
|
||||
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
|
||||
<div style="font-size: small">
|
||||
<span style="color: purple">boolean</span>
|
||||
</div>
|
||||
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.6.0</div>
|
||||
</td>
|
||||
<td>
|
||||
<ul style="margin: 0; padding: 0"><b>Choices:</b>
|
||||
<li><div style="color: blue"><b>no</b> ←</div></li>
|
||||
<li>yes</li>
|
||||
</ul>
|
||||
</td>
|
||||
<td>
|
||||
<div>When <em>release_state</em> is set to <code>present</code>, and <em>wait</em> is set to <code>True</code>, wait until all jobs are in a completed state before marking the release as successful.</div>
|
||||
<div>Ignored when used without O(wait).</div>
|
||||
<div>Requires Helm >= 3.5.0</div>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="2">
|
||||
<div class="ansibleOptionAnchor" id="parameter-"></div>
|
||||
@@ -824,7 +874,7 @@ Parameters
|
||||
</td>
|
||||
<td>
|
||||
<div>Timeout when wait option is enabled (helm2 is a number of seconds, helm3 is a duration).</div>
|
||||
<div>The use of <em>wait_timeout</em> to wait for kubernetes commands to complete has been deprecated and will be removed after 2022-12-01.</div>
|
||||
<div>The use of <em>wait_timeout</em> to wait for kubernetes commands to complete has been deprecated and will be removed in version 7.0.0. Use O(timeout) instead.</div>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
@@ -935,6 +985,7 @@ Examples
|
||||
release_namespace: default
|
||||
force: True
|
||||
wait: True
|
||||
wait_for_jobs: True
|
||||
replace: True
|
||||
update_repo_cache: True
|
||||
disable_hook: True
|
||||
@@ -954,16 +1005,31 @@ Examples
|
||||
enabled: True
|
||||
|
||||
# Deploy latest version
|
||||
# 'reset_values' defaults to true and helm ignores '--reuse-values' when it is set,
|
||||
# so it has to be turned off explicitly.
|
||||
- name: Deploy latest version of Grafana chart using reuse_values
|
||||
kubernetes.core.helm:
|
||||
name: test
|
||||
chart_ref: stable/grafana
|
||||
release_namespace: monitoring
|
||||
reuse_values: true
|
||||
reset_values: false
|
||||
values:
|
||||
replicas: 2
|
||||
version: 3e8ec0b2dffa40fb97d5342e4af887de95faa8c61a62480dd7f8aa03dffcf533
|
||||
|
||||
# Same for 'reset_then_reuse_values', which helm ignores when either
|
||||
# '--reset-values' or '--reuse-values' is set.
|
||||
- name: Deploy latest version of Grafana chart using reset_then_reuse_values
|
||||
kubernetes.core.helm:
|
||||
name: test
|
||||
chart_ref: stable/grafana
|
||||
release_namespace: monitoring
|
||||
reset_then_reuse_values: true
|
||||
reset_values: false
|
||||
values:
|
||||
replicas: 2
|
||||
|
||||
|
||||
|
||||
Return Values
|
||||
@@ -1152,7 +1218,7 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
|
||||
<td>always</td>
|
||||
<td>
|
||||
<div>Dict of Values used to deploy.</div>
|
||||
<div>This return value has been deprecated and will be removed in a release after 2027-01-08. Use RV(status.release_values) instead.</div>
|
||||
<div>This return value has been deprecated and will be removed in version 8.0.0. Use RV(status.release_values) instead.</div>
|
||||
<br/>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@@ -152,6 +152,25 @@ Parameters
|
||||
<div>The name of a context found in the config file. Can also be specified via K8S_AUTH_CONTEXT environment variable.</div>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="2">
|
||||
<div class="ansibleOptionAnchor" id="parameter-"></div>
|
||||
<b>copy_timeout</b>
|
||||
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
|
||||
<div style="font-size: small">
|
||||
<span style="color: purple">integer</span>
|
||||
</div>
|
||||
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.6.0</div>
|
||||
</td>
|
||||
<td>
|
||||
<b>Default:</b><br/><div style="color: blue">300</div>
|
||||
</td>
|
||||
<td>
|
||||
<div>Maximum time in seconds to spend streaming the archive to the pod and waiting for the remote <code>tar</code> process to finish extracting it.</div>
|
||||
<div>Raise this when copying large files over a slow connection.</div>
|
||||
<div>This option is ignored when <em>state</em> is set to <code>from_pod</code>.</div>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="2">
|
||||
<div class="ansibleOptionAnchor" id="parameter-"></div>
|
||||
@@ -512,6 +531,7 @@ Notes
|
||||
|
||||
.. note::
|
||||
- the tar binary is required on the container when copying from local filesystem to pod.
|
||||
- a POSIX shell at ``/bin/sh`` and ``head`` are also used, when present, to bound the archive sent to the container so that the module can confirm the copy finished. Without them the copy still runs but completion cannot be verified, and a warning is emitted.
|
||||
- the (init) container has to be started before you copy files or directories to it.
|
||||
- To avoid SSL certificate validation errors when ``validate_certs`` is *True*, the full certificate chain for the API server must be provided via ``ca_cert`` or in the kubeconfig file.
|
||||
|
||||
|
||||
@@ -535,7 +535,7 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
|
||||
</td>
|
||||
<td></td>
|
||||
<td>
|
||||
<div>The command status code. This attribute is deprecated and will be removed in a future release. Please use rc instead.</div>
|
||||
<div>The command status code. This attribute is deprecated and will be removed in version 7.0.0. Use RV(result.rc) instead.</div>
|
||||
<br/>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@@ -280,6 +280,29 @@ Parameters
|
||||
<div>List of label selectors to use to filter results</div>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="2">
|
||||
<div class="ansibleOptionAnchor" id="parameter-"></div>
|
||||
<b>metadata_only</b>
|
||||
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
|
||||
<div style="font-size: small">
|
||||
<span style="color: purple">boolean</span>
|
||||
</div>
|
||||
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.6.0</div>
|
||||
</td>
|
||||
<td>
|
||||
<ul style="margin: 0; padding: 0"><b>Choices:</b>
|
||||
<li><div style="color: blue"><b>no</b> ←</div></li>
|
||||
<li>yes</li>
|
||||
</ul>
|
||||
</td>
|
||||
<td>
|
||||
<div>Request metadata only response from the Kubernetes API server.</div>
|
||||
<div>This feature is useful for clients that only need to check for the existence of an object,</div>
|
||||
<div>or that only need to read its metadata.</div>
|
||||
<div>It can significantly reduce the size of the response from the API server.</div>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="2">
|
||||
<div class="ansibleOptionAnchor" id="parameter-"></div>
|
||||
@@ -716,6 +739,12 @@ Examples
|
||||
retries: 60
|
||||
delay: 15
|
||||
|
||||
- name: Get a list of all pods metadata only
|
||||
kubernetes.core.k8s_info:
|
||||
kind: Pod
|
||||
metadata_only: true
|
||||
register: pod_metadata_list
|
||||
|
||||
|
||||
|
||||
Return Values
|
||||
|
||||
@@ -247,6 +247,7 @@ Parameters
|
||||
<div>See <a href='https://kubernetes.io/docs/tasks/run-application/update-api-object-kubectl-patch/#use-a-json-merge-patch-to-update-a-deployment'>https://kubernetes.io/docs/tasks/run-application/update-api-object-kubectl-patch/#use-a-json-merge-patch-to-update-a-deployment</a></div>
|
||||
<div>If more than one <code>merge_type</code> is given, the merge_types will be tried in order</div>
|
||||
<div>This defaults to <code>['strategic-merge', 'merge']</code>, which is ideal for using the same parameters on resource kinds that combine Custom Resources and built-in resources.</div>
|
||||
<div><em>merge_type=json</em> has been deprecated and will be removed in version 7.0.0. Use <span class='module'>kubernetes.core.k8s_json_patch</span> instead.</div>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
|
||||
@@ -383,6 +383,7 @@ Examples
|
||||
# and requires python to be installed in the image
|
||||
- name: Run a command in a pod
|
||||
ansible.builtin.command: echo "Hello, World!"
|
||||
changed_when: false
|
||||
|
||||
- name: Run a command in a pod using local kubectl with inventory variables
|
||||
# Example inventory:
|
||||
@@ -407,6 +408,7 @@ Examples
|
||||
# and requires python to be installed in the image
|
||||
- name: Run a command in a pod
|
||||
ansible.builtin.command: echo "Hello, World!"
|
||||
changed_when: false
|
||||
|
||||
- name: Run a command in a pod using dynamic inventory
|
||||
hosts: localhost
|
||||
@@ -440,6 +442,7 @@ Examples
|
||||
# be aware that the command is executed as the user that started the container
|
||||
# and requires python to be installed in the image
|
||||
ansible.builtin.command: echo "Hello, World!"
|
||||
changed_when: false
|
||||
delegate_to: "{{ my_app_pod_name }}"
|
||||
|
||||
|
||||
|
||||
+1
-1
@@ -25,7 +25,7 @@ tags:
|
||||
- openshift
|
||||
- okd
|
||||
- cluster
|
||||
version: 6.5.0
|
||||
version: 6.6.0
|
||||
build_ignore:
|
||||
- .DS_Store
|
||||
- "*.tar.gz"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
---
|
||||
version: 3
|
||||
dependencies:
|
||||
python: requirements.txt
|
||||
system: meta/ee-bindep.txt
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
---
|
||||
requires_ansible: '>=2.16.0'
|
||||
|
||||
# Only modules that accept the shared authentication options belong in these
|
||||
# groups: HELM_AUTH_ARG_SPEC for helm, AUTH_ARG_SPEC for k8s. Adding a module
|
||||
# that does not accept them makes module_defaults fail for every user of the
|
||||
# group. This excludes helm_pull, helm_registry_auth, helm_template and
|
||||
# kubeconfig, which only take a subset (or none) of those options.
|
||||
action_groups:
|
||||
helm:
|
||||
- helm
|
||||
- helm_info
|
||||
- helm_plugin
|
||||
- helm_plugin_info
|
||||
- helm_repository
|
||||
k8s:
|
||||
- k8s
|
||||
@@ -18,6 +25,7 @@ action_groups:
|
||||
- k8s_rollback
|
||||
- k8s_scale
|
||||
- k8s_service
|
||||
- k8s_taint
|
||||
|
||||
plugin_routing:
|
||||
inventory:
|
||||
|
||||
@@ -35,7 +35,11 @@ def _from_yaml_to_definition(buffer):
|
||||
import yaml
|
||||
except ImportError:
|
||||
raise AnsibleError("Failed to import the required Python library (PyYAML).")
|
||||
return list(yaml.safe_load_all(buffer))
|
||||
|
||||
# Handle empty template output
|
||||
if buffer is None:
|
||||
return []
|
||||
return [doc for doc in yaml.safe_load_all(buffer) if doc is not None]
|
||||
|
||||
|
||||
ENV_KUBECONFIG_PATH_SEPARATOR = ";" if platform.system() == "Windows" else ":"
|
||||
@@ -380,10 +384,15 @@ class ActionModule(ActionBase):
|
||||
template = self._task.args.get("template", None)
|
||||
if template:
|
||||
self.load_template(template, new_module_args, task_vars)
|
||||
# If template rendered to empty definition, return early with no changes
|
||||
if not new_module_args.get("definition"):
|
||||
result["changed"] = False
|
||||
return self._ensure_invocation(result)
|
||||
|
||||
local_path = self._task.args.get("local_path")
|
||||
state = self._task.args.get("state", None)
|
||||
if local_path and state == "to_pod" and not remote_transport:
|
||||
is_local_pod_upload = local_path and state == "to_pod" and not remote_transport
|
||||
if is_local_pod_upload:
|
||||
new_module_args["local_path"] = self.get_file_realpath(local_path)
|
||||
|
||||
# Execute the k8s_* module.
|
||||
|
||||
@@ -196,6 +196,7 @@ EXAMPLES = r"""
|
||||
# and requires python to be installed in the image
|
||||
- name: Run a command in a pod
|
||||
ansible.builtin.command: echo "Hello, World!"
|
||||
changed_when: false
|
||||
|
||||
- name: Run a command in a pod using local kubectl with inventory variables
|
||||
# Example inventory:
|
||||
@@ -220,6 +221,7 @@ EXAMPLES = r"""
|
||||
# and requires python to be installed in the image
|
||||
- name: Run a command in a pod
|
||||
ansible.builtin.command: echo "Hello, World!"
|
||||
changed_when: false
|
||||
|
||||
- name: Run a command in a pod using dynamic inventory
|
||||
hosts: localhost
|
||||
@@ -253,6 +255,7 @@ EXAMPLES = r"""
|
||||
# be aware that the command is executed as the user that started the container
|
||||
# and requires python to be installed in the image
|
||||
ansible.builtin.command: echo "Hello, World!"
|
||||
changed_when: false
|
||||
delegate_to: "{{ my_app_pod_name }}"
|
||||
"""
|
||||
|
||||
@@ -262,11 +265,11 @@ import os.path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
from shlex import quote as shlex_quote
|
||||
|
||||
from ansible.errors import AnsibleError, AnsibleFileNotFound
|
||||
from ansible.module_utils.common.text.converters import to_bytes
|
||||
from ansible.module_utils.parsing.convert_bool import boolean
|
||||
from ansible.module_utils.six.moves import shlex_quote
|
||||
from ansible.parsing.yaml.loader import AnsibleLoader
|
||||
from ansible.plugins.connection import BUFSIZE, ConnectionBase
|
||||
from ansible.utils.display import Display
|
||||
|
||||
+33
-1
@@ -209,28 +209,60 @@ RETURN = """
|
||||
"""
|
||||
|
||||
import os
|
||||
from collections.abc import KeysView
|
||||
|
||||
from ansible.errors import AnsibleError
|
||||
from ansible.module_utils.common._collections_compat import KeysView
|
||||
from ansible.module_utils.ansible_release import __version__ as ansible_version
|
||||
from ansible.module_utils.common.validation import check_type_bool
|
||||
from ansible.utils.display import Display
|
||||
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
|
||||
get_api_client,
|
||||
)
|
||||
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.resource import (
|
||||
create_definitions,
|
||||
)
|
||||
from ansible_collections.kubernetes.core.plugins.module_utils.version import (
|
||||
LooseVersion,
|
||||
)
|
||||
|
||||
display = Display()
|
||||
|
||||
# cloud.common declares requires_ansible '>=2.15.0,<2.19'. On newer ansible-core the
|
||||
# import still succeeds, so the version has to be checked explicitly: relying on
|
||||
# ImportError alone lets turbo mode fail later with an unrelated traceback.
|
||||
TURBO_UNSUPPORTED_CORE = "2.19.0"
|
||||
|
||||
try:
|
||||
enable_turbo_mode = check_type_bool(os.environ.get("ENABLE_TURBO_MODE"))
|
||||
except TypeError:
|
||||
enable_turbo_mode = False
|
||||
|
||||
if enable_turbo_mode:
|
||||
display.deprecated(
|
||||
"ENABLE_TURBO_MODE is deprecated, as it relies on the cloud.common "
|
||||
"collection which is being retired. Setting this environment "
|
||||
"variable will have no effect once support is removed.",
|
||||
version="8.0.0",
|
||||
collection_name="kubernetes.core",
|
||||
)
|
||||
if LooseVersion(ansible_version) >= LooseVersion(TURBO_UNSUPPORTED_CORE):
|
||||
display.warning(
|
||||
"ENABLE_TURBO_MODE is ignored on ansible-core %s: Ansible Turbo mode requires "
|
||||
"the cloud.common collection, which supports ansible-core < %s only. "
|
||||
"Continuing without Turbo mode." % (ansible_version, TURBO_UNSUPPORTED_CORE)
|
||||
)
|
||||
enable_turbo_mode = False
|
||||
|
||||
if enable_turbo_mode:
|
||||
try:
|
||||
from ansible_collections.cloud.common.plugins.plugin_utils.turbo.lookup import (
|
||||
TurboLookupBase as LookupBase,
|
||||
)
|
||||
except ImportError:
|
||||
display.warning(
|
||||
"ENABLE_TURBO_MODE is set but the cloud.common collection is not installed. "
|
||||
"Continuing without Turbo mode."
|
||||
)
|
||||
from ansible.plugins.lookup import LookupBase # noqa: F401
|
||||
else:
|
||||
from ansible.plugins.lookup import LookupBase # noqa: F401
|
||||
|
||||
@@ -5,13 +5,39 @@ __metaclass__ = type
|
||||
|
||||
import os
|
||||
|
||||
from ansible.module_utils.ansible_release import __version__ as ansible_version
|
||||
from ansible.module_utils.common.validation import check_type_bool
|
||||
from ansible.module_utils.common.warnings import deprecate, warn
|
||||
from ansible_collections.kubernetes.core.plugins.module_utils.version import (
|
||||
LooseVersion,
|
||||
)
|
||||
|
||||
# cloud.common declares requires_ansible '>=2.15.0,<2.19'. On newer ansible-core the
|
||||
# import still succeeds, so the version has to be checked explicitly: relying on
|
||||
# ImportError alone lets turbo mode fail later with an unrelated traceback.
|
||||
TURBO_UNSUPPORTED_CORE = "2.19.0"
|
||||
|
||||
try:
|
||||
enable_turbo_mode = check_type_bool(os.environ.get("ENABLE_TURBO_MODE"))
|
||||
except TypeError:
|
||||
enable_turbo_mode = False
|
||||
|
||||
if enable_turbo_mode:
|
||||
deprecate(
|
||||
"ENABLE_TURBO_MODE is deprecated, as it relies on the cloud.common collection "
|
||||
"which is being retired. Setting this environment variable will have no effect "
|
||||
"once support is removed.",
|
||||
version="8.0.0",
|
||||
collection_name="kubernetes.core",
|
||||
)
|
||||
if LooseVersion(ansible_version) >= LooseVersion(TURBO_UNSUPPORTED_CORE):
|
||||
warn(
|
||||
"ENABLE_TURBO_MODE is ignored on ansible-core %s: Ansible Turbo mode requires "
|
||||
"the cloud.common collection, which supports ansible-core < %s only. "
|
||||
"Continuing without Turbo mode." % (ansible_version, TURBO_UNSUPPORTED_CORE)
|
||||
)
|
||||
enable_turbo_mode = False
|
||||
|
||||
if enable_turbo_mode:
|
||||
try:
|
||||
from ansible_collections.cloud.common.plugins.module_utils.turbo.module import ( # noqa: F401
|
||||
@@ -20,6 +46,10 @@ if enable_turbo_mode:
|
||||
|
||||
AnsibleModule.collection_name = "kubernetes.core"
|
||||
except ImportError:
|
||||
warn(
|
||||
"ENABLE_TURBO_MODE is set but the cloud.common collection is not installed. "
|
||||
"Continuing without Turbo mode."
|
||||
)
|
||||
from ansible.module_utils.basic import AnsibleModule # noqa: F401
|
||||
else:
|
||||
from ansible.module_utils.basic import AnsibleModule # noqa: F401
|
||||
|
||||
@@ -144,3 +144,18 @@ DELETE_OPTS_ARG_SPEC = {
|
||||
"options": {"resourceVersion": {"type": "str"}, "uid": {"type": "str"}},
|
||||
},
|
||||
}
|
||||
|
||||
METADATA_ONLY_HEADERS_SPEC = {
|
||||
"accept": {"type": "str"},
|
||||
}
|
||||
|
||||
METADATA_ONLY_HEADER_VALUES = {
|
||||
"partial_object": (
|
||||
"application/json;as=PartialObjectMetadata;g=meta.k8s.io;v=v1,"
|
||||
"application/json;q=0.9"
|
||||
),
|
||||
"partial_object_list": (
|
||||
"application/json;as=PartialObjectMetadataList;g=meta.k8s.io;v=v1,"
|
||||
"application/json;q=0.9"
|
||||
),
|
||||
}
|
||||
|
||||
+178
-53
@@ -18,7 +18,9 @@ from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
import os
|
||||
import shlex
|
||||
import tarfile
|
||||
import time
|
||||
from abc import ABCMeta, abstractmethod
|
||||
from select import select
|
||||
from tempfile import NamedTemporaryFile, TemporaryFile
|
||||
@@ -296,14 +298,156 @@ class K8SCopyToPod(K8SCopy):
|
||||
Copy files/directory from local filesystem into remote Pod
|
||||
"""
|
||||
|
||||
# Size of the chunks the tar archive is written to stdin with.
|
||||
CHUNK_SIZE = 1024 * 1024
|
||||
SHELL = "/bin/sh"
|
||||
|
||||
def __init__(self, module, client):
|
||||
super(K8SCopyToPod, self).__init__(module, client)
|
||||
self.files_to_copy = list()
|
||||
self.named_temp_file = None
|
||||
self.copy_timeout = module.params.get("copy_timeout")
|
||||
|
||||
def close_temp_file(self):
|
||||
if self.named_temp_file:
|
||||
self.named_temp_file.close()
|
||||
|
||||
def _fail(self, response, msg, stderr=(), **kwargs):
|
||||
"""Fail, keeping whatever the remote already wrote to stderr.
|
||||
|
||||
An early close or a stall is usually the symptom, not the cause: tar
|
||||
has typically said why on stderr first.
|
||||
"""
|
||||
if stderr:
|
||||
msg = "{0}: {1}".format(msg, "".join(stderr))
|
||||
response.close()
|
||||
self.close_temp_file()
|
||||
self.module.fail_json(
|
||||
msg="Failed to copy local file/directory into Pod: {0}".format(msg),
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def tar_command(self, dest_file):
|
||||
if self.no_preserve:
|
||||
command = [
|
||||
"tar",
|
||||
"--no-same-permissions",
|
||||
"--no-same-owner",
|
||||
"-xmf",
|
||||
"-",
|
||||
]
|
||||
else:
|
||||
command = ["tar", "-xmf", "-"]
|
||||
|
||||
if dest_file.startswith("/"):
|
||||
command.extend(["-C", "/"])
|
||||
return command
|
||||
|
||||
def can_bound_stream(self):
|
||||
"""Whether the container can run ``sh -c 'head -c ...'``."""
|
||||
error, _out, _err = self._run_from_pod(
|
||||
cmd=[self.SHELL, "-c", "command -v head"]
|
||||
)
|
||||
return (error or {}).get("status") == "Success"
|
||||
|
||||
def remote_command(self, dest_file, archive_size):
|
||||
"""Build the command that extracts the archive inside the container.
|
||||
|
||||
The websocket exec protocol the kubernetes client speaks (v4) cannot
|
||||
half-close stdin, so the only EOF the remote process can get is the
|
||||
connection going away. Relying on that races with tar finishing and
|
||||
truncates the file (issue #776), and tar cannot be relied on to stop at
|
||||
the end-of-archive marker either -- busybox tar blocks for EOF.
|
||||
|
||||
Piping through ``head -c`` bounds the stream at the exact archive size,
|
||||
so tar sees a clean EOF, exits on its own, and the API server reports
|
||||
its exit status on the error channel. Only where the container has no
|
||||
shell do we fall back to feeding tar directly, which cannot confirm
|
||||
that the copy completed.
|
||||
"""
|
||||
command = self.tar_command(dest_file)
|
||||
if not self.can_bound_stream():
|
||||
self.module.warn(
|
||||
"Container has no '{0}' with 'head', falling back to writing the"
|
||||
" archive straight to tar. The module cannot confirm the copy"
|
||||
" completed; verify the file after copying.".format(self.SHELL)
|
||||
)
|
||||
return command, False
|
||||
|
||||
return [
|
||||
self.SHELL,
|
||||
"-c",
|
||||
"head -c {0} | {1}".format(
|
||||
archive_size, " ".join(shlex.quote(arg) for arg in command)
|
||||
),
|
||||
], True
|
||||
|
||||
def _stream_tar_to_pod(self, response, tar_buffer, wait_for_exit):
|
||||
"""Feed the archive to the remote extractor and wait for it to finish.
|
||||
|
||||
Writing the last chunk only hands the bytes to the local socket; they
|
||||
still have to cross the API server and reach the container. Closing the
|
||||
connection at that point kills the extractor mid-write and silently
|
||||
truncates the file, which is what issue #776 reports.
|
||||
"""
|
||||
stdout, stderr = [], []
|
||||
|
||||
def drain(timeout):
|
||||
response.update(timeout=timeout)
|
||||
if response.peek_stdout():
|
||||
stdout.append(response.read_stdout().rstrip("\n"))
|
||||
if response.peek_stderr():
|
||||
stderr.append(response.read_stderr().rstrip("\n"))
|
||||
|
||||
deadline = time.monotonic() + self.copy_timeout
|
||||
|
||||
chunk = tar_buffer.read(self.CHUNK_SIZE)
|
||||
while chunk:
|
||||
if not response.is_open():
|
||||
self._fail(
|
||||
response,
|
||||
"connection to Pod {0}/{1} closed before the whole archive was"
|
||||
" sent, the remote file is incomplete".format(
|
||||
self.namespace, self.name
|
||||
),
|
||||
stderr,
|
||||
)
|
||||
if time.monotonic() > deadline:
|
||||
self._fail(
|
||||
response,
|
||||
"timed out after {0}s sending the archive to Pod {1}/{2}".format(
|
||||
self.copy_timeout, self.namespace, self.name
|
||||
),
|
||||
stderr,
|
||||
)
|
||||
# Non-blocking, keeps the receive buffer clear while we write.
|
||||
drain(0)
|
||||
response.write_stdin(chunk)
|
||||
chunk = tar_buffer.read(self.CHUNK_SIZE)
|
||||
|
||||
if not wait_for_exit:
|
||||
# No way to make the extractor exit, so no status to collect: read
|
||||
# whatever it has already said and close, as the module always did.
|
||||
drain(0)
|
||||
response.close()
|
||||
return None, stdout, stderr
|
||||
|
||||
# The archive is on the wire; wait for the extractor to consume it,
|
||||
# exit, and have its status reported on the error channel.
|
||||
while response.is_open():
|
||||
if time.monotonic() > deadline:
|
||||
self._fail(
|
||||
response,
|
||||
"timed out after {0}s waiting for tar to finish extracting on Pod"
|
||||
" {1}/{2}".format(self.copy_timeout, self.namespace, self.name),
|
||||
stderr,
|
||||
)
|
||||
drain(1)
|
||||
|
||||
error = yaml.safe_load(response.read_channel(ERROR_CHANNEL)) or {}
|
||||
response.close()
|
||||
return error, stdout, stderr
|
||||
|
||||
def run(self):
|
||||
# remove trailing slash from destination path
|
||||
dest_file = self.remote_path.rstrip("/")
|
||||
@@ -336,65 +480,46 @@ class K8SCopyToPod(K8SCopy):
|
||||
dest_file = os.path.join(dest_file, os.path.basename(src_file))
|
||||
|
||||
if not self.check_mode:
|
||||
if self.no_preserve:
|
||||
tar_command = [
|
||||
"tar",
|
||||
"--no-same-permissions",
|
||||
"--no-same-owner",
|
||||
"-xmf",
|
||||
"-",
|
||||
]
|
||||
else:
|
||||
tar_command = ["tar", "-xmf", "-"]
|
||||
|
||||
if dest_file.startswith("/"):
|
||||
tar_command.extend(["-C", "/"])
|
||||
|
||||
response = stream(
|
||||
self.api_instance.connect_get_namespaced_pod_exec,
|
||||
self.name,
|
||||
self.namespace,
|
||||
command=tar_command,
|
||||
stderr=True,
|
||||
stdin=True,
|
||||
stdout=True,
|
||||
tty=False,
|
||||
_preload_content=False,
|
||||
**self.container_arg,
|
||||
)
|
||||
with TemporaryFile() as tar_buffer:
|
||||
# Build the archive first: bounding the remote read needs its
|
||||
# exact size.
|
||||
with tarfile.open(fileobj=tar_buffer, mode="w") as tar:
|
||||
tar.add(src_file, dest_file)
|
||||
archive_size = tar_buffer.tell()
|
||||
tar_buffer.seek(0)
|
||||
commands = []
|
||||
# push command in chunk mode
|
||||
size = 1024 * 1024
|
||||
while True:
|
||||
data = tar_buffer.read(size)
|
||||
if not data:
|
||||
break
|
||||
commands.append(data)
|
||||
|
||||
stderr, stdout = [], []
|
||||
while response.is_open():
|
||||
if response.peek_stdout():
|
||||
stdout.append(response.read_stdout().rstrip("\n"))
|
||||
if response.peek_stderr():
|
||||
stderr.append(response.read_stderr().rstrip("\n"))
|
||||
if commands:
|
||||
cmd = commands.pop(0)
|
||||
response.write_stdin(cmd)
|
||||
else:
|
||||
break
|
||||
response.close()
|
||||
if stderr:
|
||||
self.close_temp_file()
|
||||
self.module.fail_json(
|
||||
command=tar_command,
|
||||
msg="Failed to copy local file/directory into Pod due to: {0}".format(
|
||||
"".join(stderr)
|
||||
),
|
||||
command, wait_for_exit = self.remote_command(dest_file, archive_size)
|
||||
response = stream(
|
||||
self.api_instance.connect_get_namespaced_pod_exec,
|
||||
self.name,
|
||||
self.namespace,
|
||||
command=command,
|
||||
stderr=True,
|
||||
stdin=True,
|
||||
stdout=True,
|
||||
tty=False,
|
||||
_preload_content=False,
|
||||
**self.container_arg,
|
||||
)
|
||||
error, stdout, stderr = self._stream_tar_to_pod(
|
||||
response, tar_buffer, wait_for_exit
|
||||
)
|
||||
|
||||
if error is not None and error.get("status") != "Success":
|
||||
self._fail(
|
||||
response,
|
||||
"".join(stderr) or error.get("message", "unknown error"),
|
||||
command=command,
|
||||
)
|
||||
if error is None and stderr:
|
||||
# Legacy path: no exit status to go on, so any output is fatal.
|
||||
self._fail(response, "".join(stderr), command=command)
|
||||
if stderr:
|
||||
self.module.warn(
|
||||
"tar wrote to stderr while extracting into Pod {0}/{1}: {2}".format(
|
||||
self.namespace, self.name, "".join(stderr)
|
||||
)
|
||||
)
|
||||
self.close_temp_file()
|
||||
if self.content:
|
||||
self.module.exit_json(
|
||||
|
||||
@@ -32,6 +32,53 @@ except ImportError:
|
||||
HAS_YAML = False
|
||||
|
||||
|
||||
# Helm's registry client writes these progress messages to stdout as of helm 4.2.1
|
||||
# (helm/helm#32056); earlier versions sent them to stderr. Anything that parses the
|
||||
# stdout of a helm command which may pull from an OCI registry has to skip them.
|
||||
# Kept verbatim from helm's pkg/registry/client.go so that a reworded message fails
|
||||
# to match, and therefore fails loudly, rather than silently eating real output.
|
||||
REGISTRY_PROGRESS_RE = re.compile(r"^(?:Pulled|Pushed|Digest): \S")
|
||||
|
||||
REGISTRY_UNDERSCORE_SUFFIX = " contains an underscore.\n"
|
||||
|
||||
REGISTRY_UNDERSCORE_MESSAGE = """
|
||||
OCI artifact references (e.g. tags) do not support the plus sign (+). To support
|
||||
storing semantic versions, Helm adopts the convention of changing plus (+) to
|
||||
an underscore (_) in chart version tags when pushing to a registry and back to
|
||||
a plus (+) when pulling from a registry.
|
||||
"""
|
||||
|
||||
REGISTRY_UNDERSCORE_MESSAGE_LINES = len(REGISTRY_UNDERSCORE_MESSAGE.splitlines())
|
||||
|
||||
|
||||
def strip_registry_progress(out):
|
||||
"""
|
||||
Drop OCI registry progress messages from the front of a helm command's stdout.
|
||||
|
||||
Helm emits 'Pulled:'/'Pushed:' and 'Digest:' lines, followed - when the
|
||||
reference contains an underscore - by a free-text explanation that is not
|
||||
valid YAML. Since helm 4.2.1 these land on stdout ahead of the real output,
|
||||
so 'helm show chart' can no longer be parsed and 'helm template' no longer
|
||||
returns only rendered manifests.
|
||||
"""
|
||||
lines = out.splitlines(keepends=True)
|
||||
index = 0
|
||||
while index < len(lines):
|
||||
if REGISTRY_PROGRESS_RE.match(lines[index]):
|
||||
index += 1
|
||||
elif lines[index].endswith(REGISTRY_UNDERSCORE_SUFFIX):
|
||||
# helm prints its registryUnderscoreMessage right after this line, led
|
||||
# by a blank line. Anything else is not a message we know about.
|
||||
start = index + 1
|
||||
end = start + REGISTRY_UNDERSCORE_MESSAGE_LINES
|
||||
if "".join(lines[start:end]) != REGISTRY_UNDERSCORE_MESSAGE:
|
||||
break
|
||||
index = end
|
||||
else:
|
||||
break
|
||||
return "".join(lines[index:])
|
||||
|
||||
|
||||
def parse_helm_plugin_list(output=None):
|
||||
"""
|
||||
Parse `helm plugin list`, return list of plugins
|
||||
|
||||
@@ -181,6 +181,7 @@ def _create_headers(module=None, **kwargs):
|
||||
header_map = {
|
||||
"impersonate_user": "Impersonate-User",
|
||||
"impersonate_groups": "Impersonate-Group",
|
||||
"accept": "Accept",
|
||||
}
|
||||
|
||||
headers = {}
|
||||
|
||||
@@ -47,6 +47,18 @@ def pod_ready(pod: ResourceInstance) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def job_complete(job: ResourceInstance) -> bool:
|
||||
return bool(
|
||||
job.status
|
||||
and job.status.conditions
|
||||
and any(
|
||||
condition["type"] in ("Complete", "Failed")
|
||||
and boolean(condition["status"], strict=False)
|
||||
for condition in job.status.conditions
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def daemonset_ready(daemonset: ResourceInstance) -> bool:
|
||||
return bool(
|
||||
daemonset.status
|
||||
@@ -89,18 +101,18 @@ def custom_condition(condition: Dict, resource: ResourceInstance) -> bool:
|
||||
if not matches:
|
||||
return False
|
||||
# There should never be more than one condition of a specific type
|
||||
match: ResourceField = matches[0]
|
||||
if match.status == "Unknown":
|
||||
if match.status == condition["status"]:
|
||||
match_condition: ResourceField = matches[0]
|
||||
if match_condition.status == "Unknown":
|
||||
if match_condition.status == condition["status"]:
|
||||
if "reason" not in condition:
|
||||
return True
|
||||
if condition["reason"]:
|
||||
return match.reason == condition["reason"]
|
||||
return match_condition.reason == condition["reason"]
|
||||
return False
|
||||
status = True if match.status == "True" else False
|
||||
status = True if match_condition.status == "True" else False
|
||||
if status == boolean(condition["status"], strict=False):
|
||||
if condition.get("reason"):
|
||||
return match.reason == condition["reason"]
|
||||
return match_condition.reason == condition["reason"]
|
||||
return True
|
||||
return False
|
||||
|
||||
@@ -143,6 +155,7 @@ RESOURCE_PREDICATES = {
|
||||
"DaemonSet": daemonset_ready,
|
||||
"Deployment": deployment_ready,
|
||||
"Pod": pod_ready,
|
||||
"Job": job_complete,
|
||||
"StatefulSet": statefulset_ready,
|
||||
"ClusterOperator": cluster_operator_ready,
|
||||
}
|
||||
|
||||
@@ -15,4 +15,6 @@ __metaclass__ = type
|
||||
#
|
||||
# from ansible.module_utils.compat.version import LooseVersion
|
||||
|
||||
from ._version import LooseVersion # noqa: F401
|
||||
from ._version import LooseVersion # noqa: F401 # pylint: disable=unused-import
|
||||
|
||||
__all__ = ["LooseVersion"]
|
||||
|
||||
+217
-61
@@ -132,15 +132,19 @@ options:
|
||||
version_added: 2.4.0
|
||||
reuse_values:
|
||||
description:
|
||||
- When upgrading package, specifies wether to reuse the last release's values and merge in any overrides from parameters I(release_values),
|
||||
I(values_files) or I(set_values).
|
||||
- If I(reset_values) is set to C(True), this is ignored.
|
||||
- When upgrading package, specifies whether to reuse the last release's values and merge in any overrides from parameters O(release_values),
|
||||
O(values_files) or O(set_values).
|
||||
- Helm ignores this when C(--reset-values) is passed. Since O(reset_values) defaults to V(true), it has to be set to V(false)
|
||||
for this option to take any effect.
|
||||
- C(helm install) does not accept C(--reuse-values), so this option is ignored when O(replace) is set.
|
||||
- The module warns whenever one of those combinations makes this option a no-op.
|
||||
type: bool
|
||||
required: false
|
||||
version_added: 3.0.0
|
||||
reset_values:
|
||||
description:
|
||||
- When upgrading package, reset the values to the ones built into the chart.
|
||||
- Defaults to V(true), which makes helm ignore O(reuse_values) and O(reset_then_reuse_values). Set it to V(false) to use either of them.
|
||||
type: bool
|
||||
required: false
|
||||
default: True
|
||||
@@ -149,7 +153,10 @@ options:
|
||||
description:
|
||||
- When upgrading package, reset the values to the ones built into the chart, apply the last release's values and merge in any overrides from
|
||||
parameters O(release_values), O(values_files) or O(set_values).
|
||||
- If O(reset_values) or O(reuse_values) is set to V(True), this is ignored.
|
||||
- Helm ignores this when C(--reset-values) or C(--reuse-values) is passed. Since O(reset_values) defaults to V(true), it has to be
|
||||
set to V(false), and O(reuse_values) left unset or V(false), for this option to take any effect.
|
||||
- C(helm install) does not accept C(--reset-then-reuse-values), so this option is ignored when O(replace) is set.
|
||||
- The module warns whenever one of those combinations makes this option a no-op.
|
||||
- This feature requires helm diff >= 3.9.12.
|
||||
type: bool
|
||||
required: false
|
||||
@@ -187,10 +194,19 @@ options:
|
||||
It will wait for as long as I(wait_timeout). This feature requires helm>=3.7.0. Added in version 2.3.0.
|
||||
default: False
|
||||
type: bool
|
||||
wait_for_jobs:
|
||||
description:
|
||||
- When I(release_state) is set to C(present), and I(wait) is set to C(True), wait until all jobs are in a
|
||||
completed state before marking the release as successful.
|
||||
- Ignored when used without O(wait).
|
||||
- Requires Helm >= 3.5.0
|
||||
version_added: 6.6.0
|
||||
default: False
|
||||
type: bool
|
||||
wait_timeout:
|
||||
description:
|
||||
- Timeout when wait option is enabled (helm2 is a number of seconds, helm3 is a duration).
|
||||
- The use of I(wait_timeout) to wait for kubernetes commands to complete has been deprecated and will be removed after 2022-12-01.
|
||||
- The use of I(wait_timeout) to wait for kubernetes commands to complete has been deprecated and will be removed in version 7.0.0. Use O(timeout) instead.
|
||||
type: str
|
||||
timeout:
|
||||
description:
|
||||
@@ -207,6 +223,18 @@ options:
|
||||
O(atomic) option works the same way regardless of the installed Helm version.
|
||||
type: bool
|
||||
default: False
|
||||
cleanup_on_fail:
|
||||
description:
|
||||
- Allow deletion of new resources created during a failed upgrade.
|
||||
- Maps to the C(--cleanup-on-fail) flag, which is available since helm 3.0.0 and
|
||||
was not renamed in Helm v4.
|
||||
- Complements O(atomic) rather than replacing it, and the two can be combined so
|
||||
that a rollback also drops resources orphaned by the failed upgrade.
|
||||
- Helm only accepts this flag on C(helm upgrade), so it cannot be used together
|
||||
with O(replace), which deploys through C(helm install).
|
||||
type: bool
|
||||
default: False
|
||||
version_added: 6.6.0
|
||||
server_side:
|
||||
description:
|
||||
- Control Helm v4 server-side apply when installing or upgrading a release.
|
||||
@@ -385,6 +413,7 @@ EXAMPLES = r"""
|
||||
release_namespace: default
|
||||
force: True
|
||||
wait: True
|
||||
wait_for_jobs: True
|
||||
replace: True
|
||||
update_repo_cache: True
|
||||
disable_hook: True
|
||||
@@ -404,15 +433,30 @@ EXAMPLES = r"""
|
||||
enabled: True
|
||||
|
||||
# Deploy latest version
|
||||
# 'reset_values' defaults to true and helm ignores '--reuse-values' when it is set,
|
||||
# so it has to be turned off explicitly.
|
||||
- name: Deploy latest version of Grafana chart using reuse_values
|
||||
kubernetes.core.helm:
|
||||
name: test
|
||||
chart_ref: stable/grafana
|
||||
release_namespace: monitoring
|
||||
reuse_values: true
|
||||
reset_values: false
|
||||
values:
|
||||
replicas: 2
|
||||
version: 3e8ec0b2dffa40fb97d5342e4af887de95faa8c61a62480dd7f8aa03dffcf533
|
||||
|
||||
# Same for 'reset_then_reuse_values', which helm ignores when either
|
||||
# '--reset-values' or '--reuse-values' is set.
|
||||
- name: Deploy latest version of Grafana chart using reset_then_reuse_values
|
||||
kubernetes.core.helm:
|
||||
name: test
|
||||
chart_ref: stable/grafana
|
||||
release_namespace: monitoring
|
||||
reset_then_reuse_values: true
|
||||
reset_values: false
|
||||
values:
|
||||
replicas: 2
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
@@ -454,8 +498,8 @@ status:
|
||||
returned: always
|
||||
description:
|
||||
- Dict of Values used to deploy.
|
||||
- This return value has been deprecated and will be removed in a release after
|
||||
2027-01-08. Use RV(status.release_values) instead.
|
||||
- This return value has been deprecated and will be removed in version 8.0.0.
|
||||
Use RV(status.release_values) instead.
|
||||
release_values:
|
||||
type: dict
|
||||
returned: always
|
||||
@@ -501,6 +545,7 @@ from ansible.module_utils.basic import missing_required_lib
|
||||
from ansible_collections.kubernetes.core.plugins.module_utils.helm import (
|
||||
AnsibleHelmModule,
|
||||
parse_helm_plugin_list,
|
||||
strip_registry_progress,
|
||||
)
|
||||
from ansible_collections.kubernetes.core.plugins.module_utils.helm_args_common import (
|
||||
HELM_AUTH_ARG_SPEC,
|
||||
@@ -548,6 +593,13 @@ def get_release_status(module, release_name, all_status=False):
|
||||
release["release_values"] = module.get_values(release_name)
|
||||
release["values"] = release["release_values"]
|
||||
|
||||
# Add deprecation warning for status.values
|
||||
module.deprecate(
|
||||
"The 'status.values' return value is deprecated and will be removed in version 8.0.0. Use 'status.release_values' instead.",
|
||||
version="8.0.0",
|
||||
collection_name="kubernetes.core",
|
||||
)
|
||||
|
||||
return release
|
||||
|
||||
|
||||
@@ -591,7 +643,52 @@ def fetch_chart_info(
|
||||
|
||||
rc, out, err = module.run_helm_command(inspect_command)
|
||||
|
||||
return yaml.safe_load(out)
|
||||
return yaml.safe_load(strip_registry_progress(out))
|
||||
|
||||
|
||||
def validate_value_options(
|
||||
module, replace, reuse_values, reset_values, reset_then_reuse_values
|
||||
):
|
||||
"""
|
||||
Check the value-reuse options against each other and against 'replace'.
|
||||
|
||||
'helm install' accepts none of these flags, so 'replace' drops all three. The rest
|
||||
are precedence rules helm applies silently: '--reset-values' wins over
|
||||
'--reuse-values', and both win over '--reset-then-reuse-values'. Since 'reset_values'
|
||||
defaults to true, requesting either of the other two on its own is a no-op.
|
||||
|
||||
Warn rather than fail throughout. Every one of these combinations is accepted by
|
||||
playbooks today: 'reuse_values' has existed since 3.0.0, and a release that is
|
||||
already converged never reaches deploy(), so the invalid command was never built.
|
||||
Failing here would turn tasks that pass today into tasks that fail.
|
||||
"""
|
||||
if replace:
|
||||
for name, requested in (
|
||||
("reuse_values", reuse_values is not None),
|
||||
("reset_then_reuse_values", reset_then_reuse_values),
|
||||
):
|
||||
if requested:
|
||||
module.warn(
|
||||
"{0} is ignored because replace=true deploys through 'helm install',"
|
||||
" which does not accept the flag.".format(name)
|
||||
)
|
||||
return
|
||||
|
||||
if reset_values:
|
||||
for name, requested in (
|
||||
("reuse_values", reuse_values),
|
||||
("reset_then_reuse_values", reset_then_reuse_values),
|
||||
):
|
||||
if requested:
|
||||
module.warn(
|
||||
"{0} is ignored because reset_values is true. "
|
||||
"Set reset_values=false to make it take effect.".format(name)
|
||||
)
|
||||
elif reuse_values and reset_then_reuse_values:
|
||||
module.warn(
|
||||
"reset_then_reuse_values is ignored because reuse_values is true. "
|
||||
"Set reuse_values=false to make it take effect."
|
||||
)
|
||||
|
||||
|
||||
def deploy(
|
||||
@@ -601,12 +698,14 @@ def deploy(
|
||||
release_values,
|
||||
chart_name,
|
||||
wait,
|
||||
wait_for_jobs,
|
||||
wait_timeout,
|
||||
disable_hook,
|
||||
force,
|
||||
values_files,
|
||||
history_max,
|
||||
atomic=False,
|
||||
cleanup_on_fail=False,
|
||||
create_namespace=False,
|
||||
replace=False,
|
||||
post_renderer=None,
|
||||
@@ -634,27 +733,41 @@ def deploy(
|
||||
deploy_command += " --dependency-update"
|
||||
else:
|
||||
deploy_command = command + " upgrade -i" # install/upgrade
|
||||
if reset_values:
|
||||
deploy_command += " --reset-values"
|
||||
if take_ownership:
|
||||
deploy_command += " --take-ownership"
|
||||
|
||||
if reuse_values is not None:
|
||||
deploy_command += " --reuse-values=" + str(reuse_values)
|
||||
# '--reset-values', '--reuse-values' and '--reset-then-reuse-values' are all
|
||||
# upgrade-only flags, so they must not leak into the 'replace' branch above.
|
||||
# validate_value_options() has already warned about that combination.
|
||||
if reset_values:
|
||||
deploy_command += " --reset-values"
|
||||
|
||||
if reset_then_reuse_values:
|
||||
helm_version = module.get_helm_version()
|
||||
if LooseVersion(helm_version) < LooseVersion("3.14.0"):
|
||||
module.fail_json(
|
||||
msg="reset_then_reuse_values requires helm >= 3.14.0, current version is {0}".format(
|
||||
helm_version
|
||||
if reuse_values is not None:
|
||||
deploy_command += " --reuse-values=" + str(reuse_values)
|
||||
|
||||
if reset_then_reuse_values:
|
||||
helm_version = module.get_helm_version()
|
||||
if LooseVersion(helm_version) < LooseVersion("3.14.0"):
|
||||
module.fail_json(
|
||||
msg="reset_then_reuse_values requires helm >= 3.14.0, current version is {0}".format(
|
||||
helm_version
|
||||
)
|
||||
)
|
||||
)
|
||||
else:
|
||||
deploy_command += " --reset-then-reuse-values"
|
||||
else:
|
||||
deploy_command += " --reset-then-reuse-values"
|
||||
|
||||
if wait:
|
||||
deploy_command += " --wait"
|
||||
if wait_for_jobs:
|
||||
helm_version = module.get_helm_version()
|
||||
if LooseVersion(helm_version) < LooseVersion("3.5.0"):
|
||||
module.fail_json(
|
||||
msg="wait_for_jobs requires helm >= 3.5.0, current version is {0}".format(
|
||||
helm_version
|
||||
)
|
||||
)
|
||||
else:
|
||||
deploy_command += " --wait-for-jobs"
|
||||
if wait_timeout is not None:
|
||||
deploy_command += " --timeout " + wait_timeout
|
||||
|
||||
@@ -667,6 +780,17 @@ def deploy(
|
||||
else:
|
||||
deploy_command += " --atomic"
|
||||
|
||||
if cleanup_on_fail:
|
||||
# '--cleanup-on-fail' is only accepted by 'helm upgrade', so it cannot be
|
||||
# combined with 'replace', which deploys through 'helm install'. The flag
|
||||
# exists since helm 3.0.0 and kept its name in v4, so no version gate is
|
||||
# needed on top of the module-wide helm >= 3.0.0 requirement.
|
||||
if replace:
|
||||
module.fail_json(
|
||||
msg="cleanup_on_fail is only supported by 'helm upgrade' and cannot be used with replace=true"
|
||||
)
|
||||
deploy_command += " --cleanup-on-fail"
|
||||
|
||||
if timeout:
|
||||
deploy_command += " --timeout " + timeout
|
||||
|
||||
@@ -865,10 +989,10 @@ def helmdiff_check(
|
||||
if set_value_args:
|
||||
cmd += " " + set_value_args
|
||||
|
||||
if reuse_values:
|
||||
if not replace and reuse_values:
|
||||
cmd += " --reuse-values"
|
||||
|
||||
if reset_then_reuse_values:
|
||||
if not replace and reset_then_reuse_values:
|
||||
helm_diff_version = get_plugin_version("diff")
|
||||
helm_version = module.get_helm_version()
|
||||
fail_msg = ""
|
||||
@@ -942,44 +1066,58 @@ def default_check(release_status, chart_info, values=None, values_files=None):
|
||||
def argument_spec():
|
||||
arg_spec = copy.deepcopy(HELM_AUTH_ARG_SPEC)
|
||||
arg_spec.update(
|
||||
dict(
|
||||
chart_ref=dict(type="path"),
|
||||
chart_repo_url=dict(type="str"),
|
||||
chart_version=dict(type="str"),
|
||||
dependency_update=dict(type="bool", default=False, aliases=["dep_up"]),
|
||||
release_name=dict(type="str", required=True, aliases=["name"]),
|
||||
release_namespace=dict(type="str", required=True, aliases=["namespace"]),
|
||||
release_state=dict(
|
||||
default="present", choices=["present", "absent"], aliases=["state"]
|
||||
),
|
||||
release_values=dict(type="dict", default={}, aliases=["values"]),
|
||||
values_files=dict(type="list", default=[], elements="str"),
|
||||
update_repo_cache=dict(type="bool", default=False),
|
||||
disable_hook=dict(type="bool", default=False),
|
||||
force=dict(type="bool", default=False),
|
||||
purge=dict(type="bool", default=True),
|
||||
wait=dict(type="bool", default=False),
|
||||
wait_timeout=dict(type="str"),
|
||||
timeout=dict(type="str"),
|
||||
atomic=dict(type="bool", default=False),
|
||||
server_side=dict(type="str", choices=["auto", "true", "false"]),
|
||||
force_conflicts=dict(type="bool", default=False),
|
||||
create_namespace=dict(type="bool", default=False),
|
||||
post_renderer=dict(type="str"),
|
||||
replace=dict(type="bool", default=False),
|
||||
skip_crds=dict(type="bool", default=False),
|
||||
history_max=dict(type="int"),
|
||||
set_values=dict(type="list", elements="dict"),
|
||||
reuse_values=dict(type="bool"),
|
||||
reset_values=dict(type="bool", default=True),
|
||||
reset_then_reuse_values=dict(type="bool", default=False),
|
||||
insecure_skip_tls_verify=dict(
|
||||
type="bool", default=False, aliases=["skip_tls_certs_check"]
|
||||
),
|
||||
plain_http=dict(type="bool", default=False),
|
||||
take_ownership=dict(type="bool", default=False),
|
||||
skip_schema_validation=dict(type="bool", default=False),
|
||||
)
|
||||
{
|
||||
"chart_ref": {"type": "path"},
|
||||
"chart_repo_url": {"type": "str"},
|
||||
"chart_version": {"type": "str"},
|
||||
"dependency_update": {
|
||||
"type": "bool",
|
||||
"default": False,
|
||||
"aliases": ["dep_up"],
|
||||
},
|
||||
"release_name": {"type": "str", "required": True, "aliases": ["name"]},
|
||||
"release_namespace": {
|
||||
"type": "str",
|
||||
"required": True,
|
||||
"aliases": ["namespace"],
|
||||
},
|
||||
"release_state": {
|
||||
"default": "present",
|
||||
"choices": ["present", "absent"],
|
||||
"aliases": ["state"],
|
||||
},
|
||||
"release_values": {"type": "dict", "default": {}, "aliases": ["values"]},
|
||||
"values_files": {"type": "list", "default": [], "elements": "str"},
|
||||
"update_repo_cache": {"type": "bool", "default": False},
|
||||
"disable_hook": {"type": "bool", "default": False},
|
||||
"force": {"type": "bool", "default": False},
|
||||
"purge": {"type": "bool", "default": True},
|
||||
"wait": {"type": "bool", "default": False},
|
||||
"wait_for_jobs": {"type": "bool", "default": False},
|
||||
"wait_timeout": {"type": "str"},
|
||||
"timeout": {"type": "str"},
|
||||
"atomic": {"type": "bool", "default": False},
|
||||
"server_side": {"type": "str", "choices": ["auto", "true", "false"]},
|
||||
"force_conflicts": {"type": "bool", "default": False},
|
||||
"create_namespace": {"type": "bool", "default": False},
|
||||
"post_renderer": {"type": "str"},
|
||||
"replace": {"type": "bool", "default": False},
|
||||
"skip_crds": {"type": "bool", "default": False},
|
||||
"history_max": {"type": "int"},
|
||||
"set_values": {"type": "list", "elements": "dict"},
|
||||
"reuse_values": {"type": "bool"},
|
||||
"reset_values": {"type": "bool", "default": True},
|
||||
"reset_then_reuse_values": {"type": "bool", "default": False},
|
||||
"insecure_skip_tls_verify": {
|
||||
"type": "bool",
|
||||
"default": False,
|
||||
"aliases": ["skip_tls_certs_check"],
|
||||
},
|
||||
"plain_http": {"type": "bool", "default": False},
|
||||
"take_ownership": {"type": "bool", "default": False},
|
||||
"skip_schema_validation": {"type": "bool", "default": False},
|
||||
"cleanup_on_fail": {"type": "bool", "default": False},
|
||||
}
|
||||
)
|
||||
return arg_spec
|
||||
|
||||
@@ -1002,6 +1140,14 @@ def main():
|
||||
supports_check_mode=True,
|
||||
)
|
||||
|
||||
# Add deprecation warning for wait_timeout
|
||||
if module.params.get("wait_timeout") is not None:
|
||||
module.deprecate(
|
||||
"The 'wait_timeout' parameter is deprecated and will be removed in version 7.0.0. Use 'timeout' instead.",
|
||||
version="7.0.0",
|
||||
collection_name="kubernetes.core",
|
||||
)
|
||||
|
||||
if not IMP_YAML:
|
||||
module.fail_json(msg=missing_required_lib("yaml"), exception=IMP_YAML_ERR)
|
||||
|
||||
@@ -1025,8 +1171,10 @@ def main():
|
||||
force = module.params.get("force")
|
||||
purge = module.params.get("purge")
|
||||
wait = module.params.get("wait")
|
||||
wait_for_jobs = module.params.get("wait_for_jobs")
|
||||
wait_timeout = module.params.get("wait_timeout")
|
||||
atomic = module.params.get("atomic")
|
||||
cleanup_on_fail = module.params.get("cleanup_on_fail")
|
||||
server_side = module.params.get("server_side")
|
||||
force_conflicts = module.params.get("force_conflicts")
|
||||
create_namespace = module.params.get("create_namespace")
|
||||
@@ -1099,6 +1247,10 @@ def main():
|
||||
)
|
||||
changed = True
|
||||
elif release_state == "present":
|
||||
validate_value_options(
|
||||
module, replace, reuse_values, reset_values, reset_then_reuse_values
|
||||
)
|
||||
|
||||
if chart_version is not None:
|
||||
helm_cmd += " --version=" + chart_version
|
||||
|
||||
@@ -1152,11 +1304,13 @@ def main():
|
||||
release_values,
|
||||
chart_ref,
|
||||
wait,
|
||||
wait_for_jobs,
|
||||
wait_timeout,
|
||||
disable_hook,
|
||||
False,
|
||||
values_files=values_files,
|
||||
atomic=atomic,
|
||||
cleanup_on_fail=cleanup_on_fail,
|
||||
server_side=server_side,
|
||||
force_conflicts=force_conflicts,
|
||||
create_namespace=create_namespace,
|
||||
@@ -1238,11 +1392,13 @@ def main():
|
||||
release_values,
|
||||
chart_ref,
|
||||
wait,
|
||||
wait_for_jobs,
|
||||
wait_timeout,
|
||||
disable_hook,
|
||||
force,
|
||||
values_files=values_files,
|
||||
atomic=atomic,
|
||||
cleanup_on_fail=cleanup_on_fail,
|
||||
server_side=server_side,
|
||||
force_conflicts=force_conflicts,
|
||||
create_namespace=create_namespace,
|
||||
|
||||
@@ -119,8 +119,8 @@ status:
|
||||
returned: always
|
||||
description:
|
||||
- Dict of Values used to deploy
|
||||
- This return value has been deprecated and will be removed in a release after
|
||||
2027-01-08. Use RV(status.release_values) instead.
|
||||
- This return value has been deprecated and will be removed in version 8.0.0.
|
||||
Use RV(status.release_values) instead.
|
||||
release_values:
|
||||
type: dict
|
||||
returned: always
|
||||
@@ -213,6 +213,14 @@ def get_release_status(module, release_name, release_state, get_all_values=False
|
||||
|
||||
release["release_values"] = module.get_values(release_name, get_all_values)
|
||||
release["values"] = release["release_values"]
|
||||
|
||||
# Add deprecation warning for status.values
|
||||
module.deprecate(
|
||||
"The 'status.values' return value is deprecated and will be removed in version 8.0.0. Use 'status.release_values' instead.",
|
||||
version="8.0.0",
|
||||
collection_name="kubernetes.core",
|
||||
)
|
||||
|
||||
release["manifest"] = module.get_manifest(release_name)
|
||||
release["notes"] = module.get_notes(release_name)
|
||||
release["hooks"] = module.get_hooks(release_name)
|
||||
|
||||
@@ -331,7 +331,7 @@ def main():
|
||||
insecure_skip_tls_verify,
|
||||
)
|
||||
changed = True
|
||||
elif repository_status["url"] != repo_url:
|
||||
elif repository_status["url"].rstrip("/") != repo_url:
|
||||
module.fail_json(
|
||||
msg="Repository already have a repository named {0}".format(repo_name)
|
||||
)
|
||||
|
||||
@@ -228,6 +228,7 @@ except ImportError:
|
||||
from ansible.module_utils.basic import missing_required_lib
|
||||
from ansible_collections.kubernetes.core.plugins.module_utils.helm import (
|
||||
AnsibleHelmModule,
|
||||
strip_registry_progress,
|
||||
)
|
||||
from ansible_collections.kubernetes.core.plugins.module_utils.version import (
|
||||
LooseVersion,
|
||||
@@ -394,6 +395,9 @@ def main():
|
||||
|
||||
if not check_mode:
|
||||
rc, out, err = module.run_helm_command(tmpl_cmd)
|
||||
# 'stdout' is documented to hold the rendered templates, so keep helm's
|
||||
# OCI registry progress messages out of it.
|
||||
out = strip_registry_progress(out)
|
||||
else:
|
||||
out = err = ""
|
||||
rc = 0
|
||||
|
||||
@@ -76,9 +76,21 @@ options:
|
||||
- This option is ignored when I(content) is set or when I(state) is set to C(from_pod).
|
||||
type: bool
|
||||
default: False
|
||||
copy_timeout:
|
||||
description:
|
||||
- Maximum time in seconds to spend streaming the archive to the pod and waiting for the remote
|
||||
C(tar) process to finish extracting it.
|
||||
- Raise this when copying large files over a slow connection.
|
||||
- This option is ignored when I(state) is set to C(from_pod).
|
||||
type: int
|
||||
default: 300
|
||||
version_added: 6.6.0
|
||||
|
||||
notes:
|
||||
- the tar binary is required on the container when copying from local filesystem to pod.
|
||||
- a POSIX shell at C(/bin/sh) and C(head) are also used, when present, to bound the archive
|
||||
sent to the container so that the module can confirm the copy finished. Without them the
|
||||
copy still runs but completion cannot be verified, and a warning is emitted.
|
||||
- the (init) container has to be started before you copy files or directories to it.
|
||||
"""
|
||||
|
||||
@@ -180,6 +192,7 @@ def argspec():
|
||||
"choices": ["to_pod", "from_pod"],
|
||||
}
|
||||
argument_spec["no_preserve"] = {"type": "bool", "default": False}
|
||||
argument_spec["copy_timeout"] = {"type": "int", "default": 300}
|
||||
return argument_spec
|
||||
|
||||
|
||||
|
||||
@@ -118,7 +118,7 @@ result:
|
||||
type: int
|
||||
version_added: 2.2.0
|
||||
return_code:
|
||||
description: The command status code. This attribute is deprecated and will be removed in a future release. Please use rc instead.
|
||||
description: The command status code. This attribute is deprecated and will be removed in version 7.0.0. Use RV(result.rc) instead.
|
||||
type: int
|
||||
"""
|
||||
|
||||
@@ -219,6 +219,13 @@ def execute_module(module, client):
|
||||
else:
|
||||
rc = int(err["details"]["causes"][0]["message"])
|
||||
|
||||
# Add deprecation warning for return_code return value
|
||||
module.deprecate(
|
||||
"The 'return_code' return value is deprecated and will be removed in version 7.0.0. Use 'rc' instead.",
|
||||
version="7.0.0",
|
||||
collection_name="kubernetes.core",
|
||||
)
|
||||
|
||||
module.exit_json(
|
||||
# Some command might change environment, but ultimately failing at end
|
||||
changed=True,
|
||||
|
||||
+40
-10
@@ -53,6 +53,15 @@ options:
|
||||
type: list
|
||||
elements: str
|
||||
version_added: 3.0.0
|
||||
metadata_only:
|
||||
description:
|
||||
- Request metadata only response from the Kubernetes API server.
|
||||
- This feature is useful for clients that only need to check for the existence of an object,
|
||||
- or that only need to read its metadata.
|
||||
- It can significantly reduce the size of the response from the API server.
|
||||
type: bool
|
||||
default: false
|
||||
version_added: 6.6.0
|
||||
|
||||
extends_documentation_fragment:
|
||||
- kubernetes.core.k8s_auth_options
|
||||
@@ -135,6 +144,12 @@ EXAMPLES = r"""
|
||||
(ocp_bootstrap_status.resources[0].data.status == 'complete')
|
||||
retries: 60
|
||||
delay: 15
|
||||
|
||||
- name: Get a list of all pods metadata only
|
||||
kubernetes.core.k8s_info:
|
||||
kind: Pod
|
||||
metadata_only: true
|
||||
register: pod_metadata_list
|
||||
"""
|
||||
|
||||
RETURN = r"""
|
||||
@@ -179,6 +194,8 @@ from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule impo
|
||||
)
|
||||
from ansible_collections.kubernetes.core.plugins.module_utils.args_common import (
|
||||
AUTH_ARG_SPEC,
|
||||
METADATA_ONLY_HEADER_VALUES,
|
||||
METADATA_ONLY_HEADERS_SPEC,
|
||||
WAIT_ARG_SPEC,
|
||||
)
|
||||
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
|
||||
@@ -216,15 +233,16 @@ def argspec():
|
||||
args = copy.deepcopy(AUTH_ARG_SPEC)
|
||||
args.update(WAIT_ARG_SPEC)
|
||||
args.update(
|
||||
dict(
|
||||
kind=dict(required=True),
|
||||
api_version=dict(default="v1", aliases=["api", "version"]),
|
||||
name=dict(),
|
||||
namespace=dict(),
|
||||
label_selectors=dict(type="list", elements="str", default=[]),
|
||||
field_selectors=dict(type="list", elements="str", default=[]),
|
||||
hidden_fields=dict(type="list", elements="str"),
|
||||
)
|
||||
{
|
||||
"kind": {"required": True},
|
||||
"api_version": {"default": "v1", "aliases": ["api", "version"]},
|
||||
"name": {},
|
||||
"namespace": {},
|
||||
"label_selectors": {"type": "list", "elements": "str", "default": []},
|
||||
"field_selectors": {"type": "list", "elements": "str", "default": []},
|
||||
"hidden_fields": {"type": "list", "elements": "str"},
|
||||
"metadata_only": {"type": "bool", "default": False},
|
||||
}
|
||||
)
|
||||
return args
|
||||
|
||||
@@ -233,8 +251,20 @@ def main():
|
||||
module = AnsibleK8SModule(
|
||||
module_class=AnsibleModule, argument_spec=argspec(), supports_check_mode=True
|
||||
)
|
||||
|
||||
metadata_only_headers = {}
|
||||
if module.params["metadata_only"]:
|
||||
metadata_only_headers = copy.deepcopy(METADATA_ONLY_HEADERS_SPEC)
|
||||
metadata_only_headers.update(
|
||||
{"accept": METADATA_ONLY_HEADER_VALUES["partial_object_list"]}
|
||||
)
|
||||
if module.params["name"]:
|
||||
metadata_only_headers.update(
|
||||
{"accept": METADATA_ONLY_HEADER_VALUES["partial_object"]}
|
||||
)
|
||||
|
||||
try:
|
||||
client = get_api_client(module)
|
||||
client = get_api_client(module, **metadata_only_headers)
|
||||
svc = K8sService(client, module)
|
||||
execute_module(module, svc)
|
||||
except CoreException as e:
|
||||
|
||||
@@ -36,6 +36,7 @@ options:
|
||||
- If more than one C(merge_type) is given, the merge_types will be tried in order
|
||||
- This defaults to C(['strategic-merge', 'merge']), which is ideal for using the same parameters
|
||||
on resource kinds that combine Custom Resources and built-in resources.
|
||||
- I(merge_type=json) has been deprecated and will be removed in version 7.0.0. Use M(kubernetes.core.k8s_json_patch) instead.
|
||||
choices:
|
||||
- json
|
||||
- merge
|
||||
@@ -251,6 +252,15 @@ def main():
|
||||
supports_check_mode=True,
|
||||
)
|
||||
|
||||
# Add deprecation warning for merge_type=json
|
||||
merge_type = module.params.get("merge_type")
|
||||
if merge_type and "json" in merge_type:
|
||||
module.deprecate(
|
||||
"The 'merge_type=json' option is deprecated and will be removed in version 7.0.0. Use the 'kubernetes.core.k8s_json_patch' module instead.",
|
||||
version="7.0.0",
|
||||
collection_name="kubernetes.core",
|
||||
)
|
||||
|
||||
try:
|
||||
client = get_api_client(module=module)
|
||||
svc = K8sService(client, module)
|
||||
|
||||
@@ -13,6 +13,17 @@ sonar.newCode.referenceBranch=stable-6
|
||||
|
||||
sonar.exclusions=tests/**,.tox/**
|
||||
|
||||
# Exclude test code from copy/paste detection. 'sonar.exclusions' above only
|
||||
# filters the *source* set (it disambiguates 'sonar.sources=.' from
|
||||
# 'sonar.tests'), so test files are still indexed as tests and still scored for
|
||||
# duplication. Unit tests here are unittest.TestCase classes: every class needs
|
||||
# its own setUp, and per-case arrange/assert blocks are deliberately repeated so
|
||||
# a failing test reads on its own. Because SonarCloud scores only *new code* on
|
||||
# a pull request, any PR adding cases to an already-repetitive test module
|
||||
# inherits duplication accrued across earlier PRs. Production code under
|
||||
# plugins/ stays fully covered by duplication analysis.
|
||||
sonar.cpd.exclusions=tests/**
|
||||
|
||||
# Ansible module argument_spec is conventionally defined with the dict(...)
|
||||
# constructor (not {...} literals) for readability and consistency across the
|
||||
# collection. Suppress python:S7498 ("prefer literal syntax"), which conflicts
|
||||
|
||||
+1
-1
@@ -1,2 +1,2 @@
|
||||
modules:
|
||||
python_requires: ">=3.6"
|
||||
python_requires: ">=3.9"
|
||||
|
||||
@@ -31,3 +31,4 @@ test_namespace:
|
||||
- "helm-insecure-{{ helm_version | replace('.', '-') }}"
|
||||
- "helm-test-take-ownership-{{ helm_version | replace('.', '-') }}"
|
||||
- "helm-skip-schema-validation-{{ helm_version | replace('.', '-') }}"
|
||||
- "helm-wait-for-jobs-{{ helm_version | replace('.', '-') }}"
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
apiVersion: v2
|
||||
name: test-chart-job
|
||||
description: A chart with a Job for testing wait_for_jobs
|
||||
type: application
|
||||
version: 0.1.0
|
||||
appVersion: "default"
|
||||
@@ -0,0 +1,21 @@
|
||||
apiVersion: batch/v1
|
||||
kind: Job
|
||||
metadata:
|
||||
name: "{{ .Release.Name }}-job"
|
||||
spec:
|
||||
backoffLimit: 0
|
||||
template:
|
||||
spec:
|
||||
automountServiceAccountToken: false
|
||||
restartPolicy: Never
|
||||
containers:
|
||||
- name: test
|
||||
image: "busybox:1.37"
|
||||
command: ["sh", "-c", "echo done"]
|
||||
resources:
|
||||
requests:
|
||||
cpu: "50m"
|
||||
memory: "32Mi"
|
||||
ephemeral-storage: "16Mi"
|
||||
limits:
|
||||
memory: "64Mi"
|
||||
@@ -49,6 +49,9 @@
|
||||
- name: Test helm skip_schema_validation
|
||||
include_tasks: test_skip_schema_validation.yml
|
||||
|
||||
- name: Test helm wait_for_jobs
|
||||
include_tasks: test_helm_wait_for_jobs.yml
|
||||
|
||||
always:
|
||||
- name: Remove helm-diff plugin
|
||||
helm_plugin:
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
---
|
||||
- name: Test helm wait_for_jobs
|
||||
vars:
|
||||
helm_namespace: "{{ test_namespace[15] }}"
|
||||
chart_local: "{{ role_path }}/files/test-chart-job"
|
||||
block:
|
||||
|
||||
- name: Install chart with wait and wait_for_jobs
|
||||
helm:
|
||||
binary_path: "{{ helm_binary }}"
|
||||
chart_ref: "{{ chart_local }}"
|
||||
release_name: test-wait-for-jobs
|
||||
release_namespace: "{{ helm_namespace }}"
|
||||
create_namespace: true
|
||||
wait: true
|
||||
wait_for_jobs: true
|
||||
wait_timeout: "120s"
|
||||
register: install
|
||||
ignore_errors: true
|
||||
|
||||
- name: Validate wait_for_jobs with helm >= 3.5.0 works
|
||||
assert:
|
||||
that:
|
||||
- install is changed
|
||||
- "'--wait' in install.command"
|
||||
- "'--wait-for-jobs' in install.command"
|
||||
when: "helm_version is ansible.builtin.version('v3.5.0', '>=')"
|
||||
|
||||
- name: Validate wait_for_jobs with helm < 3.5.0 fails
|
||||
assert:
|
||||
that:
|
||||
- install is failed
|
||||
- "'wait_for_jobs requires helm >= 3.5.0' in install.msg"
|
||||
when: "helm_version is ansible.builtin.version('v3.5.0', '<')"
|
||||
|
||||
- name: Install chart with wait_for_jobs but without wait
|
||||
helm:
|
||||
binary_path: "{{ helm_binary }}"
|
||||
chart_ref: "{{ chart_local }}"
|
||||
release_name: test-wait-for-jobs-no-wait
|
||||
release_namespace: "{{ helm_namespace }}"
|
||||
create_namespace: true
|
||||
wait_for_jobs: true
|
||||
register: install_no_wait
|
||||
|
||||
- name: Validate wait_for_jobs is ignored without wait
|
||||
assert:
|
||||
that:
|
||||
- install_no_wait is changed
|
||||
- "'--wait-for-jobs' not in install_no_wait.command"
|
||||
- "'--wait' not in install_no_wait.command"
|
||||
|
||||
always:
|
||||
- name: Remove helm namespace
|
||||
k8s:
|
||||
api_version: v1
|
||||
kind: Namespace
|
||||
name: "{{ helm_namespace }}"
|
||||
state: absent
|
||||
@@ -0,0 +1,3 @@
|
||||
time=10
|
||||
helm
|
||||
helm_template
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
# Helm >= 4.2.1 is required for this test to be meaningful: that is the release which
|
||||
# moved the OCI registry progress messages from stderr to stdout (helm/helm#32056).
|
||||
helm_oci_version: v4.2.4
|
||||
|
||||
helm_oci_namespace: helm-oci-registry-progress
|
||||
test_namespace: "{{ helm_oci_namespace }}"
|
||||
|
||||
# Matches the registry stood up by the setup_helm_registry role.
|
||||
helm_oci_registry: "localhost:6035"
|
||||
helm_oci_registry_username: testuser
|
||||
helm_oci_registry_password: 'pass123!'
|
||||
helm_oci_repo_path: testing
|
||||
|
||||
helm_oci_chart_name: test-chart-plus-version
|
||||
# '+' is not allowed in an OCI tag, so Helm stores this as '1.0.0_build.1'.
|
||||
helm_oci_chart_version: 1.0.0+build.1
|
||||
# A version without build metadata, to cover the case where the progress messages
|
||||
# happen to be valid YAML and so corrupt the parsed output silently.
|
||||
helm_oci_chart_version_plain: 1.0.1
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
apiVersion: v2
|
||||
name: test-chart-plus-version
|
||||
description: A chart whose version carries semver build metadata
|
||||
type: application
|
||||
version: 1.0.0+build.1
|
||||
appVersion: "default"
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
metadata:
|
||||
name: test-chart-plus-version-configmap
|
||||
data:
|
||||
myValue: test
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
dependencies:
|
||||
- remove_namespace
|
||||
- setup_helm_registry
|
||||
@@ -0,0 +1,158 @@
|
||||
---
|
||||
# Regression test for https://github.com/ansible-collections/kubernetes.core/issues/1222
|
||||
#
|
||||
# Helm >= 4.2.1 writes OCI registry progress messages to stdout rather than stderr
|
||||
# (helm/helm#32056): 'Pulled:', 'Digest:' and, when the reference contains an
|
||||
# underscore, a free-text explanation. Helm rewrites '+' to '_' in OCI tags, so a
|
||||
# chart version carrying semver build metadata is what triggers that explanation,
|
||||
# which is not valid YAML.
|
||||
#
|
||||
# The helm module parses the stdout of 'helm show chart', and helm_template returns
|
||||
# the stdout of 'helm template' as its documented result, so both have to skip those
|
||||
# messages. Without the fix, the helm task below fails with
|
||||
# "could not find expected ':'".
|
||||
- name: Test OCI charts whose version contains build metadata
|
||||
vars:
|
||||
chart_ref: "oci://{{ helm_oci_registry }}/{{ helm_oci_repo_path }}/{{ helm_oci_chart_name }}"
|
||||
block:
|
||||
- name: "Install Helm {{ helm_oci_version }}"
|
||||
ansible.builtin.include_role:
|
||||
name: install_helm
|
||||
vars:
|
||||
helm_version: "{{ helm_oci_version }}"
|
||||
|
||||
- name: Create temporary directory to hold the chart
|
||||
ansible.builtin.tempfile:
|
||||
state: directory
|
||||
suffix: .chart
|
||||
register: _tmpd
|
||||
|
||||
- name: Copy the test chart
|
||||
ansible.builtin.copy:
|
||||
src: "{{ helm_oci_chart_name }}"
|
||||
dest: "{{ _tmpd.path }}/"
|
||||
|
||||
- name: Log into the helm registry
|
||||
ansible.builtin.command: >-
|
||||
{{ helm_binary }} registry login --plain-http
|
||||
-u {{ helm_oci_registry_username }} -p {{ helm_oci_registry_password }}
|
||||
{{ helm_oci_registry }}
|
||||
|
||||
- name: Package and push both chart versions
|
||||
ansible.builtin.command: "{{ item }}"
|
||||
loop:
|
||||
- >-
|
||||
{{ helm_binary }} package {{ _tmpd.path }}/{{ helm_oci_chart_name }}
|
||||
--version {{ helm_oci_chart_version }} --destination {{ _tmpd.path }}
|
||||
- >-
|
||||
{{ helm_binary }} package {{ _tmpd.path }}/{{ helm_oci_chart_name }}
|
||||
--version {{ helm_oci_chart_version_plain }} --destination {{ _tmpd.path }}
|
||||
- >-
|
||||
{{ helm_binary }} push --plain-http
|
||||
{{ _tmpd.path }}/{{ helm_oci_chart_name }}-{{ helm_oci_chart_version }}.tgz
|
||||
oci://{{ helm_oci_registry }}/{{ helm_oci_repo_path }}
|
||||
- >-
|
||||
{{ helm_binary }} push --plain-http
|
||||
{{ _tmpd.path }}/{{ helm_oci_chart_name }}-{{ helm_oci_chart_version_plain }}.tgz
|
||||
oci://{{ helm_oci_registry }}/{{ helm_oci_repo_path }}
|
||||
register: _push
|
||||
|
||||
- name: Ensure Helm stored the build metadata version with an underscore
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- "'1.0.0_build.1' in (_push.results[2].stdout + _push.results[2].stderr)"
|
||||
fail_msg: >-
|
||||
Expected Helm to rewrite '+' to '_' when pushing the chart tag. Without
|
||||
that rewrite this target no longer covers the case it was written for.
|
||||
|
||||
# helm - the version with build metadata is the case that failed outright.
|
||||
- name: Install the chart from the OCI registry
|
||||
kubernetes.core.helm:
|
||||
binary_path: "{{ helm_binary }}"
|
||||
name: "{{ helm_oci_chart_name }}"
|
||||
chart_ref: "{{ chart_ref }}"
|
||||
chart_version: "{{ helm_oci_chart_version }}"
|
||||
release_namespace: "{{ helm_oci_namespace }}"
|
||||
create_namespace: true
|
||||
plain_http: true
|
||||
register: _install
|
||||
|
||||
- name: Ensure the release reports the chart version verbatim
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- _install is changed
|
||||
- _install.status.chart == helm_oci_chart_name ~ '-' ~ helm_oci_chart_version
|
||||
|
||||
- name: Install the same chart again
|
||||
kubernetes.core.helm:
|
||||
binary_path: "{{ helm_binary }}"
|
||||
name: "{{ helm_oci_chart_name }}"
|
||||
chart_ref: "{{ chart_ref }}"
|
||||
chart_version: "{{ helm_oci_chart_version }}"
|
||||
release_namespace: "{{ helm_oci_namespace }}"
|
||||
plain_http: true
|
||||
register: _reinstall
|
||||
|
||||
- name: Ensure the module is idempotent
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- _reinstall is not changed
|
||||
|
||||
# helm_template - stdout is documented to hold only the rendered templates. Both
|
||||
# chart versions are checked: the plain one covers the case where the progress
|
||||
# messages are valid YAML and would otherwise be parsed as a manifest.
|
||||
- name: Render the chart from the OCI registry
|
||||
kubernetes.core.helm_template:
|
||||
binary_path: "{{ helm_binary }}"
|
||||
chart_ref: "{{ chart_ref }}"
|
||||
chart_version: "{{ item }}"
|
||||
release_name: "{{ helm_oci_chart_name }}"
|
||||
plain_http: true
|
||||
loop:
|
||||
- "{{ helm_oci_chart_version }}"
|
||||
- "{{ helm_oci_chart_version_plain }}"
|
||||
register: _template
|
||||
|
||||
- name: Ensure stdout holds the rendered manifests and nothing else
|
||||
ansible.builtin.assert:
|
||||
that:
|
||||
- "'Pulled:' not in item.stdout"
|
||||
- "'Digest:' not in item.stdout"
|
||||
- "'contains an underscore' not in item.stdout"
|
||||
- item.stdout.startswith('---')
|
||||
- (item.stdout | from_yaml_all | list | map(attribute='kind') | list) == ['ConfigMap']
|
||||
fail_msg: "helm_template stdout was not only rendered manifests: {{ item.stdout[:200] }}"
|
||||
loop: "{{ _template.results }}"
|
||||
loop_control:
|
||||
label: "{{ item.item }}"
|
||||
|
||||
always:
|
||||
- name: Uninstall the release
|
||||
kubernetes.core.helm:
|
||||
binary_path: "{{ helm_binary }}"
|
||||
name: "{{ helm_oci_chart_name }}"
|
||||
release_namespace: "{{ helm_oci_namespace }}"
|
||||
state: absent
|
||||
when: helm_binary is defined
|
||||
ignore_errors: true
|
||||
|
||||
- name: Remove the test namespace
|
||||
kubernetes.core.k8s:
|
||||
api_version: v1
|
||||
kind: Namespace
|
||||
name: "{{ helm_oci_namespace }}"
|
||||
state: absent
|
||||
wait: true
|
||||
ignore_errors: true
|
||||
|
||||
- name: Log out of the helm registry
|
||||
ansible.builtin.command: "{{ helm_binary }} registry logout {{ helm_oci_registry }}"
|
||||
when: helm_binary is defined
|
||||
ignore_errors: true
|
||||
|
||||
- name: Remove the temporary directory
|
||||
ansible.builtin.file:
|
||||
path: "{{ _tmpd.path }}"
|
||||
state: absent
|
||||
when: _tmpd is defined and _tmpd.path is defined
|
||||
ignore_errors: true
|
||||
@@ -103,3 +103,81 @@
|
||||
binary_path: "{{ helm_binary }}"
|
||||
name: test_helm_repo
|
||||
state: absent
|
||||
|
||||
# https://github.com/ansible-collections/kubernetes.core/issues/1235
|
||||
- name: Ensure the trailing slash test repositories don't exist
|
||||
helm_repository:
|
||||
binary_path: "{{ helm_binary }}"
|
||||
name: "{{ item }}"
|
||||
state: absent
|
||||
loop:
|
||||
- test_helm_repo_slash
|
||||
- test_helm_repo_noslash
|
||||
|
||||
- name: Register test_helm_repo_slash directly through helm, keeping the trailing slash
|
||||
ansible.builtin.command: "{{ helm_binary }} repo add test_helm_repo_slash {{ chart_test_repo }}/"
|
||||
changed_when: true
|
||||
|
||||
- name: Add test_helm_repo_noslash chart repository without a trailing slash
|
||||
helm_repository:
|
||||
binary_path: "{{ helm_binary }}"
|
||||
name: test_helm_repo_noslash
|
||||
repo_url: "{{ chart_test_repo }}"
|
||||
|
||||
- name: Check idempotency when the stored and the requested URL both have a trailing slash
|
||||
helm_repository:
|
||||
binary_path: "{{ helm_binary }}"
|
||||
name: test_helm_repo_slash
|
||||
repo_url: "{{ chart_test_repo }}/"
|
||||
register: repository
|
||||
|
||||
- name: Assert idempotency when the stored and the requested URL both have a trailing slash
|
||||
assert:
|
||||
that:
|
||||
- repository is not changed
|
||||
|
||||
- name: Check idempotency when only the stored URL has a trailing slash
|
||||
helm_repository:
|
||||
binary_path: "{{ helm_binary }}"
|
||||
name: test_helm_repo_slash
|
||||
repo_url: "{{ chart_test_repo }}"
|
||||
register: repository
|
||||
|
||||
- name: Assert idempotency when only the stored URL has a trailing slash
|
||||
assert:
|
||||
that:
|
||||
- repository is not changed
|
||||
|
||||
- name: Check idempotency when only the requested URL has a trailing slash
|
||||
helm_repository:
|
||||
binary_path: "{{ helm_binary }}"
|
||||
name: test_helm_repo_noslash
|
||||
repo_url: "{{ chart_test_repo }}/"
|
||||
register: repository
|
||||
|
||||
- name: Assert idempotency when only the requested URL has a trailing slash
|
||||
assert:
|
||||
that:
|
||||
- repository is not changed
|
||||
|
||||
- name: Failed to add repository with the same name and a different URL, trailing slash aside
|
||||
helm_repository:
|
||||
binary_path: "{{ helm_binary }}"
|
||||
name: test_helm_repo_slash
|
||||
repo_url: "https://other-charts.url/"
|
||||
register: repository_errors
|
||||
ignore_errors: true
|
||||
|
||||
- name: Assert that adding repository with the same name and a different URL failed
|
||||
assert:
|
||||
that:
|
||||
- repository_errors is failed
|
||||
|
||||
- name: Clean the trailing slash test repositories
|
||||
helm_repository:
|
||||
binary_path: "{{ helm_binary }}"
|
||||
name: "{{ item }}"
|
||||
state: absent
|
||||
loop:
|
||||
- test_helm_repo_slash
|
||||
- test_helm_repo_noslash
|
||||
|
||||
@@ -143,9 +143,7 @@ def compare_directories(dir1, dir2):
|
||||
[len(test.left_only) > 0, len(test.right_only) > 0, len(test.funny_files) > 0]
|
||||
):
|
||||
return False
|
||||
(t, mismatch, errors) = filecmp.cmpfiles(
|
||||
dir1, dir2, test.common_files, shallow=False
|
||||
)
|
||||
t, mismatch, errors = filecmp.cmpfiles(dir1, dir2, test.common_files, shallow=False)
|
||||
if len(mismatch) > 0 or len(errors) > 0:
|
||||
return False
|
||||
for common_dir in test.common_dirs:
|
||||
|
||||
@@ -33,7 +33,7 @@
|
||||
init_pod_status.resources|length > 0
|
||||
and 'initContainerStatuses' in init_pod_status.resources.0.status
|
||||
and init_pod_status.resources.0.status.initContainerStatuses|length > 0
|
||||
and init_pod_status.resources.0.status.initContainerStatuses.0.started|bool
|
||||
and init_pod_status.resources.0.status.initContainerStatuses.0.started|default(false)|bool
|
||||
|
||||
- include_tasks: test_copy_errors.yml
|
||||
- include_tasks: test_check_mode.yml
|
||||
@@ -41,6 +41,7 @@
|
||||
- include_tasks: test_multi_container_pod.yml
|
||||
- include_tasks: test_copy_directory.yml
|
||||
- include_tasks: test_copy_large_file.yml
|
||||
- include_tasks: test_copy_repeated.yml
|
||||
- include_tasks: test_copy_item_with_space_in_its_name.yml
|
||||
- include_tasks: test_init_container_pod.yml
|
||||
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
---
|
||||
# Regression coverage for
|
||||
# https://github.com/ansible-collections/kubernetes.core/issues/776
|
||||
#
|
||||
# The module used to close the exec connection as soon as the last chunk had
|
||||
# been written, which killed the remote tar mid-extract and truncated the file.
|
||||
# The failure was timing dependent, so a single copy rarely caught it: repeat
|
||||
# the copy and compare every time.
|
||||
- name: create temporary directory for local files
|
||||
ansible.builtin.tempfile:
|
||||
state: directory
|
||||
suffix: k8scp_repeated
|
||||
register: test_dir
|
||||
|
||||
- name: test repeated copies are never truncated
|
||||
block:
|
||||
- set_fact:
|
||||
test_directory: "{{ test_dir.path }}"
|
||||
copy_iterations: 10
|
||||
no_log: true
|
||||
|
||||
# Large enough to span several 1MiB write chunks, so the last chunk is not
|
||||
# also the first and the drain actually has something to wait for.
|
||||
- name: create a multi-chunk file
|
||||
ansible.builtin.command:
|
||||
cmd: dd if=/dev/urandom of={{ test_directory }}/repeated.bin bs=1M count=12
|
||||
|
||||
- name: copy the same file repeatedly and verify each time
|
||||
ansible.builtin.include_tasks: verify_one_copy.yml
|
||||
loop: "{{ range(0, copy_iterations) | list }}"
|
||||
loop_control:
|
||||
loop_var: iteration
|
||||
|
||||
always:
|
||||
- name: delete temporary directory created for the test
|
||||
ansible.builtin.file:
|
||||
path: "{{ test_dir.path }}"
|
||||
state: absent
|
||||
ignore_errors: true
|
||||
|
||||
- name: delete file created on Pod
|
||||
k8s_exec:
|
||||
namespace: '{{ copy_namespace }}'
|
||||
pod: '{{ pod_with_one_container.name }}'
|
||||
command: 'rm -f /repeated.bin'
|
||||
ignore_errors: true
|
||||
@@ -0,0 +1,23 @@
|
||||
---
|
||||
# One iteration of the repeated-copy regression check, see test_copy_repeated.yml
|
||||
- name: remove any file left by the previous iteration
|
||||
k8s_exec:
|
||||
namespace: '{{ copy_namespace }}'
|
||||
pod: '{{ pod_with_one_container.name }}'
|
||||
command: 'rm -f /repeated.bin'
|
||||
ignore_errors: true
|
||||
|
||||
- name: "copy file into remote Pod (iteration {{ iteration }})"
|
||||
k8s_cp:
|
||||
namespace: '{{ copy_namespace }}'
|
||||
pod: '{{ pod_with_one_container.name }}'
|
||||
remote_path: /repeated.bin
|
||||
local_path: "{{ test_directory }}/repeated.bin"
|
||||
state: to_pod
|
||||
|
||||
- name: "compare local and remote file (iteration {{ iteration }})"
|
||||
kubectl_file_compare:
|
||||
namespace: '{{ copy_namespace }}'
|
||||
pod: '{{ pod_with_one_container.name }}'
|
||||
remote_path: /repeated.bin
|
||||
local_path: "{{ test_directory }}/repeated.bin"
|
||||
@@ -4,3 +4,4 @@
|
||||
- wait
|
||||
- api-server-caching
|
||||
- discovery
|
||||
- metadata-only-fetches
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
- name: Retrieve Node list with metadata_only
|
||||
kubernetes.core.k8s_info:
|
||||
kind: Node
|
||||
metadata_only: true
|
||||
register: node_metadata_only_list
|
||||
|
||||
- name: Assert response has kind PartialObjectMetadata
|
||||
assert:
|
||||
that:
|
||||
- node_metadata_only_list.resources[0].kind == "PartialObjectMetadata"
|
||||
|
||||
- name: Retrieve full Node list
|
||||
kubernetes.core.k8s_info:
|
||||
kind: Node
|
||||
metadata_only: false
|
||||
register: node_full_list
|
||||
|
||||
- name: Assert response has kind Node
|
||||
assert:
|
||||
that:
|
||||
- node_full_list.resources[0].kind == "Node"
|
||||
@@ -238,7 +238,55 @@
|
||||
- resource.result.results | selectattr('changed') | list | length == 1
|
||||
- resource.result.results | selectattr('error', 'defined') | list | length == 1
|
||||
|
||||
- name: Apply template where all items are disabled (empty output)
|
||||
kubernetes.core.k8s:
|
||||
state: present
|
||||
template:
|
||||
path: "conditional_empty.j2"
|
||||
vars:
|
||||
items:
|
||||
- name: test1
|
||||
enabled: false
|
||||
- name: test2
|
||||
enabled: false
|
||||
k8s_pod_namespace: "{{ template_namespace }}"
|
||||
register: r
|
||||
|
||||
- name: Check that empty template succeeds with no changes
|
||||
assert:
|
||||
that:
|
||||
- r is successful
|
||||
- r is not changed
|
||||
|
||||
- name: Apply template where some items are enabled
|
||||
kubernetes.core.k8s:
|
||||
state: present
|
||||
template:
|
||||
path: "conditional_empty.j2"
|
||||
vars:
|
||||
items:
|
||||
- name: conditional-configmap-1
|
||||
enabled: true
|
||||
- name: conditional-configmap-2
|
||||
enabled: false
|
||||
k8s_pod_namespace: "{{ template_namespace }}"
|
||||
register: r
|
||||
|
||||
- name: Check that partial template creates resources
|
||||
assert:
|
||||
that:
|
||||
- r is successful
|
||||
- r is changed
|
||||
|
||||
always:
|
||||
- name: Cleanup conditional configmap
|
||||
kubernetes.core.k8s:
|
||||
state: absent
|
||||
kind: ConfigMap
|
||||
name: conditional-configmap-1
|
||||
namespace: "{{ template_namespace }}"
|
||||
ignore_errors: true
|
||||
|
||||
- name: Remove namespace (Cleanup)
|
||||
kubernetes.core.k8s:
|
||||
kind: Namespace
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
{% for item in items %}
|
||||
{% if item.enabled %}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
metadata:
|
||||
name: "{{ item.name }}"
|
||||
namespace: "{{ k8s_pod_namespace }}"
|
||||
data:
|
||||
key: value
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
@@ -21,6 +21,7 @@ tests/integration/targets/k8s_delete/files/deployments.yaml yamllint!skip
|
||||
tests/unit/module_utils/fixtures/pods.yml yamllint!skip
|
||||
tests/integration/targets/helm/files/appversionless-chart-v2/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/appversionless-chart/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/test-chart-job/Chart.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/test-chart-v2/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/test-chart/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm_diff/files/test-chart/templates/configmap.yaml yamllint!skip
|
||||
|
||||
@@ -21,6 +21,7 @@ tests/integration/targets/k8s_delete/files/deployments.yaml yamllint!skip
|
||||
tests/unit/module_utils/fixtures/pods.yml yamllint!skip
|
||||
tests/integration/targets/helm/files/appversionless-chart-v2/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/appversionless-chart/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/test-chart-job/Chart.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/test-chart-v2/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/test-chart/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm_diff/files/test-chart/templates/configmap.yaml yamllint!skip
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
plugins/module_utils/client/discovery.py import-3.9!skip
|
||||
plugins/module_utils/client/discovery.py import-3.10!skip
|
||||
plugins/module_utils/client/discovery.py import-3.11!skip
|
||||
plugins/module_utils/client/discovery.py import-3.12!skip
|
||||
plugins/module_utils/client/discovery.py import-3.13!skip
|
||||
plugins/module_utils/client/resource.py import-3.9!skip
|
||||
plugins/module_utils/client/resource.py import-3.10!skip
|
||||
plugins/module_utils/client/resource.py import-3.11!skip
|
||||
plugins/module_utils/client/resource.py import-3.12!skip
|
||||
plugins/module_utils/client/resource.py import-3.13!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.9!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.10!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.11!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.12!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.13!skip
|
||||
@@ -18,6 +24,7 @@ tests/integration/targets/k8s_delete/files/deployments.yaml yamllint!skip
|
||||
tests/unit/module_utils/fixtures/pods.yml yamllint!skip
|
||||
tests/integration/targets/helm/files/appversionless-chart-v2/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/appversionless-chart/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/test-chart-job/Chart.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/test-chart-v2/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/test-chart/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm_diff/files/test-chart/templates/configmap.yaml yamllint!skip
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
plugins/module_utils/client/discovery.py import-3.9!skip
|
||||
plugins/module_utils/client/discovery.py import-3.10!skip
|
||||
plugins/module_utils/client/discovery.py import-3.11!skip
|
||||
plugins/module_utils/client/discovery.py import-3.12!skip
|
||||
plugins/module_utils/client/discovery.py import-3.13!skip
|
||||
plugins/module_utils/client/resource.py import-3.9!skip
|
||||
plugins/module_utils/client/resource.py import-3.10!skip
|
||||
plugins/module_utils/client/resource.py import-3.11!skip
|
||||
plugins/module_utils/client/resource.py import-3.12!skip
|
||||
plugins/module_utils/client/resource.py import-3.13!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.9!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.10!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.11!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.12!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.13!skip
|
||||
@@ -18,6 +24,7 @@ tests/integration/targets/k8s_delete/files/deployments.yaml yamllint!skip
|
||||
tests/unit/module_utils/fixtures/pods.yml yamllint!skip
|
||||
tests/integration/targets/helm/files/appversionless-chart-v2/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/appversionless-chart/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/test-chart-job/Chart.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/test-chart-v2/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/test-chart/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm_diff/files/test-chart/templates/configmap.yaml yamllint!skip
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
plugins/module_utils/client/discovery.py import-3.9!skip
|
||||
plugins/module_utils/client/discovery.py import-3.10!skip
|
||||
plugins/module_utils/client/discovery.py import-3.11!skip
|
||||
plugins/module_utils/client/discovery.py import-3.12!skip
|
||||
plugins/module_utils/client/discovery.py import-3.13!skip
|
||||
plugins/module_utils/client/discovery.py import-3.14!skip
|
||||
plugins/module_utils/client/resource.py import-3.9!skip
|
||||
plugins/module_utils/client/resource.py import-3.10!skip
|
||||
plugins/module_utils/client/resource.py import-3.11!skip
|
||||
plugins/module_utils/client/resource.py import-3.12!skip
|
||||
plugins/module_utils/client/resource.py import-3.13!skip
|
||||
plugins/module_utils/client/resource.py import-3.14!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.9!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.10!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.11!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.12!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.13!skip
|
||||
@@ -21,6 +27,7 @@ tests/integration/targets/k8s_delete/files/deployments.yaml yamllint!skip
|
||||
tests/unit/module_utils/fixtures/pods.yml yamllint!skip
|
||||
tests/integration/targets/helm/files/appversionless-chart-v2/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/appversionless-chart/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/test-chart-job/Chart.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/test-chart-v2/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/test-chart/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm_diff/files/test-chart/templates/configmap.yaml yamllint!skip
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
plugins/module_utils/client/discovery.py import-3.9!skip
|
||||
plugins/module_utils/client/discovery.py import-3.10!skip
|
||||
plugins/module_utils/client/discovery.py import-3.11!skip
|
||||
plugins/module_utils/client/discovery.py import-3.12!skip
|
||||
plugins/module_utils/client/discovery.py import-3.13!skip
|
||||
plugins/module_utils/client/discovery.py import-3.14!skip
|
||||
plugins/module_utils/client/resource.py import-3.9!skip
|
||||
plugins/module_utils/client/resource.py import-3.10!skip
|
||||
plugins/module_utils/client/resource.py import-3.11!skip
|
||||
plugins/module_utils/client/resource.py import-3.12!skip
|
||||
plugins/module_utils/client/resource.py import-3.13!skip
|
||||
plugins/module_utils/client/resource.py import-3.14!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.9!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.10!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.11!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.12!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.13!skip
|
||||
@@ -21,6 +27,7 @@ tests/integration/targets/k8s_delete/files/deployments.yaml yamllint!skip
|
||||
tests/unit/module_utils/fixtures/pods.yml yamllint!skip
|
||||
tests/integration/targets/helm/files/appversionless-chart-v2/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/appversionless-chart/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/test-chart-job/Chart.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/test-chart-v2/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/test-chart/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm_diff/files/test-chart/templates/configmap.yaml yamllint!skip
|
||||
|
||||
@@ -1,15 +1,24 @@
|
||||
plugins/module_utils/client/discovery.py import-3.9!skip
|
||||
plugins/module_utils/client/discovery.py import-3.10!skip
|
||||
plugins/module_utils/client/discovery.py import-3.11!skip
|
||||
plugins/module_utils/client/discovery.py import-3.12!skip
|
||||
plugins/module_utils/client/discovery.py import-3.13!skip
|
||||
plugins/module_utils/client/discovery.py import-3.14!skip
|
||||
plugins/module_utils/client/discovery.py import-3.15!skip
|
||||
plugins/module_utils/client/resource.py import-3.9!skip
|
||||
plugins/module_utils/client/resource.py import-3.10!skip
|
||||
plugins/module_utils/client/resource.py import-3.11!skip
|
||||
plugins/module_utils/client/resource.py import-3.12!skip
|
||||
plugins/module_utils/client/resource.py import-3.13!skip
|
||||
plugins/module_utils/client/resource.py import-3.14!skip
|
||||
plugins/module_utils/client/resource.py import-3.15!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.9!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.10!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.11!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.12!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.13!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.14!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.15!skip
|
||||
plugins/module_utils/version.py pylint!skip
|
||||
plugins/modules/k8s.py validate-modules:parameter-type-not-in-doc
|
||||
plugins/modules/k8s_scale.py validate-modules:parameter-type-not-in-doc
|
||||
@@ -21,6 +30,7 @@ tests/integration/targets/k8s_delete/files/deployments.yaml yamllint!skip
|
||||
tests/unit/module_utils/fixtures/pods.yml yamllint!skip
|
||||
tests/integration/targets/helm/files/appversionless-chart-v2/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/appversionless-chart/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/test-chart-job/Chart.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/test-chart-v2/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/test-chart/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm_diff/files/test-chart/templates/configmap.yaml yamllint!skip
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
plugins/module_utils/client/discovery.py import-3.9!skip
|
||||
plugins/module_utils/client/discovery.py import-3.10!skip
|
||||
plugins/module_utils/client/discovery.py import-3.11!skip
|
||||
plugins/module_utils/client/discovery.py import-3.12!skip
|
||||
plugins/module_utils/client/discovery.py import-3.13!skip
|
||||
plugins/module_utils/client/discovery.py import-3.14!skip
|
||||
plugins/module_utils/client/discovery.py import-3.15!skip
|
||||
plugins/module_utils/client/resource.py import-3.9!skip
|
||||
plugins/module_utils/client/resource.py import-3.10!skip
|
||||
plugins/module_utils/client/resource.py import-3.11!skip
|
||||
plugins/module_utils/client/resource.py import-3.12!skip
|
||||
plugins/module_utils/client/resource.py import-3.13!skip
|
||||
plugins/module_utils/client/resource.py import-3.14!skip
|
||||
plugins/module_utils/client/resource.py import-3.15!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.9!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.10!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.11!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.12!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.13!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.14!skip
|
||||
plugins/module_utils/k8sdynamicclient.py import-3.15!skip
|
||||
plugins/modules/k8s.py validate-modules:parameter-type-not-in-doc
|
||||
plugins/modules/k8s_scale.py validate-modules:parameter-type-not-in-doc
|
||||
plugins/modules/k8s_service.py validate-modules:parameter-type-not-in-doc
|
||||
tests/unit/module_utils/fixtures/clusteroperator.yml yamllint!skip
|
||||
tests/unit/module_utils/fixtures/definitions.yml yamllint!skip
|
||||
tests/unit/module_utils/fixtures/deployments.yml yamllint!skip
|
||||
tests/integration/targets/k8s_delete/files/deployments.yaml yamllint!skip
|
||||
tests/unit/module_utils/fixtures/pods.yml yamllint!skip
|
||||
tests/integration/targets/helm/files/appversionless-chart-v2/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/appversionless-chart/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/test-chart-job/Chart.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/test-chart-v2/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm/files/test-chart/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm_diff/files/test-chart/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/k8s_scale/files/deployment.yaml yamllint!skip
|
||||
plugins/modules/k8s.py validate-modules:return-syntax-error
|
||||
plugins/modules/k8s_scale.py validate-modules:return-syntax-error
|
||||
plugins/modules/k8s_service.py validate-modules:return-syntax-error
|
||||
plugins/modules/k8s_taint.py validate-modules:return-syntax-error
|
||||
tests/integration/targets/helm_diff/files/test-chart-reuse-values/templates/configmap.yaml yamllint!skip
|
||||
tests/integration/targets/helm_diff/files/test-chart-deployment-time/templates/configmap.yaml yamllint!skip
|
||||
plugins/modules/helm.py validate-modules:bad-return-value-key
|
||||
plugins/modules/helm_info.py validate-modules:bad-return-value-key
|
||||
@@ -4,11 +4,11 @@ __metaclass__ = type
|
||||
|
||||
import json
|
||||
import sys
|
||||
from collections.abc import MutableMapping
|
||||
from io import BytesIO
|
||||
|
||||
import ansible.module_utils.basic
|
||||
import pytest
|
||||
from ansible.module_utils.common._collections_compat import MutableMapping
|
||||
from ansible.module_utils.common.text.converters import to_bytes
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright: (c) 2026, Ansible Project
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__metaclass__ = type
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
from ansible_collections.kubernetes.core.plugins.module_utils.helm import (
|
||||
strip_registry_progress,
|
||||
)
|
||||
|
||||
# What helm's registry client prints, verbatim. Since helm 4.2.1 this goes to
|
||||
# stdout ahead of the command's real output (helm/helm#32056).
|
||||
PULLED = "Pulled: registry.example.com/charts/demochart:109.0.1_up1.0.2\n"
|
||||
DIGEST = (
|
||||
"Digest: sha256:41e9b37f85fa7f5df5fc7f2b7b068eb56ae1592784eee28f535563b599850249\n"
|
||||
)
|
||||
PUSHED = "Pushed: registry.example.com/charts/demochart:109.0.1_up1.0.2\n"
|
||||
UNDERSCORE_WARNING = (
|
||||
"registry.example.com/charts/demochart:109.0.1_up1.0.2 contains an underscore.\n"
|
||||
"\n"
|
||||
"OCI artifact references (e.g. tags) do not support the plus sign (+). To support\n"
|
||||
"storing semantic versions, Helm adopts the convention of changing plus (+) to\n"
|
||||
"an underscore (_) in chart version tags when pushing to a registry and back to\n"
|
||||
"a plus (+) when pulling from a registry.\n"
|
||||
)
|
||||
|
||||
# 'helm show chart' output. Note that helm marshals Chart.yaml with sorted keys, so
|
||||
# 'annotations' precedes 'apiVersion' and the metadata does not reliably start with
|
||||
# a fixed key.
|
||||
CHART_YAML = (
|
||||
"annotations:\n"
|
||||
" category: Demo\n"
|
||||
"apiVersion: v2\n"
|
||||
"appVersion: 1.16.0\n"
|
||||
"description: A Helm chart for Kubernetes\n"
|
||||
"name: demochart\n"
|
||||
"type: application\n"
|
||||
"version: 109.0.1+up1.0.2\n"
|
||||
)
|
||||
|
||||
# 'helm template' output.
|
||||
MANIFESTS = (
|
||||
"---\n"
|
||||
"# Source: demochart/templates/serviceaccount.yaml\n"
|
||||
"apiVersion: v1\n"
|
||||
"kind: ServiceAccount\n"
|
||||
"metadata:\n"
|
||||
" name: rel-demochart\n"
|
||||
)
|
||||
|
||||
# 'helm template --output-dir' output.
|
||||
WROTE = (
|
||||
"wrote outdir/demochart/templates/serviceaccount.yaml\n"
|
||||
"wrote outdir/demochart/templates/service.yaml\n"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"payload",
|
||||
[CHART_YAML, MANIFESTS, WROTE, ""],
|
||||
ids=["show_chart", "template", "template_output_dir", "empty"],
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"progress",
|
||||
[
|
||||
"",
|
||||
PULLED + DIGEST,
|
||||
PULLED + DIGEST + UNDERSCORE_WARNING,
|
||||
PUSHED + DIGEST + UNDERSCORE_WARNING,
|
||||
],
|
||||
ids=["none", "pulled_digest", "with_warning", "pushed_with_warning"],
|
||||
)
|
||||
def test_progress_is_stripped_and_payload_is_untouched(progress, payload):
|
||||
assert strip_registry_progress(progress + payload) == payload
|
||||
|
||||
|
||||
def test_show_chart_output_is_parseable_once_stripped():
|
||||
# Unstripped, the free-text warning makes this invalid YAML.
|
||||
out = PULLED + DIGEST + UNDERSCORE_WARNING + CHART_YAML
|
||||
with pytest.raises(yaml.YAMLError):
|
||||
yaml.safe_load(out)
|
||||
|
||||
chart_info = yaml.safe_load(strip_registry_progress(out))
|
||||
assert chart_info["name"] == "demochart"
|
||||
assert chart_info["version"] == "109.0.1+up1.0.2"
|
||||
assert chart_info["annotations"] == {"category": "Demo"}
|
||||
|
||||
|
||||
def test_pulled_and_digest_alone_parse_as_yaml_but_pollute_the_result():
|
||||
# Without the warning the output is still valid YAML, so the pollution is silent.
|
||||
assert yaml.safe_load(PULLED + DIGEST + CHART_YAML)["Pulled"]
|
||||
assert "Pulled" not in yaml.safe_load(
|
||||
strip_registry_progress(PULLED + DIGEST + CHART_YAML)
|
||||
)
|
||||
|
||||
|
||||
def test_reworded_warning_is_left_alone():
|
||||
# A message helm no longer emits verbatim must not be partially consumed: better
|
||||
# to fail loudly than to silently drop a line of real output.
|
||||
reworded = UNDERSCORE_WARNING.replace("plus sign (+)", "plus character (+)")
|
||||
out = PULLED + DIGEST + reworded + CHART_YAML
|
||||
assert strip_registry_progress(out) == reworded + CHART_YAML
|
||||
|
||||
|
||||
def test_progress_like_lines_inside_the_payload_are_kept():
|
||||
payload = "description: |\n Digest: not a helm message\n" + CHART_YAML
|
||||
assert strip_registry_progress(PULLED + payload) == payload
|
||||
@@ -0,0 +1,298 @@
|
||||
# Copyright [2026] [Red Hat, Inc.]
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
# Tests for the to_pod streaming path of K8SCopyToPod. The v4 exec protocol
|
||||
# cannot half-close stdin, so the archive is bounded with `head -c` to give the
|
||||
# remote tar a clean EOF; the module must then keep reading until the API server
|
||||
# closes the connection and check the status reported on the error channel. See
|
||||
# https://github.com/ansible-collections/kubernetes.core/issues/776
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__metaclass__ = type
|
||||
|
||||
import io
|
||||
|
||||
import pytest
|
||||
from ansible_collections.kubernetes.core.plugins.module_utils.copy import K8SCopyToPod
|
||||
|
||||
ERROR_CHANNEL = 3
|
||||
|
||||
SUCCESS = '{"metadata":{},"status":"Success"}'
|
||||
FAILURE = (
|
||||
'{"metadata":{},"status":"Failure","message":"command terminated with'
|
||||
' non-zero exit code","reason":"NonZeroExitCode"}'
|
||||
)
|
||||
|
||||
|
||||
class FakeModuleFailure(Exception):
|
||||
"""Stands in for the SystemExit that AnsibleModule.fail_json raises."""
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
self.kwargs = kwargs
|
||||
super(FakeModuleFailure, self).__init__(kwargs.get("msg"))
|
||||
|
||||
|
||||
class FakeModule:
|
||||
def __init__(self, **params):
|
||||
params.setdefault("copy_timeout", 300)
|
||||
self.params = params
|
||||
self.check_mode = False
|
||||
self.warnings = []
|
||||
|
||||
def fail_json(self, **kwargs):
|
||||
raise FakeModuleFailure(**kwargs)
|
||||
|
||||
def warn(self, warning):
|
||||
self.warnings.append(warning)
|
||||
|
||||
|
||||
class FakeWSClient:
|
||||
"""Minimal stand-in for kubernetes.stream.ws_client.WSClient.
|
||||
|
||||
``close_after`` is the number of ``update()`` calls the connection stays
|
||||
open for once the last chunk has been written, modelling the remote tar
|
||||
consuming the archive and exiting.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
close_after=2,
|
||||
error=SUCCESS,
|
||||
stderr=None,
|
||||
drop_after=None,
|
||||
stderr_early=False,
|
||||
):
|
||||
self.written = []
|
||||
self.closed = False
|
||||
self._open = True
|
||||
self._updates = 0
|
||||
self._close_after = close_after
|
||||
self._error = error
|
||||
self._pending_stderr = stderr
|
||||
self._drop_after = drop_after
|
||||
self._stderr_early = stderr_early
|
||||
self.writes_done = False
|
||||
|
||||
def is_open(self):
|
||||
return self._open
|
||||
|
||||
def update(self, timeout=0):
|
||||
self._updates += 1
|
||||
if self.writes_done and self._updates > self._close_after:
|
||||
self._open = False
|
||||
|
||||
def write_stdin(self, data):
|
||||
if self._drop_after is not None and len(self.written) >= self._drop_after:
|
||||
self._open = False
|
||||
return
|
||||
self.written.append(data)
|
||||
|
||||
def peek_stdout(self):
|
||||
return ""
|
||||
|
||||
def read_stdout(self):
|
||||
return ""
|
||||
|
||||
def peek_stderr(self):
|
||||
# tar only complains once it has started extracting, i.e. after the
|
||||
# whole archive has been handed over, unless it failed outright.
|
||||
if not (self.writes_done or self._stderr_early):
|
||||
return ""
|
||||
return self._pending_stderr or ""
|
||||
|
||||
def read_stderr(self):
|
||||
out, self._pending_stderr = self._pending_stderr, None
|
||||
return out
|
||||
|
||||
def read_channel(self, channel):
|
||||
assert channel == ERROR_CHANNEL
|
||||
return self._error
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
self._open = False
|
||||
|
||||
|
||||
def make_copier(has_shell=True, no_preserve=False, **params):
|
||||
module = FakeModule(**params)
|
||||
copier = K8SCopyToPod.__new__(K8SCopyToPod)
|
||||
copier.module = module
|
||||
copier.namespace = "testing"
|
||||
copier.name = "some-pod"
|
||||
copier.named_temp_file = None
|
||||
copier.no_preserve = no_preserve
|
||||
copier.copy_timeout = module.params["copy_timeout"]
|
||||
copier.can_bound_stream = lambda: has_shell
|
||||
return copier
|
||||
|
||||
|
||||
def stream_archive(copier, response, size, wait_for_exit=True):
|
||||
"""Drive _stream_tar_to_pod, marking the writes finished for the fake."""
|
||||
payload = io.BytesIO(b"x" * size)
|
||||
original_read = payload.read
|
||||
|
||||
def read(n):
|
||||
data = original_read(n)
|
||||
if not data:
|
||||
response.writes_done = True
|
||||
return data
|
||||
|
||||
payload.read = read
|
||||
return copier._stream_tar_to_pod(response, payload, wait_for_exit)
|
||||
|
||||
|
||||
def test_waits_for_tar_to_exit_before_closing():
|
||||
"""The connection must not be closed until the remote process is done."""
|
||||
copier = make_copier()
|
||||
response = FakeWSClient(close_after=5)
|
||||
|
||||
error, stdout, stderr = stream_archive(
|
||||
copier, response, 3 * K8SCopyToPod.CHUNK_SIZE
|
||||
)
|
||||
|
||||
assert error["status"] == "Success"
|
||||
assert stdout == []
|
||||
assert stderr == []
|
||||
# Whole archive sent, in CHUNK_SIZE pieces.
|
||||
assert len(response.written) == 3
|
||||
assert sum(len(c) for c in response.written) == 3 * K8SCopyToPod.CHUNK_SIZE
|
||||
# Closed only after the server hung up, not right after the last write.
|
||||
assert response.closed
|
||||
assert response._updates > 3
|
||||
|
||||
|
||||
def test_partial_write_is_not_reported_as_success():
|
||||
"""A connection dropped mid-archive must fail, not silently truncate."""
|
||||
copier = make_copier()
|
||||
response = FakeWSClient(drop_after=2)
|
||||
|
||||
with pytest.raises(FakeModuleFailure) as exc:
|
||||
stream_archive(copier, response, 5 * K8SCopyToPod.CHUNK_SIZE)
|
||||
|
||||
assert "the remote file is incomplete" in exc.value.kwargs["msg"]
|
||||
assert len(response.written) == 2
|
||||
assert response.closed
|
||||
|
||||
|
||||
def test_early_close_reports_what_tar_said():
|
||||
"""The remote error must not be masked by the generic truncation message."""
|
||||
copier = make_copier()
|
||||
response = FakeWSClient(
|
||||
drop_after=2,
|
||||
stderr="tar: /etc/foo: Cannot open: Read-only file system",
|
||||
stderr_early=True,
|
||||
)
|
||||
|
||||
with pytest.raises(FakeModuleFailure) as exc:
|
||||
stream_archive(copier, response, 5 * K8SCopyToPod.CHUNK_SIZE)
|
||||
|
||||
assert "the remote file is incomplete" in exc.value.kwargs["msg"]
|
||||
assert "Read-only file system" in exc.value.kwargs["msg"]
|
||||
|
||||
|
||||
def test_non_zero_tar_exit_is_surfaced():
|
||||
"""A Failure status on the error channel must reach the caller."""
|
||||
copier = make_copier()
|
||||
response = FakeWSClient(error=FAILURE)
|
||||
|
||||
error, _stdout, _stderr = stream_archive(copier, response, K8SCopyToPod.CHUNK_SIZE)
|
||||
|
||||
assert error["status"] == "Failure"
|
||||
assert error["reason"] == "NonZeroExitCode"
|
||||
|
||||
|
||||
def test_stderr_is_collected_while_draining():
|
||||
"""Output tar writes after the last chunk must still be captured."""
|
||||
copier = make_copier()
|
||||
response = FakeWSClient(stderr="tar: /foo: Cannot utime: Operation not permitted")
|
||||
|
||||
_error, _stdout, stderr = stream_archive(copier, response, K8SCopyToPod.CHUNK_SIZE)
|
||||
|
||||
assert stderr == ["tar: /foo: Cannot utime: Operation not permitted"]
|
||||
|
||||
|
||||
def test_drain_honours_copy_timeout(monkeypatch):
|
||||
"""A remote tar that never exits must time out instead of hanging."""
|
||||
copier = make_copier(copy_timeout=30)
|
||||
response = FakeWSClient(close_after=10**6)
|
||||
|
||||
# Time only moves past the deadline once the archive has been sent, so the
|
||||
# timeout is exercised in the drain loop rather than the write loop.
|
||||
monkeypatch.setattr(
|
||||
"time.monotonic", lambda: 10**6 if response.writes_done else 0
|
||||
)
|
||||
|
||||
with pytest.raises(FakeModuleFailure) as exc:
|
||||
stream_archive(copier, response, K8SCopyToPod.CHUNK_SIZE)
|
||||
|
||||
assert "waiting for tar to finish extracting" in exc.value.kwargs["msg"]
|
||||
assert response.closed
|
||||
|
||||
|
||||
def test_archive_is_bounded_with_head():
|
||||
"""head -c gives the remote tar a clean EOF the v4 protocol cannot."""
|
||||
copier = make_copier()
|
||||
|
||||
command, wait_for_exit = copier.remote_command("/tmp/foo", 1003520)
|
||||
|
||||
assert wait_for_exit is True
|
||||
assert command == ["/bin/sh", "-c", "head -c 1003520 | tar -xmf - -C /"]
|
||||
assert copier.module.warnings == []
|
||||
|
||||
|
||||
def test_bounded_command_carries_no_preserve():
|
||||
copier = make_copier(no_preserve=True)
|
||||
|
||||
command, _wait = copier.remote_command("/tmp/foo", 512)
|
||||
|
||||
assert command[2] == (
|
||||
"head -c 512 | tar --no-same-permissions --no-same-owner -xmf - -C /"
|
||||
)
|
||||
|
||||
|
||||
def test_relative_destination_is_not_anchored():
|
||||
"""Only absolute destinations get -C /, as before."""
|
||||
copier = make_copier()
|
||||
|
||||
command, _wait = copier.remote_command("tmp/foo", 512)
|
||||
|
||||
assert command[2] == "head -c 512 | tar -xmf -"
|
||||
|
||||
|
||||
def test_shell_less_container_falls_back_and_warns():
|
||||
"""Without a shell the copy still runs, but completion is unverifiable."""
|
||||
copier = make_copier(has_shell=False)
|
||||
|
||||
command, wait_for_exit = copier.remote_command("/tmp/foo", 512)
|
||||
|
||||
assert wait_for_exit is False
|
||||
assert command == ["tar", "-xmf", "-", "-C", "/"]
|
||||
assert len(copier.module.warnings) == 1
|
||||
assert "cannot confirm the copy" in copier.module.warnings[0]
|
||||
|
||||
|
||||
def test_fallback_path_does_not_wait_for_exit():
|
||||
"""The legacy path must not block on a tar that will never exit."""
|
||||
copier = make_copier(has_shell=False)
|
||||
response = FakeWSClient(close_after=10**6)
|
||||
|
||||
error, _stdout, _stderr = stream_archive(
|
||||
copier, response, K8SCopyToPod.CHUNK_SIZE, wait_for_exit=False
|
||||
)
|
||||
|
||||
# No exit status is available on this path.
|
||||
assert error is None
|
||||
assert response.closed
|
||||
assert sum(len(c) for c in response.written) == K8SCopyToPod.CHUNK_SIZE
|
||||
@@ -23,6 +23,79 @@ from ansible_collections.kubernetes.core.tests.unit.utils.ansible_module_mock im
|
||||
set_module_args,
|
||||
)
|
||||
|
||||
CHART_INFO = {
|
||||
"apiVersion": "v2",
|
||||
"appVersion": "default",
|
||||
"description": "A chart used in molecule tests",
|
||||
"name": "test-chart",
|
||||
"type": "application",
|
||||
"version": "0.1.0",
|
||||
}
|
||||
|
||||
|
||||
def patch_ansible_module(test_case):
|
||||
"""Patch AnsibleModule's exit/fail/bin-path hooks for the duration of test_case."""
|
||||
mock_module_helper = patch.multiple(
|
||||
basic.AnsibleModule,
|
||||
exit_json=exit_json,
|
||||
fail_json=fail_json,
|
||||
get_bin_path=get_bin_path,
|
||||
)
|
||||
mock_module_helper.start()
|
||||
test_case.addCleanup(mock_module_helper.stop)
|
||||
|
||||
|
||||
def deploy_command_for_version(args, helm_version):
|
||||
"""Run helm.main() against a mocked helm of helm_version and return its command.
|
||||
|
||||
Only the fresh-install path is mocked, so the caller sees the command built by
|
||||
deploy(). Failures raised by the module (AnsibleFailJson) propagate to the test.
|
||||
"""
|
||||
set_module_args(args)
|
||||
helm.get_release_status = MagicMock(return_value=None)
|
||||
helm.fetch_chart_info = MagicMock(return_value=CHART_INFO)
|
||||
with patch.object(
|
||||
helm.AnsibleHelmModule, "get_helm_version", return_value=helm_version
|
||||
):
|
||||
with patch.object(basic.AnsibleModule, "run_command") as mock_run_command:
|
||||
mock_run_command.return_value = (0, "configuration updated", "")
|
||||
try:
|
||||
helm.main()
|
||||
except AnsibleExitJson as exc:
|
||||
return exc.args[0]["command"]
|
||||
raise AssertionError("helm.main() did not exit successfully")
|
||||
|
||||
|
||||
def diff_command_for_version(args, helm_version="3.17.0", helm_diff_version="3.14.0"):
|
||||
"""Run helm.main() against an existing release and return the 'helm diff' command.
|
||||
|
||||
The release is reported as deployed and helm diff as installed, so main() takes the
|
||||
idempotency branch. The diff output is empty, so nothing is deployed afterwards and
|
||||
the first command run is the one helmdiff_check() built.
|
||||
"""
|
||||
set_module_args(args)
|
||||
helm.get_release_status = MagicMock(
|
||||
return_value={
|
||||
"status": "deployed",
|
||||
"values": {},
|
||||
"release_values": {},
|
||||
"chart": "{0}-{1}".format(CHART_INFO["name"], CHART_INFO["version"]),
|
||||
"app_version": CHART_INFO["appVersion"],
|
||||
}
|
||||
)
|
||||
helm.fetch_chart_info = MagicMock(return_value=CHART_INFO)
|
||||
helm.get_plugin_version = MagicMock(return_value=helm_diff_version)
|
||||
with patch.object(
|
||||
helm.AnsibleHelmModule, "get_helm_version", return_value=helm_version
|
||||
):
|
||||
with patch.object(basic.AnsibleModule, "run_command") as mock_run_command:
|
||||
mock_run_command.return_value = (0, "", "")
|
||||
try:
|
||||
helm.main()
|
||||
except AnsibleExitJson:
|
||||
return mock_run_command.call_args_list[0][0][0]
|
||||
raise AssertionError("helm.main() did not exit successfully")
|
||||
|
||||
|
||||
class TestDependencyUpdateWithoutChartRepoUrlOption(unittest.TestCase):
|
||||
def setUp(self):
|
||||
@@ -716,39 +789,10 @@ class TestAtomicFlagHelmVersion(unittest.TestCase):
|
||||
"""Helm v4 renamed '--atomic' to '--rollback-on-failure' (issue #1143)."""
|
||||
|
||||
def setUp(self):
|
||||
self.mock_module_helper = patch.multiple(
|
||||
basic.AnsibleModule,
|
||||
exit_json=exit_json,
|
||||
fail_json=fail_json,
|
||||
get_bin_path=get_bin_path,
|
||||
)
|
||||
self.mock_module_helper.start()
|
||||
self.addCleanup(self.mock_module_helper.stop)
|
||||
|
||||
self.chart_info = {
|
||||
"apiVersion": "v2",
|
||||
"appVersion": "default",
|
||||
"description": "A chart used in molecule tests",
|
||||
"name": "test-chart",
|
||||
"type": "application",
|
||||
"version": "0.1.0",
|
||||
}
|
||||
|
||||
def _run_with_version(self, args, helm_version):
|
||||
set_module_args(args)
|
||||
helm.get_release_status = MagicMock(return_value=None)
|
||||
helm.fetch_chart_info = MagicMock(return_value=self.chart_info)
|
||||
with patch.object(
|
||||
helm.AnsibleHelmModule, "get_helm_version", return_value=helm_version
|
||||
):
|
||||
with patch.object(basic.AnsibleModule, "run_command") as mock_run_command:
|
||||
mock_run_command.return_value = (0, "configuration updated", "")
|
||||
with self.assertRaises(AnsibleExitJson) as result:
|
||||
helm.main()
|
||||
return result.exception.args[0]["command"]
|
||||
patch_ansible_module(self)
|
||||
|
||||
def test_atomic_uses_atomic_flag_on_helm_v3(self):
|
||||
command = self._run_with_version(
|
||||
command = deploy_command_for_version(
|
||||
{
|
||||
"release_name": "test",
|
||||
"release_namespace": "test",
|
||||
@@ -761,7 +805,7 @@ class TestAtomicFlagHelmVersion(unittest.TestCase):
|
||||
assert "--rollback-on-failure" not in command
|
||||
|
||||
def test_atomic_uses_rollback_on_failure_on_helm_v4(self):
|
||||
command = self._run_with_version(
|
||||
command = deploy_command_for_version(
|
||||
{
|
||||
"release_name": "test",
|
||||
"release_namespace": "test",
|
||||
@@ -775,7 +819,7 @@ class TestAtomicFlagHelmVersion(unittest.TestCase):
|
||||
|
||||
def test_atomic_with_replace_uses_rollback_on_failure_on_helm_v4(self):
|
||||
# 'replace' uses 'helm install', where '--atomic' is removed in v4.
|
||||
command = self._run_with_version(
|
||||
command = deploy_command_for_version(
|
||||
{
|
||||
"release_name": "test",
|
||||
"release_namespace": "test",
|
||||
@@ -788,3 +832,396 @@ class TestAtomicFlagHelmVersion(unittest.TestCase):
|
||||
assert " install " in command
|
||||
assert "--rollback-on-failure" in command
|
||||
assert "--atomic" not in command
|
||||
|
||||
|
||||
class TestCleanupOnFail(unittest.TestCase):
|
||||
"""'--cleanup-on-fail' is upgrade-only and unchanged in Helm v4 (issue #1198)."""
|
||||
|
||||
def setUp(self):
|
||||
patch_ansible_module(self)
|
||||
|
||||
def test_cleanup_on_fail_not_set_by_default(self):
|
||||
command = deploy_command_for_version(
|
||||
{
|
||||
"release_name": "test",
|
||||
"release_namespace": "test",
|
||||
"chart_ref": "chart1",
|
||||
},
|
||||
"3.17.0",
|
||||
)
|
||||
assert "--cleanup-on-fail" not in command
|
||||
|
||||
def test_cleanup_on_fail_on_helm_v3(self):
|
||||
# '--cleanup-on-fail' exists since helm 3.0.0, the module-wide minimum.
|
||||
command = deploy_command_for_version(
|
||||
{
|
||||
"release_name": "test",
|
||||
"release_namespace": "test",
|
||||
"chart_ref": "chart1",
|
||||
"cleanup_on_fail": True,
|
||||
},
|
||||
"3.0.0",
|
||||
)
|
||||
assert " upgrade -i" in command
|
||||
assert "--cleanup-on-fail" in command
|
||||
|
||||
def test_cleanup_on_fail_keeps_same_flag_on_helm_v4(self):
|
||||
# Unlike '--atomic', the flag was not renamed in Helm v4.
|
||||
command = deploy_command_for_version(
|
||||
{
|
||||
"release_name": "test",
|
||||
"release_namespace": "test",
|
||||
"chart_ref": "chart1",
|
||||
"cleanup_on_fail": True,
|
||||
},
|
||||
"4.0.0",
|
||||
)
|
||||
assert "--cleanup-on-fail" in command
|
||||
|
||||
def test_cleanup_on_fail_combines_with_atomic_on_helm_v3(self):
|
||||
command = deploy_command_for_version(
|
||||
{
|
||||
"release_name": "test",
|
||||
"release_namespace": "test",
|
||||
"chart_ref": "chart1",
|
||||
"atomic": True,
|
||||
"cleanup_on_fail": True,
|
||||
},
|
||||
"3.17.0",
|
||||
)
|
||||
assert "--atomic" in command
|
||||
assert "--rollback-on-failure" not in command
|
||||
assert "--cleanup-on-fail" in command
|
||||
|
||||
def test_cleanup_on_fail_combines_with_atomic_on_helm_v4(self):
|
||||
command = deploy_command_for_version(
|
||||
{
|
||||
"release_name": "test",
|
||||
"release_namespace": "test",
|
||||
"chart_ref": "chart1",
|
||||
"atomic": True,
|
||||
"cleanup_on_fail": True,
|
||||
},
|
||||
"4.0.0",
|
||||
)
|
||||
assert "--rollback-on-failure" in command
|
||||
assert "--atomic" not in command
|
||||
assert "--cleanup-on-fail" in command
|
||||
|
||||
def test_cleanup_on_fail_with_replace_fails(self):
|
||||
# 'replace' deploys via 'helm install', which has no '--cleanup-on-fail'.
|
||||
with self.assertRaises(AnsibleFailJson):
|
||||
deploy_command_for_version(
|
||||
{
|
||||
"release_name": "test",
|
||||
"release_namespace": "test",
|
||||
"chart_ref": "chart1",
|
||||
"cleanup_on_fail": True,
|
||||
"replace": True,
|
||||
},
|
||||
"3.17.0",
|
||||
)
|
||||
|
||||
|
||||
class TestValueReuseOptions(unittest.TestCase):
|
||||
"""reset_values wins over reuse_values, and both are upgrade-only (issue #1229)."""
|
||||
|
||||
def setUp(self):
|
||||
patch_ansible_module(self)
|
||||
|
||||
def test_reuse_values_alone_is_overridden_by_the_reset_values_default(self):
|
||||
# What the pre-fix example in the docs produced: helm ignores '--reuse-values'.
|
||||
command = deploy_command_for_version(
|
||||
{
|
||||
"release_name": "test",
|
||||
"release_namespace": "test",
|
||||
"chart_ref": "chart1",
|
||||
"reuse_values": True,
|
||||
},
|
||||
"3.17.0",
|
||||
)
|
||||
assert "--reset-values" in command
|
||||
assert "--reuse-values=True" in command
|
||||
|
||||
def test_reuse_values_with_reset_values_disabled(self):
|
||||
command = deploy_command_for_version(
|
||||
{
|
||||
"release_name": "test",
|
||||
"release_namespace": "test",
|
||||
"chart_ref": "chart1",
|
||||
"reuse_values": True,
|
||||
"reset_values": False,
|
||||
},
|
||||
"3.17.0",
|
||||
)
|
||||
assert "--reset-values" not in command
|
||||
assert "--reuse-values=True" in command
|
||||
|
||||
def test_reset_then_reuse_values_with_reset_values_disabled(self):
|
||||
command = deploy_command_for_version(
|
||||
{
|
||||
"release_name": "test",
|
||||
"release_namespace": "test",
|
||||
"chart_ref": "chart1",
|
||||
"reset_then_reuse_values": True,
|
||||
"reset_values": False,
|
||||
},
|
||||
"3.17.0",
|
||||
)
|
||||
assert "--reset-values" not in command
|
||||
assert "--reset-then-reuse-values" in command
|
||||
|
||||
def test_reuse_values_with_replace_is_dropped_and_warns(self):
|
||||
# 'replace' deploys via 'helm install', which has no '--reuse-values'.
|
||||
with patch.object(basic.AnsibleModule, "warn") as mock_warn:
|
||||
command = deploy_command_for_version(
|
||||
{
|
||||
"release_name": "test",
|
||||
"release_namespace": "test",
|
||||
"chart_ref": "chart1",
|
||||
"reuse_values": True,
|
||||
"replace": True,
|
||||
},
|
||||
"3.17.0",
|
||||
)
|
||||
assert " install" in command
|
||||
assert "--reuse-values" not in command
|
||||
warnings = [call.args[0] for call in mock_warn.call_args_list]
|
||||
assert any(
|
||||
"reuse_values is ignored because replace=true" in warning
|
||||
for warning in warnings
|
||||
)
|
||||
|
||||
def test_reuse_values_false_with_replace_is_dropped_and_warns(self):
|
||||
# Even 'reuse_values: false' used to emit '--reuse-values=False' on install.
|
||||
with patch.object(basic.AnsibleModule, "warn") as mock_warn:
|
||||
command = deploy_command_for_version(
|
||||
{
|
||||
"release_name": "test",
|
||||
"release_namespace": "test",
|
||||
"chart_ref": "chart1",
|
||||
"reuse_values": False,
|
||||
"replace": True,
|
||||
},
|
||||
"3.17.0",
|
||||
)
|
||||
assert "--reuse-values" not in command
|
||||
warnings = [call.args[0] for call in mock_warn.call_args_list]
|
||||
assert any(
|
||||
"reuse_values is ignored because replace=true" in warning
|
||||
for warning in warnings
|
||||
)
|
||||
|
||||
def test_reset_then_reuse_values_with_replace_is_dropped_and_warns(self):
|
||||
with patch.object(basic.AnsibleModule, "warn") as mock_warn:
|
||||
command = deploy_command_for_version(
|
||||
{
|
||||
"release_name": "test",
|
||||
"release_namespace": "test",
|
||||
"chart_ref": "chart1",
|
||||
"reset_then_reuse_values": True,
|
||||
"replace": True,
|
||||
},
|
||||
"3.17.0",
|
||||
)
|
||||
assert "--reset-then-reuse-values" not in command
|
||||
warnings = [call.args[0] for call in mock_warn.call_args_list]
|
||||
assert any(
|
||||
"reset_then_reuse_values is ignored because replace=true" in warning
|
||||
for warning in warnings
|
||||
)
|
||||
|
||||
def test_replace_alone_keeps_working(self):
|
||||
command = deploy_command_for_version(
|
||||
{
|
||||
"release_name": "test",
|
||||
"release_namespace": "test",
|
||||
"chart_ref": "chart1",
|
||||
"replace": True,
|
||||
},
|
||||
"3.17.0",
|
||||
)
|
||||
assert " install" in command
|
||||
assert "--reuse-values" not in command
|
||||
assert "--reset-values" not in command
|
||||
|
||||
def test_reuse_values_alone_warns(self):
|
||||
with patch.object(basic.AnsibleModule, "warn") as mock_warn:
|
||||
deploy_command_for_version(
|
||||
{
|
||||
"release_name": "test",
|
||||
"release_namespace": "test",
|
||||
"chart_ref": "chart1",
|
||||
"reuse_values": True,
|
||||
},
|
||||
"3.17.0",
|
||||
)
|
||||
warnings = [call.args[0] for call in mock_warn.call_args_list]
|
||||
assert any("reuse_values is ignored" in warning for warning in warnings)
|
||||
|
||||
def test_reset_then_reuse_values_alone_warns(self):
|
||||
with patch.object(basic.AnsibleModule, "warn") as mock_warn:
|
||||
deploy_command_for_version(
|
||||
{
|
||||
"release_name": "test",
|
||||
"release_namespace": "test",
|
||||
"chart_ref": "chart1",
|
||||
"reset_then_reuse_values": True,
|
||||
},
|
||||
"3.17.0",
|
||||
)
|
||||
warnings = [call.args[0] for call in mock_warn.call_args_list]
|
||||
assert any(
|
||||
"reset_then_reuse_values is ignored" in warning for warning in warnings
|
||||
)
|
||||
|
||||
def test_reset_then_reuse_values_warns_when_reuse_values_wins(self):
|
||||
with patch.object(basic.AnsibleModule, "warn") as mock_warn:
|
||||
deploy_command_for_version(
|
||||
{
|
||||
"release_name": "test",
|
||||
"release_namespace": "test",
|
||||
"chart_ref": "chart1",
|
||||
"reuse_values": True,
|
||||
"reset_then_reuse_values": True,
|
||||
"reset_values": False,
|
||||
},
|
||||
"3.17.0",
|
||||
)
|
||||
warnings = [call.args[0] for call in mock_warn.call_args_list]
|
||||
assert any(
|
||||
"reset_then_reuse_values is ignored because reuse_values is true" in warning
|
||||
for warning in warnings
|
||||
)
|
||||
|
||||
def test_no_warning_when_options_are_combined_correctly(self):
|
||||
with patch.object(basic.AnsibleModule, "warn") as mock_warn:
|
||||
deploy_command_for_version(
|
||||
{
|
||||
"release_name": "test",
|
||||
"release_namespace": "test",
|
||||
"chart_ref": "chart1",
|
||||
"reuse_values": True,
|
||||
"reset_values": False,
|
||||
},
|
||||
"3.17.0",
|
||||
)
|
||||
assert mock_warn.call_args_list == []
|
||||
|
||||
|
||||
class TestValueReuseOptionsWithHelmDiff(unittest.TestCase):
|
||||
"""The same options on the idempotency path, where 'helm diff' builds the command."""
|
||||
|
||||
def setUp(self):
|
||||
patch_ansible_module(self)
|
||||
|
||||
def test_reuse_values_alone_is_overridden_by_the_reset_values_default(self):
|
||||
# helm diff is handed both flags and applies helm's precedence, which is why
|
||||
# 'reuse_values' on its own still reports a change (issue #1229).
|
||||
command = diff_command_for_version(
|
||||
{
|
||||
"release_name": "test",
|
||||
"release_namespace": "test",
|
||||
"chart_ref": "chart1",
|
||||
"reuse_values": True,
|
||||
}
|
||||
)
|
||||
assert "--reset-values=True" in command
|
||||
assert "--reuse-values" in command
|
||||
|
||||
def test_reuse_values_with_reset_values_disabled(self):
|
||||
command = diff_command_for_version(
|
||||
{
|
||||
"release_name": "test",
|
||||
"release_namespace": "test",
|
||||
"chart_ref": "chart1",
|
||||
"reuse_values": True,
|
||||
"reset_values": False,
|
||||
}
|
||||
)
|
||||
assert "--reset-values=False" in command
|
||||
assert "--reuse-values" in command
|
||||
|
||||
def test_reset_then_reuse_values_with_reset_values_disabled(self):
|
||||
command = diff_command_for_version(
|
||||
{
|
||||
"release_name": "test",
|
||||
"release_namespace": "test",
|
||||
"chart_ref": "chart1",
|
||||
"reset_then_reuse_values": True,
|
||||
"reset_values": False,
|
||||
}
|
||||
)
|
||||
assert "--reset-values=False" in command
|
||||
assert "--reset-then-reuse-values" in command
|
||||
|
||||
def test_reuse_values_with_replace_is_dropped_and_warns(self):
|
||||
with patch.object(basic.AnsibleModule, "warn") as mock_warn:
|
||||
command = diff_command_for_version(
|
||||
{
|
||||
"release_name": "test",
|
||||
"release_namespace": "test",
|
||||
"chart_ref": "chart1",
|
||||
"reuse_values": True,
|
||||
"replace": True,
|
||||
}
|
||||
)
|
||||
assert "--reuse-values" not in command
|
||||
assert "--reset-values" not in command
|
||||
warnings = [call.args[0] for call in mock_warn.call_args_list]
|
||||
assert any(
|
||||
"reuse_values is ignored because replace=true" in warning
|
||||
for warning in warnings
|
||||
)
|
||||
|
||||
def test_reset_then_reuse_values_with_replace_is_dropped_and_warns(self):
|
||||
with patch.object(basic.AnsibleModule, "warn") as mock_warn:
|
||||
command = diff_command_for_version(
|
||||
{
|
||||
"release_name": "test",
|
||||
"release_namespace": "test",
|
||||
"chart_ref": "chart1",
|
||||
"reset_then_reuse_values": True,
|
||||
"replace": True,
|
||||
}
|
||||
)
|
||||
assert "--reset-then-reuse-values" not in command
|
||||
warnings = [call.args[0] for call in mock_warn.call_args_list]
|
||||
assert any(
|
||||
"reset_then_reuse_values is ignored because replace=true" in warning
|
||||
for warning in warnings
|
||||
)
|
||||
|
||||
def test_reset_then_reuse_values_requires_helm_3_14(self):
|
||||
with self.assertRaises(AnsibleFailJson) as result:
|
||||
diff_command_for_version(
|
||||
{
|
||||
"release_name": "test",
|
||||
"release_namespace": "test",
|
||||
"chart_ref": "chart1",
|
||||
"reset_then_reuse_values": True,
|
||||
"reset_values": False,
|
||||
},
|
||||
helm_version="3.13.0",
|
||||
)
|
||||
assert (
|
||||
"reset_then_reuse_values requires helm >= 3.14.0"
|
||||
in result.exception.args[0]["msg"]
|
||||
)
|
||||
|
||||
def test_reset_then_reuse_values_requires_helm_diff_3_9_12(self):
|
||||
with self.assertRaises(AnsibleFailJson) as result:
|
||||
diff_command_for_version(
|
||||
{
|
||||
"release_name": "test",
|
||||
"release_namespace": "test",
|
||||
"chart_ref": "chart1",
|
||||
"reset_then_reuse_values": True,
|
||||
"reset_values": False,
|
||||
},
|
||||
helm_diff_version="3.9.0",
|
||||
)
|
||||
assert (
|
||||
"reset_then_reuse_values requires helm diff >= 3.9.12"
|
||||
in result.exception.args[0]["msg"]
|
||||
)
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__metaclass__ = type
|
||||
|
||||
import sys
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from ansible.plugins.lookup import LookupBase as StandardLookupBase
|
||||
|
||||
|
||||
class TestK8sTurboMode:
|
||||
"""Test turbo mode version checking in k8s lookup plugin."""
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def cleanup_k8s_module(self):
|
||||
"""Ensure clean module state before each test."""
|
||||
sys.modules.pop("ansible_collections.kubernetes.core.plugins.lookup.k8s", None)
|
||||
|
||||
@pytest.mark.parametrize("ansible_version", ["2.19.0", "2.21.4"])
|
||||
def test_turbo_mode_disabled_on_newer_ansible(self, monkeypatch, ansible_version):
|
||||
"""Test that turbo mode is disabled on ansible-core >= 2.19.0."""
|
||||
monkeypatch.setenv("ENABLE_TURBO_MODE", "true")
|
||||
mock_display = MagicMock()
|
||||
|
||||
with patch.dict(
|
||||
"sys.modules",
|
||||
{
|
||||
"ansible.module_utils.ansible_release": MagicMock(
|
||||
__version__=ansible_version
|
||||
),
|
||||
"ansible.utils.display": MagicMock(Display=lambda: mock_display),
|
||||
},
|
||||
):
|
||||
from ansible_collections.kubernetes.core.plugins.lookup import k8s
|
||||
|
||||
mock_display.deprecated.assert_called()
|
||||
assert (
|
||||
"ENABLE_TURBO_MODE is deprecated"
|
||||
in mock_display.deprecated.call_args[0][0]
|
||||
)
|
||||
|
||||
mock_display.warning.assert_called()
|
||||
assert (
|
||||
f"ENABLE_TURBO_MODE is ignored on ansible-core {ansible_version}"
|
||||
in mock_display.warning.call_args[0][0]
|
||||
)
|
||||
assert "ansible-core < 2.19.0 only" in mock_display.warning.call_args[0][0]
|
||||
|
||||
assert k8s.LookupBase == StandardLookupBase
|
||||
|
||||
def test_turbo_mode_enabled_on_ansible_core_2_18(self, monkeypatch):
|
||||
"""Test that turbo mode is still enabled on ansible-core < 2.19.0."""
|
||||
monkeypatch.setenv("ENABLE_TURBO_MODE", "true")
|
||||
mock_display = MagicMock()
|
||||
mock_turbo_lookup = MagicMock()
|
||||
|
||||
with patch.dict(
|
||||
"sys.modules",
|
||||
{
|
||||
"ansible.module_utils.ansible_release": MagicMock(__version__="2.18.0"),
|
||||
"ansible.utils.display": MagicMock(Display=lambda: mock_display),
|
||||
"ansible_collections.cloud.common.plugins.plugin_utils.turbo.lookup": mock_turbo_lookup,
|
||||
},
|
||||
):
|
||||
from ansible_collections.kubernetes.core.plugins.lookup import ( # noqa: F401
|
||||
k8s,
|
||||
)
|
||||
|
||||
mock_display.deprecated.assert_called()
|
||||
assert not mock_display.warning.called
|
||||
|
||||
def test_turbo_mode_disabled_when_env_not_set(self, monkeypatch):
|
||||
"""Test that turbo mode is disabled when ENABLE_TURBO_MODE is not set."""
|
||||
monkeypatch.delenv("ENABLE_TURBO_MODE", raising=False)
|
||||
mock_display = MagicMock()
|
||||
|
||||
with patch.dict(
|
||||
"sys.modules",
|
||||
{
|
||||
"ansible.module_utils.ansible_release": MagicMock(__version__="2.18.0"),
|
||||
"ansible.utils.display": MagicMock(Display=lambda: mock_display),
|
||||
},
|
||||
):
|
||||
from ansible_collections.kubernetes.core.plugins.lookup import k8s
|
||||
|
||||
mock_display.deprecated.assert_not_called()
|
||||
mock_display.warning.assert_not_called()
|
||||
assert k8s.LookupBase == StandardLookupBase
|
||||
@@ -0,0 +1,156 @@
|
||||
# Copyright (c) 2026 Yuriy Novostavskiy
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
# implied. See the License for the specific language governing
|
||||
# permissions and limitations under the License.
|
||||
#
|
||||
# This file is licensed permissively rather than under the collection's
|
||||
# GPL-3.0-or-later because it lives outside plugins/ and imports no
|
||||
# GPL-licensed code: membership is read statically with ast, so nothing from
|
||||
# ansible-core or plugins/ is imported. See the collection requirements,
|
||||
# "Licensing" section.
|
||||
|
||||
# Guards the action groups declared in meta/runtime.yml.
|
||||
#
|
||||
# A module belongs in an action group if and only if it accepts that group's
|
||||
# shared authentication options, because module_defaults set on a group is
|
||||
# applied to every member. A member that does not accept the options fails with
|
||||
# "Unsupported parameters"; a non-member that does accept them silently ignores
|
||||
# the defaults the user set. Both directions are bugs, so both are asserted.
|
||||
#
|
||||
# Membership is derived from whether a module builds its argument spec from the
|
||||
# shared constant, which is how every module in the collection does it today.
|
||||
|
||||
import ast
|
||||
import os
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
COLLECTION_ROOT = os.path.dirname(
|
||||
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
)
|
||||
MODULES_DIR = os.path.join(COLLECTION_ROOT, "plugins", "modules")
|
||||
RUNTIME_YML = os.path.join(COLLECTION_ROOT, "meta", "runtime.yml")
|
||||
|
||||
# action group -> the module_utils file defining its shared spec, and the constant name
|
||||
SHARED_ARG_SPECS = {
|
||||
"k8s": {"module_utils": "args_common", "constant": "AUTH_ARG_SPEC"},
|
||||
"helm": {"module_utils": "helm_args_common", "constant": "HELM_AUTH_ARG_SPEC"},
|
||||
}
|
||||
|
||||
# Modules that intentionally stay out of the groups, with the reason. Listed
|
||||
# explicitly so that adding one back is a deliberate decision rather than an
|
||||
# oversight. See https://github.com/ansible-collections/kubernetes.core/issues/577
|
||||
EXCLUDED_FROM_GROUPS = {
|
||||
"helm_pull": "accepts only binary_path, not the shared helm auth options",
|
||||
"helm_template": "accepts only binary_path, not the shared helm auth options",
|
||||
"helm_registry_auth": "its 'host' is an OCI registry URL, not a Kubernetes API server",
|
||||
"kubeconfig": "writes a kubeconfig file locally, takes no cluster connection options",
|
||||
}
|
||||
|
||||
|
||||
def _module_names():
|
||||
return sorted(
|
||||
name[:-3]
|
||||
for name in os.listdir(MODULES_DIR)
|
||||
if name.endswith(".py") and name != "__init__.py"
|
||||
)
|
||||
|
||||
|
||||
def _shared_specs_used_by(module_name):
|
||||
"""Return the shared arg-spec constants a module imports."""
|
||||
path = os.path.join(MODULES_DIR, module_name + ".py")
|
||||
with open(path, "rb") as handle:
|
||||
tree = ast.parse(handle.read(), filename=path)
|
||||
|
||||
group_of_constant = {
|
||||
spec["constant"]: group for group, spec in SHARED_ARG_SPECS.items()
|
||||
}
|
||||
modules_of_interest = {spec["module_utils"] for spec in SHARED_ARG_SPECS.values()}
|
||||
|
||||
used = set()
|
||||
for node in ast.walk(tree):
|
||||
if not isinstance(node, ast.ImportFrom) or not node.module:
|
||||
continue
|
||||
if node.module.rsplit(".", 1)[-1] not in modules_of_interest:
|
||||
continue
|
||||
for alias in node.names:
|
||||
if alias.name in group_of_constant:
|
||||
used.add(group_of_constant[alias.name])
|
||||
return used
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def action_groups():
|
||||
with open(RUNTIME_YML) as handle:
|
||||
return yaml.safe_load(handle)["action_groups"]
|
||||
|
||||
|
||||
def test_runtime_declares_expected_action_groups(action_groups):
|
||||
assert set(action_groups) == set(SHARED_ARG_SPECS), (
|
||||
"meta/runtime.yml declares action groups this test does not know about. "
|
||||
"Add the new group and its shared arg-spec constant to SHARED_ARG_SPECS."
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("group", sorted(SHARED_ARG_SPECS))
|
||||
def test_action_group_members_exist(action_groups, group):
|
||||
known = set(_module_names())
|
||||
missing = sorted(set(action_groups[group]) - known)
|
||||
assert not missing, (
|
||||
"meta/runtime.yml lists modules in the '%s' action group that do not exist "
|
||||
"under plugins/modules/: %s" % (group, ", ".join(missing))
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("group", sorted(SHARED_ARG_SPECS))
|
||||
def test_action_group_matches_shared_arg_spec_users(action_groups, group):
|
||||
constant = SHARED_ARG_SPECS[group]["constant"]
|
||||
declared = set(action_groups[group])
|
||||
actual = {name for name in _module_names() if group in _shared_specs_used_by(name)}
|
||||
|
||||
missing_from_group = sorted(actual - declared)
|
||||
assert not missing_from_group, (
|
||||
"%s build their argument spec from %s but are not listed in the '%s' action "
|
||||
"group, so module_defaults set on that group silently does not reach them. "
|
||||
"Add them to meta/runtime.yml."
|
||||
% (", ".join(missing_from_group), constant, group)
|
||||
)
|
||||
|
||||
not_shared = sorted(declared - actual)
|
||||
assert not not_shared, (
|
||||
"%s are listed in the '%s' action group but do not build their argument spec "
|
||||
"from %s, so module_defaults set on that group will fail for them with "
|
||||
"'Unsupported parameters'. Remove them from meta/runtime.yml."
|
||||
% (", ".join(not_shared), group, constant)
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("module_name,reason", sorted(EXCLUDED_FROM_GROUPS.items()))
|
||||
def test_excluded_modules_stay_out_of_action_groups(action_groups, module_name, reason):
|
||||
assert module_name in _module_names(), (
|
||||
"%s is listed in EXCLUDED_FROM_GROUPS but no longer exists; drop the entry."
|
||||
% module_name
|
||||
)
|
||||
|
||||
for group, members in action_groups.items():
|
||||
assert module_name not in members, (
|
||||
"%s was added to the '%s' action group, but it %s. If it now accepts the "
|
||||
"group's shared authentication options, remove it from EXCLUDED_FROM_GROUPS "
|
||||
"in this test as well." % (module_name, group, reason)
|
||||
)
|
||||
|
||||
assert not _shared_specs_used_by(module_name), (
|
||||
"%s now builds its argument spec from a shared auth spec, so the reason it was "
|
||||
"excluded (%s) no longer holds. Add it to the matching action group and remove "
|
||||
"it from EXCLUDED_FROM_GROUPS." % (module_name, reason)
|
||||
)
|
||||
Reference in New Issue
Block a user