Compare commits

12 Commits
main ... 6.1.0

Author SHA1 Message Date
Alina Buzachis
fa3d94f793 Prep kubernetes.core 6.1.0 (#977)
SUMMARY


ISSUE TYPE


Bugfix Pull Request
Docs Pull Request
Feature Pull Request
New Module Pull Request

COMPONENT NAME

ADDITIONAL INFORMATION

Reviewed-by: Yuriy Novostavskiy
Reviewed-by: Bianca Henderson <beeankha@gmail.com>
Reviewed-by: GomathiselviS <gomathiselvi@gmail.com>
2025-08-12 18:25:31 +00:00
patchback[bot]
9ec27cf37c CI fix for 976 (#982) (#985)
This is a backport of PR #982 as merged into main (a861079).
SUMMARY
Exclude plugins/connection/kubectl.py from ansible-lint, as this file contains only examples that is simplificated and may not be accordingally to linter rules.
resolves #976
ISSUE TYPE

Bugfix Pull Request

COMPONENT NAME
CI
ADDITIONAL INFORMATION

Reviewed-by: Alina Buzachis
Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2025-08-12 15:59:34 +00:00
Bianca Henderson
10cb241256 Reapply "Remove kubeconfig value from module invocation log (#826)" (#899) (#966) (#979)
This reverts commit 1d962fb from stable-6 (i.e., reapplies the changes from #966); this is a temporary fix for #782 as it will re-introduce #870.

Reviewed-by: Alina Buzachis
Reviewed-by: GomathiselviS <gomathiselvi@gmail.com>
2025-08-11 16:48:04 +00:00
patchback[bot]
92e1f581fe fix(k8s,service): Hide fields first before creating diffs (#915) (#963)
This is a backport of PR #915 as merged into main (6a0635a).
SUMMARY

By hiding fields first before creating a diff hidden fields will not be shown in the resulting diffs and therefore will also not trigger the changed condition.
The issue can only be reproduced when a mutating webhook changes the object while the kubernetes.core.k8s module is working with it.

kubevirt/kubevirt.core#145
ISSUE TYPE


Bugfix Pull Request

COMPONENT NAME

kubernetes.core.module_utils.k8s.service
ADDITIONAL INFORMATION


Run kubernetes.core.k8s and create object with hidden fields. After run kubernetes.core.k8s again and let a webhook mutate the object that the module is working with. The module should return with changed: no.

Reviewed-by: Alina Buzachis
2025-08-04 18:03:21 +00:00
patchback[bot]
7f69aff0d6 k8s_json_patch: support the hidden_fields param (#964) (#972)
This is a backport of PR #964 as merged into main (c48778d).
SUMMARY
Add support for hidden_fields on k8s_json_patch

ISSUE TYPE

Feature Pull Request

COMPONENT NAME
k8s_json_patch
ADDITIONAL INFORMATION
Works exactly the same as k8s
Haven't pushed the doc yet, because of many changes. Will do it on a separate commit if the tests pass.
1st commit here, sorry if I forget some things.
Thanks!

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2025-08-01 18:24:39 +00:00
patchback[bot]
8c65ac066d Add support for take-ownership Helm flag (#957) (#969)
This is a backport of PR #957 as merged into main (cf3c3a9).
SUMMARY
Add support for take-ownership Helm flag added in Helm 3.17.0
ISSUE TYPE

Feature Pull Request

COMPONENT NAME

kubernetes.core.helm

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2025-07-28 15:48:39 +00:00
patchback[bot]
1d962fb932 Revert "Remove kubeconfig value from module invocation log (#826)" (#899) (#966)
This is a backport of PR #899 as merged into main (1705ced).
This reverts commit 6efabd3.
SUMMARY

Fixes #870
A better solution is necessary to address #782. The current code makes getting manifests practically unusable. We need to revert this commit until a better solution is found.

ISSUE TYPE


Bugfix Pull Request

COMPONENT NAME

kubeconfig

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2025-07-22 21:29:21 +00:00
patchback[bot]
27ce23aa72 Fix integration test with ansibe-core 2.20 (#951) (#960)
This is a backport of PR #951 as merged into main (f568c9d).
SUMMARY
Now that ansible-core 2.19.0rc1 has been released, ansible-core’s devel branch has been bumped from 2.19.0.dev0 to 2.20.0.dev0. This potentially requires collection CIs to be updated which rely on devel using tests/sanity/ignore-2.19.txt, for example. Also it’s now time to add stable-2.19 to CI if you relied on devel to cover 2.19 so far. Note that milestone has also been updated to 2.20.0dev0.
During testing, I noticed that the failed test tasks/test_helm_not_installed.yml due to the new error message with ansible 2.20, please find here and following comments.
ISSUE TYPE

Bugfix Pull Request

COMPONENT NAME
test/CI (tasks/test_helm_not_installed.yml)
ADDITIONAL INFORMATION
to be cherry-picked to the stable-6 and stable-5

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2025-07-15 15:34:33 +00:00
patchback[bot]
993652b581 Add more functionality coverage to k8s_rollback integration test (#950) (#956)
This is a backport of PR #950 as merged into main (94e4235).
SUMMARY

Resolves #344

This revision adds the following test coverage:

Label Selectors: Tests rollback using label selectors to target specific deployments.
No Rollout History: Tests the warning scenario when attempting to rollback a deployment with only one revision.
Unsupported Resource Types: Tests error handling when trying to rollback unsupported resources like Services.
Non-existent Resources: Tests behavior when attempting to rollback resources that don't exist.
Multiple Resource Rollback: Tests bulk rollback operations using label selectors on multiple deployments.
Return Value Validation: Comprehensive validation of the rollback_info structure and content.
Field Selectors: Tests rollback using field selectors to target specific resources.
Check Mode Validation: Additional validation of check mode behavior and return values.

COMPONENT NAME

tests/integration/targets/k8s_rollback/tasks/main.yml

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2025-07-14 14:36:29 +00:00
patchback[bot]
9bd9d22db3 Fix the integration test for helm_registry_auth with helm >= 3.18.0 and clarify idempotency. (#946) (#953)
This is a backport of PR #946 as merged into main (642eb93).
SUMMARY
Fix the integration test for helm_registry_auth with helm >= 3.18.0 and clarify idempotency.
Fixes #944
ISSUE TYPE

Bugfix Pull Request

COMPONENT NAME
helm_registry_auth
ADDITIONAL INFORMATION
Caused by the changes in helm starting from 3.18.0

Reviewed-by: Bikouo Aubin
Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2025-07-08 15:56:48 +00:00
patchback[bot]
0593426918 Add plain_http parameter to helm, helm_pull and helm_template (#934) (#949)
This is a backport of PR #934 as merged into main (775959c).
SUMMARY

This change introduces the plain_http parameter to modules that can interact with OCI registries. This in needed in cases where the OCI registry does not use SSL encryption, forcing Helm to send HTTP requests instead of HTTPS

ISSUE TYPE


Feature Pull Request

COMPONENT NAME

helm, helm_pull and helm_template
ADDITIONAL INFORMATION


This is the output when trying to use an OCI registry that is not configured to use SSL certs.

fatal: [localhost]: FAILED! => {"changed": false, "command": "/usr/local/bin/helm show chart 'oci://<http-registry>/charts/foo'", "msg": "Failure when executing Helm command. Exited 1.\nstdout: \nstderr: Error: Get \"https://<http-registry>/v2/charts/foo/tags/list\": http: server gave HTTP response to HTTPS client\n", "stderr": "Error: Get \"https://<http-registry>/v2/charts/foo/tags/list\": http: server gave HTTP response to HTTPS client\n", "stderr_lines": ["Error: Get \"https://<http-registry>/v2/charts/foo/tags/list\": http: server gave HTTP response to HTTPS client"], "stdout": "", "stdout_lines": []}

Reviewed-by: Bikouo Aubin
2025-06-12 10:53:42 +00:00
Bianca Henderson
8fa5b201a4 Prep release 6.0.0 (#933)
SUMMARY

Prep kubernetes.core 6.0.0
Prerequisite: Release of community.okd/redhat.openshift 4.0.2 needs to happen first

ISSUE TYPE


Feature Pull Request

COMPONENT NAME
Multiple

Reviewed-by: Bikouo Aubin
2025-06-03 16:56:33 +00:00
46 changed files with 1076 additions and 227 deletions

View File

@@ -3,6 +3,7 @@ profile: production
exclude_paths:
- .ansible/
- .github/
- tests/integration
- tests/unit
- tests/sanity

View File

@@ -3,3 +3,4 @@
plugins/connection/kubectl.py no-changed-when
# false positive result
plugins/connection/kubectl.py var-naming[no-reserved]
plugins/connection/kubectl.py jinja[invalid]

View File

@@ -20,4 +20,6 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: run-ansible-lint
uses: ansible/ansible-lint@v25.1.2
uses: ansible/ansible-lint@main
with:
gh_action_ref: "v25.5.0"

View File

@@ -26,3 +26,4 @@ ignore: |
.tox
.ansible
tests/output
plugins/connection/kubectl.py

View File

@@ -4,26 +4,59 @@ Kubernetes Collection Release Notes
.. contents:: Topics
v6.1.0
======
Release Summary
---------------
This release includes a fix for kubeconfig output, added ``plain_http`` and ``take_ownership`` parameters for helm modules, support for ``hidden_fields`` in ``k8s_json_patch``, documented lack of idempotency support in ``helm_registry_auth`` with ``helm ≥ 3.18.0``, and improved ``k8s_rollback`` test coverage.
Minor Changes
-------------
- Module helm_registry_auth do not support idempotency with `helm >= 3.18.0` (https://github.com/ansible-collections/kubernetes.core/pull/946)
- Module k8s_json_patch - Add support for `hidden_fields` (https://github.com/ansible-collections/kubernetes.core/pull/964).
- helm - Parameter plain_http added for working with insecure OCI registries (https://github.com/ansible-collections/kubernetes.core/pull/934).
- helm - Parameter take_ownership added (https://github.com/ansible-collections/kubernetes.core/pull/957).
- helm_pull - Parameter plain_http added for working with insecure OCI registries (https://github.com/ansible-collections/kubernetes.core/pull/934).
- helm_template - Parameter plain_http added for working with insecure OCI registries (https://github.com/ansible-collections/kubernetes.core/pull/934).
Bugfixes
--------
- module_utils/k8s/service - hide fields first before creating diffs (https://github.com/ansible-collections/kubernetes.core/pull/915).
v6.0.0
======
Breaking Changes / Porting Guide
--------------------------------
- Remove deprecated ``k8s`` invetory plugin (https://github.com/ansible-collections/kubernetes.core/pull/867).
- Remove support for ``ansible-core<2.16`` (https://github.com/ansible-collections/kubernetes.core/pull/867).
v5.3.0
======
Release Summary
---------------
This release includes minor changes, bug fixes and also bumps ``ansible-lint`` version to ``25.1.2``.
This release includes minor changes, bug fixes and also bumps ansible-lint version to ``25.1.2``.
Minor Changes
-------------
- kubernetes.core - Bump version of ``ansible-lint`` to ``25.1.2`` (https://github.com/ansible-collections/kubernetes.core/pull/919).
- Bump version of ansible-lint to 25.1.2 (https://github.com/ansible-collections/kubernetes.core/pull/919).
- action/k8s_info - update templating mechanism with changes from ``ansible-core 2.19`` (https://github.com/ansible-collections/kubernetes.core/pull/888).
- helm - add ``reset_then_reuse_values`` support to helm module (https://github.com/ansible-collections/kubernetes.core/issues/803).
- helm - add support for ``insecure_skip_tls_verify`` option to helm and ``helm_repository`` (https://github.com/ansible-collections/kubernetes.core/issues/694).
- helm - add reset_then_reuse_values support to helm module (https://github.com/ansible-collections/kubernetes.core/issues/803).
- helm - add support for ``insecure_skip_tls_verify`` option to helm and helm_repository(https://github.com/ansible-collections/kubernetes.core/issues/694).
Bugfixes
--------
- module_utils/k8s/service - Fix issue when trying to delete resource using ``delete_options`` and ``check_mode=true`` (https://github.com/ansible-collections/kubernetes.core/issues/892).
- module_utils/k8s/service - fix issue when trying to delete resource using `delete_options` and `check_mode=true` (https://github.com/ansible-collections/kubernetes.core/issues/892).
v5.2.0
======
@@ -124,7 +157,7 @@ Bugfixes
- integrations test helm_kubeconfig - set helm version to v3.10.3 to avoid incompatability with new bitnami charts (https://github.com/ansible-collections/kubernetes.core/pull/670).
v3.3.1
=======
======
Release Summary
---------------

View File

@@ -1,5 +1,5 @@
# Also needs to be updated in galaxy.yml
VERSION = 6.0.0-dev0
VERSION = 6.1.0
TEST_ARGS ?= ""
PYTHON_VERSION ?= `python -c 'import platform; print(".".join(platform.python_version_tuple()[0:2]))'`

View File

@@ -21,12 +21,10 @@ For more information about communication, see the [Ansible communication guide](
## Requirements
<!--start requires_ansible-->
### Ansible Version Compatibility
## Ansible version compatibility
This collection has been tested against following Ansible versions: **>=2.16.0**.
This collection has been tested against the following Ansible versions: **>=2.16.0**.
For collections that support Ansible 2.9, please ensure you update your `network_os` to use the
fully qualified collection name (for example, `cisco.ios.ios`).
Plugins and modules within a collection may be tested with only specific Ansible versions.
A collection may contain metadata that identifies these versions.
PEP440 is the schema used to describe the versions of Ansible.
@@ -47,17 +45,17 @@ This collection supports Kubernetes versions >= 1.24.
Click on the name of a plugin or module to view that content's documentation:
<!--start collection content-->
### Connection Plugins
### 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.
### K8s Filter Plugins
### K8s filter plugins
Name | Description
--- | ---
kubernetes.core.k8s_config_resource_name|Generate resource name for the given resource of type ConfigMap, Secret
### Lookup Plugins
### 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
@@ -101,7 +99,7 @@ You can also include it in a `requirements.yml` file and install it via `ansible
---
collections:
- name: kubernetes.core
version: 5.2.0
version: 6.1.0
```
### Installing the Kubernetes Python Library

View File

@@ -1044,3 +1044,40 @@ releases:
- 898-k8s-dont-delete-in-check-mode.yaml
- 919-update-ansible-lint-version.yaml
release_date: '2025-05-16'
6.0.0:
changes:
breaking_changes:
- Remove deprecated ``k8s`` invetory plugin (https://github.com/ansible-collections/kubernetes.core/pull/867).
- Remove support for ``ansible-core<2.16`` (https://github.com/ansible-collections/kubernetes.core/pull/867).
fragments:
- 20250121-breaking-changes-6.0.0.yml
release_date: '2025-05-19'
6.1.0:
changes:
bugfixes:
- module_utils/k8s/service - hide fields first before creating diffs (https://github.com/ansible-collections/kubernetes.core/pull/915).
minor_changes:
- Module helm_registry_auth do not support idempotency with `helm >= 3.18.0`
(https://github.com/ansible-collections/kubernetes.core/pull/946)
- Module k8s_json_patch - Add support for `hidden_fields` (https://github.com/ansible-collections/kubernetes.core/pull/964).
- helm - Parameter plain_http added for working with insecure OCI registries
(https://github.com/ansible-collections/kubernetes.core/pull/934).
- helm - Parameter take_ownership added (https://github.com/ansible-collections/kubernetes.core/pull/957).
- helm_pull - Parameter plain_http added for working with insecure OCI registries
(https://github.com/ansible-collections/kubernetes.core/pull/934).
- helm_template - Parameter plain_http added for working with insecure OCI registries
(https://github.com/ansible-collections/kubernetes.core/pull/934).
release_summary: "This release includes a fix for kubeconfig output, added ``plain_http``
and ``take_ownership`` parameters for helm modules, support for ``hidden_fields``
in ``k8s_json_patch``, documented lack of idempotency support in ``helm_registry_auth``
with ``helm \u2265 3.18.0``, and improved ``k8s_rollback`` test coverage."
fragments:
- 20250411-kubeconfig-no_log-revert.yaml
- 20250428-k8s-service-hide-fields-first.yaml
- 20250522-add-plain-http-for-oci-registries.yaml
- 20250605-fix-helm_registry_auth-integration_test.yaml
- 20250704-k8s-rollback-integration-test-coverage.yaml
- 20250720-k8s-patch-add-hidden-fields.yaml
- 20250911-add-support-helm-take-ownership.yaml
- release_summary.yml
release_date: '2025-08-12'

View File

@@ -1,4 +0,0 @@
---
breaking_changes:
- Remove support for ``ansible-core<2.16`` (https://github.com/ansible-collections/kubernetes.core/pull/867).
- Remove deprecated ``k8s`` invetory plugin (https://github.com/ansible-collections/kubernetes.core/pull/867).

View File

@@ -1,147 +0,0 @@
.. _ansible_turbo_mode:
******************
Ansible Turbo mode
******************
Following document provides overview of Ansible Turbo mode in ``kubernetes.core`` collection.
.. contents::
:local:
:depth: 1
Synopsis
--------
- A brief introduction about Ansible Turbo mode in ``kuberentes.core`` collection.
- Ansible Turbo mode is an optional performance optimization. It can be enabled by installing the cloud.common collection and setting the ``ENABLE_TURBO_MODE`` environment variable.
Requirements
------------
The following requirement is needed on the host that executes this module.
- The ``cloud.common`` collection (https://github.com/ansible-collections/cloud.common)
You will also need to set the environment variable ``ENABLE_TURBO_MODE=1`` on the managed host. This can be done in the same ways you would usually do so, for example::
---
- hosts: remote
environment:
ENABLE_TURBO_MODE: 1
tasks:
...
Installation
------------
You can install ``cloud.common`` collection using following command::
# ansible-galaxy collection install cloud.common
Current situation without Ansible Turbo mode
============================================
The traditional execution flow of an Ansible module includes the following steps:
- Upload of a ZIP archive with the module and its dependencies
- Execution of the module
- Ansible collects the results once the script is finished
These steps happen for each task of a playbook, and on every host.
Most of the time, the execution of a module is fast enough for
the user. However, sometime the module requires significant amount of time,
just to initialize itself. This is a common situation with the API based modules.
A classic initialization involves the following steps:
- Load a Python library to access the remote resource (via SDK)
- Open a client
- Load a bunch of Python modules.
- Request a new TCP connection.
- Create a session.
- Authenticate the client.
All these steps are time consuming and the same operations will be running again and again.
For instance, here:
- ``import openstack``: takes 0.569s
- ``client = openstack.connect()``: takes 0.065s
- ``client.authorize()``: takes 1.360s,
These numbers are from test running against VexxHost public cloud.
In this case, it's a 2s-ish overhead per task. If the playbook
comes with 10 tasks, the execution time cannot go below 20s.
How Ansible Turbo Module improve the situation
==============================================
``AnsibleTurboModule`` is actually a class that inherites from
the standard ``AnsibleModule`` class that your modules probably
already use.
The big difference is that when a module starts, it also spawns
a little Python daemon. If a daemon already exists, it will just
reuse it.
All the module logic is run inside this Python daemon. This means:
- Python modules are actually loaded one time
- Ansible module can reuse an existing authenticated session.
The background service
======================
The daemon kills itself after 15s, and communication are done
through an Unix socket.
It runs in one single process and uses ``asyncio`` internally.
Consequently you can use the ``async`` keyword in your Ansible module.
This will be handy if you interact with a lot of remote systems
at the same time.
Security impact
===============
``ansible_module.turbo`` open an Unix socket to interact with the background service.
We use this service to open the connection toward the different target systems.
This is similar to what SSH does with the sockets.
Keep in mind that:
- All the modules can access the same cache. Soon an isolation will be done at the collection level (https://github.com/ansible-collections/cloud.common/pull/17)
- A task can load a different version of a library and impact the next tasks.
- If the same user runs two ``ansible-playbook`` at the same time, they will have access to the same cache.
When a module stores a session in a cache, it's a good idea to use a hash of the authentication information to identify the session.
Error management
================
``ansible_module.turbo`` uses exceptions to communicate a result back to the module.
- ``EmbeddedModuleFailure`` is raised when ``json_fail()`` is called.
- ``EmbeddedModuleSuccess`` is raised in case of success and returns the result to the origin module process.
These exceptions are defined in ``ansible_collections.cloud.common.plugins.module_utils.turbo.exceptions``.
You can raise ``EmbeddedModuleFailure`` exception yourself, for instance from a module in ``module_utils``.
.. note:: Be careful with the ``except Exception:`` blocks.
Not only they are bad practice, but also may interface with this
mechanism.
Troubleshooting
===============
You may want to manually start the server. This can be done with the following command:
.. code-block:: shell
PYTHONPATH=$HOME/.ansible/collections python -m ansible_collections.cloud.common.plugins.module_utils.turbo.server --socket-path $HOME/.ansible/tmp/turbo_mode.kubernetes.core.socket
You can use the ``--help`` argument to get a list of the optional parameters.

View File

@@ -289,6 +289,29 @@ Parameters
<div>Provide a URL for accessing the API. Can also be specified via <code>K8S_AUTH_HOST</code> environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>insecure_skip_tls_verify</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 5.3.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&nbsp;&larr;</div></li>
<li>yes</li>
</ul>
</td>
<td>
<div>Skip tls certificate checks for the chart download.</div>
<div>Do not confuse with the <code>validate_certs</code> option.</div>
<div>This option is only available for helm &gt;= 3.16.0.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: skip_tls_certs_check</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -307,6 +330,27 @@ Parameters
<div style="font-size: small; color: darkgreen"><br/>aliases: kubeconfig_path</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>plain_http</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.1.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&nbsp;&larr;</div></li>
<li>yes</li>
</ul>
</td>
<td>
<div>Use HTTP instead of HTTPS when working with OCI registries</div>
<div>Requires Helm &gt;= 3.13.0</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -578,6 +622,27 @@ Parameters
<div>Skip custom resource definitions when installing or upgrading.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>take_ownership</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.1.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&nbsp;&larr;</div></li>
<li>yes</li>
</ul>
</td>
<td>
<div>When upgrading, Helm will ignore the check for helm annotations and take ownership of the existing resources</div>
<div>This feature requires helm &gt;= 3.17.0</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -787,6 +852,12 @@ Examples
chart_ref: "https://github.com/grafana/helm-charts/releases/download/grafana-5.6.0/grafana-5.6.0.tgz"
release_namespace: monitoring
- name: Deploy Bitnami's MongoDB latest chart from OCI registry
kubernetes.core.helm:
name: test
chart_ref: "oci://registry-1.docker.io/bitnamicharts/mongodb"
release_namespace: database
# Using complex Values
- name: Deploy new-relic client chart
kubernetes.core.helm:

View File

@@ -193,6 +193,27 @@ Parameters
<div>Pass credentials to all domains.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>plain_http</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.1.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&nbsp;&larr;</div></li>
<li>yes</li>
</ul>
</td>
<td>
<div>Use HTTP instead of HTTPS when working with OCI registries</div>
<div>Requires Helm &gt;= 3.13.0</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -279,7 +300,8 @@ Parameters
</td>
<td>
<div>Whether or not to check tls certificate for the chart download.</div>
<div>Requires helm &gt;= 3.3.0.</div>
<div>Requires helm &gt;= 3.3.0. Alias <code>insecure_skip_tls_verify</code> added in 5.3.0.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: insecure_skip_tls_verify</div>
</td>
</tr>
<tr>

View File

@@ -170,6 +170,7 @@ Parameters
<div>Desired state of the registry.</div>
<div>If set to V(present) attempt to log in to the remote registry server using the URL specified in O(host).</div>
<div>If set to V(absent) attempt to log out from the remote registry server using the URL specified in O(host).</div>
<div>As helm &gt;= 3.18.0 reports successful logout even if the user is not logged in, this module will report a change regardless of the current state.</div>
</td>
</tr>
<tr>

View File

@@ -143,6 +143,27 @@ Parameters
<div>Provide a URL for accessing the API. Can also be specified via <code>K8S_AUTH_HOST</code> environment variable.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>insecure_skip_tls_verify</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 5.3.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&nbsp;&larr;</div></li>
<li>yes</li>
</ul>
</td>
<td>
<div>Skip tls certificate checks for the repository url.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: skip_tls_certs_check</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>

View File

@@ -194,6 +194,27 @@ Parameters
<div>If the directory already exists, it will be overwritten.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>plain_http</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.1.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&nbsp;&larr;</div></li>
<li>yes</li>
</ul>
</td>
<td>
<div>Use HTTP instead of HTTPS when working with OCI registries</div>
<div>Requires Helm &gt;= 3.13.0</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>

View File

@@ -174,8 +174,7 @@ Parameters
</td>
<td>
<div>Hide fields matching any of the field definitions in the result</div>
<div>An example might be <code>hidden_fields=[metadata.managedFields]</code></div>
<div>Only field definitions that don&#x27;t reference list items are supported (so V(spec.containers[0]) would not work)</div>
<div>An example might be <code>hidden_fields=[metadata.managedFields]</code> or V(hidden_fields=[spec.containers[0].env[3].value]) or V(hidden_fields=[metadata.annotations[kubectl.kubernetes.io/last-applied-configuration]])</div>
</td>
</tr>
<tr>

View File

@@ -140,6 +140,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>hidden_fields</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
/ <span style="color: purple">elements=string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.1.0</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">[]</div>
</td>
<td>
<div>List of fields to hide from the diff output.</div>
<div>This is useful for fields that are not relevant to the patch operation, such as `metadata.managedFields`.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>

View File

@@ -395,8 +395,7 @@ Parameters
</td>
<td>
<div>Hide fields matching this option in the result</div>
<div>An example might be <code>hidden_fields=[metadata.managedFields]</code></div>
<div>Only field definitions that don&#x27;t reference list items are supported (so V(spec.containers[0]) would not work)</div>
<div>An example might be <code>hidden_fields=[metadata.managedFields]</code> or V(hidden_fields=[spec.containers[0].env[3].value]) or V(hidden_fields=[metadata.annotations[kubectl.kubernetes.io/last-applied-configuration]])</div>
</td>
</tr>
<tr>

View File

@@ -25,7 +25,7 @@ tags:
- openshift
- okd
- cluster
version: 6.0.0-dev0
version: 6.1.0
build_ignore:
- .DS_Store
- "*.tar.gz"

View File

@@ -22,8 +22,7 @@ plugin_routing:
redirect: community.okd.openshift
k8s:
tombstone:
# To be replaced with 6.0.0 in release 6.0.0 commit
removal_version: 6.0.0-dev0
removal_version: 6.0.0
warning_text: >-
The k8s inventory plugin was slated for deprecation in 3.3.0 and has been removed in release 6.0.0. Use kubernetes.core.k8s_info and ansible.builtin.add_host instead.
modules:

View File

@@ -498,8 +498,8 @@ def diff_objects(
if not diff:
return True, result
result["before"] = diff[0]
result["after"] = diff[1]
result["before"] = hide_fields(diff[0], hidden_fields)
result["after"] = hide_fields(diff[1], hidden_fields)
if list(result["after"].keys()) == ["metadata"] and list(
result["before"].keys()
@@ -512,9 +512,6 @@ def diff_objects(
).issubset(ignored_keys):
return True, result
result["before"] = hide_fields(result["before"], hidden_fields)
result["after"] = hide_fields(result["after"], hidden_fields)
return False, result

View File

@@ -237,6 +237,20 @@ options:
default: False
aliases: [ skip_tls_certs_check ]
version_added: 5.3.0
plain_http:
description:
- Use HTTP instead of HTTPS when working with OCI registries
- Requires Helm >= 3.13.0
type: bool
default: False
version_added: 6.1.0
take_ownership:
description:
- When upgrading, Helm will ignore the check for helm annotations and take ownership of the existing resources
- This feature requires helm >= 3.17.0
type: bool
default: False
version_added: 6.1.0
extends_documentation_fragment:
- kubernetes.core.helm_common_options
"""
@@ -319,6 +333,12 @@ EXAMPLES = r"""
chart_ref: "https://github.com/grafana/helm-charts/releases/download/grafana-5.6.0/grafana-5.6.0.tgz"
release_namespace: monitoring
- name: Deploy Bitnami's MongoDB latest chart from OCI registry
kubernetes.core.helm:
name: test
chart_ref: "oci://registry-1.docker.io/bitnamicharts/mongodb"
release_namespace: database
# Using complex Values
- name: Deploy new-relic client chart
kubernetes.core.helm:
@@ -495,7 +515,9 @@ def run_dep_update(module, chart_ref):
rc, out, err = module.run_helm_command(dep_update)
def fetch_chart_info(module, command, chart_ref, insecure_skip_tls_verify=False):
def fetch_chart_info(
module, command, chart_ref, insecure_skip_tls_verify=False, plain_http=False
):
"""
Get chart info
"""
@@ -504,6 +526,17 @@ def fetch_chart_info(module, command, chart_ref, insecure_skip_tls_verify=False)
if insecure_skip_tls_verify:
inspect_command += " --insecure-skip-tls-verify"
if plain_http:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.13.0"):
module.fail_json(
msg="plain_http requires helm >= 3.13.0, current version is {0}".format(
helm_version
)
)
else:
inspect_command += " --plain-http"
rc, out, err = module.run_helm_command(inspect_command)
return yaml.safe_load(out)
@@ -533,6 +566,8 @@ def deploy(
reset_values=True,
reset_then_reuse_values=False,
insecure_skip_tls_verify=False,
plain_http=False,
take_ownership=False,
):
"""
Install/upgrade/rollback release chart
@@ -546,6 +581,8 @@ def deploy(
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)
@@ -595,6 +632,9 @@ def deploy(
else:
deploy_command += " --insecure-skip-tls-verify"
if plain_http:
deploy_command += " --plain-http"
if values_files:
for value_file in values_files:
deploy_command += " --values=" + value_file
@@ -690,6 +730,7 @@ def helmdiff_check(
reset_values=True,
reset_then_reuse_values=False,
insecure_skip_tls_verify=False,
plain_http=False,
):
"""
Use helm diff to determine if a release would change by upgrading a chart.
@@ -745,6 +786,17 @@ def helmdiff_check(
if insecure_skip_tls_verify:
cmd += " --insecure-skip-tls-verify"
if plain_http:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.13.0"):
module.fail_json(
msg="plain_http requires helm >= 3.13.0, current version is {0}".format(
helm_version
)
)
else:
cmd += " --plain-http"
rc, out, err = module.run_helm_command(cmd)
return (len(out.strip()) > 0, out.strip())
@@ -808,6 +860,8 @@ def argument_spec():
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),
)
)
return arg_spec
@@ -862,6 +916,8 @@ def main():
reset_values = module.params.get("reset_values")
reset_then_reuse_values = module.params.get("reset_then_reuse_values")
insecure_skip_tls_verify = module.params.get("insecure_skip_tls_verify")
plain_http = module.params.get("plain_http")
take_ownership = module.params.get("take_ownership")
if update_repo_cache:
run_repo_update(module)
@@ -871,6 +927,24 @@ def main():
release_status = get_release_status(module, release_name, all_status=all_status)
helm_cmd = module.get_helm_binary()
if plain_http:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.13.0"):
module.fail_json(
msg="plain_http requires helm >= 3.13.0, current version is {0}".format(
helm_version
)
)
if take_ownership:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.17.0"):
module.fail_json(
msg="take_ownership requires helm >= 3.17.0, current version is {0}".format(
helm_version
)
)
opt_result = {}
if release_state == "absent" and release_status is not None:
# skip release statuses 'uninstalled' and 'uninstalling'
@@ -900,7 +974,7 @@ def main():
# Fetch chart info to have real version and real name for chart_ref from archive, folder or url
chart_info = fetch_chart_info(
module, helm_cmd, chart_ref, insecure_skip_tls_verify
module, helm_cmd, chart_ref, insecure_skip_tls_verify, plain_http
)
if dependency_update:
@@ -962,6 +1036,7 @@ def main():
reset_values=reset_values,
reset_then_reuse_values=reset_then_reuse_values,
insecure_skip_tls_verify=insecure_skip_tls_verify,
plain_http=plain_http,
)
changed = True
@@ -989,6 +1064,7 @@ def main():
reset_values=reset_values,
reset_then_reuse_values=reset_then_reuse_values,
insecure_skip_tls_verify=insecure_skip_tls_verify,
plain_http=plain_http,
)
if would_change and module._diff:
opt_result["diff"] = {"prepared": prepared}
@@ -1026,6 +1102,8 @@ def main():
reset_values=reset_values,
reset_then_reuse_values=reset_then_reuse_values,
insecure_skip_tls_verify=insecure_skip_tls_verify,
plain_http=plain_http,
take_ownership=take_ownership,
)
changed = True

View File

@@ -114,6 +114,13 @@ options:
- The path of a helm binary to use.
required: false
type: path
plain_http:
description:
- Use HTTP instead of HTTPS when working with OCI registries
- Requires Helm >= 3.13.0
type: bool
default: False
version_added: 6.1.0
"""
EXAMPLES = r"""
@@ -201,6 +208,7 @@ def main():
chart_ssl_cert_file=dict(type="path"),
chart_ssl_key_file=dict(type="path"),
binary_path=dict(type="path"),
plain_http=dict(type="bool", default=False),
)
module = AnsibleHelmModule(
argument_spec=argspec,
@@ -225,6 +233,7 @@ def main():
chart_ca_cert="3.1.0",
chart_ssl_cert_file="3.1.0",
chart_ssl_key_file="3.1.0",
plain_http="3.13.0",
)
def test_version_requirement(opt):
@@ -264,6 +273,7 @@ def main():
skip_tls_certs_check=dict(key="insecure-skip-tls-verify"),
chart_devel=dict(key="devel"),
untar_chart=dict(key="untar"),
plain_http=dict(key="plain-http"),
)
for k, v in helm_flag_args.items():

View File

@@ -31,6 +31,7 @@ options:
- Desired state of the registry.
- If set to V(present) attempt to log in to the remote registry server using the URL specified in O(host).
- If set to V(absent) attempt to log out from the remote registry server using the URL specified in O(host).
- As helm >= 3.18.0 reports successful logout even if the user is not logged in, this module will report a change regardless of the current state.
required: false
default: present
choices: ['present', 'absent']
@@ -129,6 +130,9 @@ failed:
from ansible_collections.kubernetes.core.plugins.module_utils.helm import (
AnsibleHelmModule,
)
from ansible_collections.kubernetes.core.plugins.module_utils.version import (
LooseVersion,
)
def arg_spec():
@@ -231,6 +235,13 @@ def main():
command=helm_cmd,
)
helm_version = module.get_helm_version()
if LooseVersion(helm_version) >= LooseVersion("3.18.0") and state == "absent":
# https://github.com/ansible-collections/kubernetes.core/issues/944
module.warn(
"The helm_registry_auth is not idempotent with helm >= 3.18.0, always report a change."
)
module.exit_json(changed=changed, stdout=out, stderr=err, command=helm_cmd)

View File

@@ -147,6 +147,13 @@ options:
- json
- file
version_added: 2.4.0
plain_http:
description:
- Use HTTP instead of HTTPS when working with OCI registries
- Requires Helm >= 3.13.0
type: bool
default: False
version_added: 6.1.0
"""
EXAMPLES = r"""
@@ -218,6 +225,9 @@ from ansible.module_utils.basic import missing_required_lib
from ansible_collections.kubernetes.core.plugins.module_utils.helm import (
AnsibleHelmModule,
)
from ansible_collections.kubernetes.core.plugins.module_utils.version import (
LooseVersion,
)
def template(
@@ -236,6 +246,7 @@ def template(
values_files=None,
include_crds=False,
set_values=None,
plain_http=False,
):
cmd += " template "
@@ -262,6 +273,9 @@ def template(
if insecure_registry:
cmd += " --insecure-skip-tls-verify"
if plain_http:
cmd += " --plain-http"
if show_only:
for template in show_only:
cmd += " -s " + template
@@ -307,6 +321,7 @@ def main():
values_files=dict(type="list", default=[], elements="str"),
update_repo_cache=dict(type="bool", default=False),
set_values=dict(type="list", elements="dict"),
plain_http=dict(type="bool", default=False),
),
supports_check_mode=True,
)
@@ -327,12 +342,22 @@ def main():
values_files = module.params.get("values_files")
update_repo_cache = module.params.get("update_repo_cache")
set_values = module.params.get("set_values")
plain_http = module.params.get("plain_http")
if not IMP_YAML:
module.fail_json(msg=missing_required_lib("yaml"), exception=IMP_YAML_ERR)
helm_cmd = module.get_helm_binary()
if plain_http:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.13.0"):
module.fail_json(
msg="plain_http requires helm >= 3.13.0, current version is {0}".format(
helm_version
)
)
if update_repo_cache:
update_cmd = helm_cmd + " repo update"
module.run_helm_command(update_cmd)
@@ -357,6 +382,7 @@ def main():
values_files=values_files,
include_crds=include_crds,
set_values=set_values_args,
plain_http=plain_http,
)
if not check_mode:

View File

@@ -33,6 +33,14 @@ options:
aliases:
- api
- version
hidden_fields:
description:
- List of fields to hide from the diff output.
- This is useful for fields that are not relevant to the patch operation, such as `metadata.managedFields`.
type: list
elements: str
default: []
version_added: 6.1.0
kind:
description:
- Use to specify an object model.
@@ -147,6 +155,7 @@ from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions imp
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.service import (
diff_objects,
hide_fields,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.waiter import (
get_waiter,
@@ -174,6 +183,7 @@ JSON_PATCH_ARGS = {
"namespace": {"type": "str"},
"name": {"type": "str", "required": True},
"patch": {"type": "list", "required": True, "elements": "dict"},
"hidden_fields": {"type": "list", "elements": "str", "default": []},
}
@@ -203,6 +213,7 @@ def execute_module(module, client):
namespace = module.params.get("namespace")
patch = module.params.get("patch")
hidden_fields = module.params.get("hidden_fields")
wait = module.params.get("wait")
wait_sleep = module.params.get("wait_sleep")
wait_timeout = module.params.get("wait_timeout")
@@ -260,13 +271,13 @@ def execute_module(module, client):
module.fail_json(msg=msg, error=to_native(exc), status="", reason="")
success = True
result = {"result": obj}
result = {"result": hide_fields(obj, hidden_fields)}
if wait and not module.check_mode:
waiter = get_waiter(client, resource, condition=wait_condition)
success, result["result"], result["duration"] = waiter.wait(
wait_timeout, wait_sleep, name, namespace
)
match, diffs = diff_objects(existing.to_dict(), obj)
match, diffs = diff_objects(existing.to_dict(), obj, hidden_fields)
result["changed"] = not match
if module._diff:
result["diff"] = diffs

View File

@@ -29,3 +29,4 @@ test_namespace:
- "helm-chart-with-space-into-name"
- "helm-reset-then-reuse-values"
- "helm-insecure"
- "helm-test-take-ownership"

View File

@@ -6,3 +6,4 @@
with_items:
- "v3.15.4"
- "v3.16.0"
- "v3.17.0"

View File

@@ -47,6 +47,9 @@
- name: Test insecure registry flag feature
include_tasks: test_helm_insecure.yml
- name: Test take ownership flag feature
include_tasks: test_helm_take_ownership.yml
- name: Clean helm install
file:
path: "{{ item }}"

View File

@@ -13,3 +13,11 @@
that:
- helm_missing_binary is failed
- "'No such file or directory' in helm_missing_binary.msg"
when: ansible_version.full is version('2.20', '<')
- name: Assert that helm is not installed (ansible 2.20+)
assert:
that:
- helm_missing_binary is failed
- "'Error executing command' in helm_missing_binary.msg"
when: ansible_version.full is version('2.20', '>=')

View File

@@ -0,0 +1,81 @@
---
- name: Test helm take ownership
vars:
helm_namespace: "{{ test_namespace[13] }}"
block:
- name: Initial chart installation (no flag set)
helm:
binary_path: "{{ helm_binary }}"
chart_ref: "{{ chart_test_oci }}"
release_name: test-take-ownership
release_namespace: "{{ helm_namespace }}"
create_namespace: true
register: install
- name: Validate that take-ownership flag is not set
assert:
that:
- install is changed
- '"--take-ownership" not in install.command'
- name: Upgrade chart (take-onwership flag set)
helm:
binary_path: "{{ helm_binary }}"
chart_ref: "{{ chart_test_oci }}"
release_name: test-take-ownership
release_namespace: "{{ helm_namespace }}"
take_ownership: true
values:
commonLabels:
take-onwership: "set"
register: upgrade
ignore_errors: true
- name: Validate that take-ownership flag IS set if helm version is >= 3.17.0
assert:
that:
- upgrade is changed
- '"--take-ownership" in upgrade.command'
when: '"v3.17.0" <= helm_version'
- name: Validate that feature fails for helm < 3.17.0
assert:
that:
- upgrade is failed
- '"take_ownership requires helm >= 3.17.0" in upgrade.msg'
when: 'helm_version < "v3.17.0"'
- name: Upgrade chart (take-onwership flag not set)
helm:
binary_path: "{{ helm_binary }}"
chart_ref: "{{ chart_test_oci }}"
release_name: test-take-ownership
release_namespace: "{{ helm_namespace }}"
values:
commonLabels:
take-onwership: "not-set"
register: upgrade
ignore_errors: true
- name: Validate that take-ownership flag IS set if helm version is >= 3.17.0
assert:
that:
- upgrade is changed
- '"--take-ownership" not in upgrade.command'
when: '"v3.17.0" <= helm_version'
- name: Validate that feature fails for helm < 3.17.0
assert:
that:
- upgrade is changed
- upgrade.msg is not defined
when: 'helm_version < "v3.17.0"'
always:
- name: Remove helm namespace
k8s:
api_version: v1
kind: Namespace
name: "{{ helm_namespace }}"
state: absent

View File

@@ -0,0 +1,3 @@
helm_template
helm_pull
helm

View File

@@ -0,0 +1,3 @@
[all]
helm-3.12.3 helm_version=v3.12.3 test_namespace=helm-plain-http-v3-12-3 tests_should_failed=true
helm-3.18.2 helm_version=v3.18.2 test_namespace=helm-plain-http-v3-18-2 tests_should_failed=false

View File

@@ -0,0 +1,14 @@
- name: Run test for helm plain http option
hosts: all
gather_facts: true
vars:
ansible_connection: local
ansible_python_interpreter: "{{ ansible_playbook_python }}"
chart_test_oci: "oci://registry-1.docker.io/bitnamicharts/redis"
roles:
- setup_namespace
tasks:
- ansible.builtin.include_tasks: tasks/test.yaml

View File

@@ -0,0 +1,99 @@
---
- name: Run test for helm
block:
- name: Create temporary directory to install chart In
ansible.builtin.tempfile:
state: directory
suffix: .helm
register: install_path
- name: Install required helm version
ansible.builtin.include_role:
name: install_helm
vars:
helm_install_path: "{{ install_path.path }}"
- name: Set helm binary path
ansible.builtin.set_fact:
helm_binary: "{{ install_path.path }}/{{ ansible_system | lower }}-amd64/helm"
# helm
- name: Run helm with plain_http
kubernetes.core.helm:
binary_path: "{{ helm_binary }}"
chart_ref: "{{ chart_test_oci }}"
release_name: test-secure
release_namespace: "{{ test_namespace }}"
create_namespace: true
plain_http: true
register: install_chart
ignore_errors: true
- name: Ensure module failed as expected
ansible.builtin.assert:
that:
- install_chart is failed
- '"plain_http requires helm >= 3.13.0" in install_chart.msg'
when: tests_should_failed | bool
- name: Ensure the result command contains the expected option
ansible.builtin.assert:
that:
- install_chart is not failed
- '"--plain-http" in install_chart.command'
when: not (tests_should_failed | bool)
# helm_pull
- name: Trying to download helm chart with option plain_http
kubernetes.core.helm_pull:
chart_ref: "{{ chart_test_oci }}"
destination: "{{ playbook_dir }}"
binary_path: "{{ helm_binary }}"
plain_http: true
register: pull_chart
ignore_errors: true
- name: Ensure module failed as expected
ansible.builtin.assert:
that:
- pull_chart is failed
- '"plain_http requires helm >= 3.13.0" in pull_chart.msg'
when: tests_should_failed | bool
- name: Ensure the result command contains the expected option
ansible.builtin.assert:
that:
- pull_chart is not failed
- '"--plain-http" in pull_chart.command'
when: not (tests_should_failed | bool)
# helm_template
- name: Test helm render template
kubernetes.core.helm_template:
binary_path: "{{ helm_binary }}"
chart_ref: "{{ chart_test_oci }}"
output_dir: "{{ playbook_dir }}"
plain_http: true
register: template
ignore_errors: true
- name: Ensure module failed as expected
ansible.builtin.assert:
that:
- template is failed
- '"plain_http requires helm >= 3.13.0" in template.msg'
when: tests_should_failed | bool
- name: Ensure the result command contains the expected option
ansible.builtin.assert:
that:
- template is not failed
- '"--plain-http" in template.command'
when: not (tests_should_failed | bool)
always:
- name: Delete temporary file
ansible.builtin.file:
path: "{{ install_path.path }}"
state: absent
ignore_errors: true

View File

@@ -0,0 +1,4 @@
#!/usr/bin/env bash
set -eux
export ANSIBLE_ROLES_PATH=../
ansible-playbook playbooks/play.yaml -i inventory.ini "$@"

View File

@@ -108,15 +108,19 @@
assert:
that: "'Removing login credentials' in _helm_registry_auth_logout.stderr"
- name: Test logout idempotency
helm_registry_auth:
host: localhost:{{ registry_port }}
state: absent
register: _helm_registry_auth_logout_idempotency
- name: Test idempotency of logout with helm < 3.18.0
when: _helm_version.stdout is ansible.builtin.version('v3.18.0', '<')
block:
- name: Assert logout operation did not report change
ansible.builtin.assert:
that: _helm_registry_auth_logout_idempotency is not changed
- name: Test logout idempotency
helm_registry_auth:
host: localhost:{{ registry_port }}
state: absent
register: _helm_registry_auth_logout_idempotency
- name: Assert logout operation did not report change
ansible.builtin.assert:
that: _helm_registry_auth_logout_idempotency is not changed
- name: Ensure that not able to push to the registry
ansible.builtin.shell: >-
@@ -133,8 +137,7 @@
# Helm binary prints the message to stderr
ansible.builtin.assert:
that:
- "'push access denied' in _save_chart.stderr"
- "'authorization failed' in _save_chart.stderr"
- "'push access denied' in _save_chart.stderr or 'basic credential not found' in _save_chart.stderr"
- "_save_chart.rc != 0"
- "'localhost:{{ registry_port }}' not in _config_json.content | b64decode"
@@ -155,7 +158,8 @@
- name: Assert that the registry is not logged in and auth data is not saved
ansible.builtin.assert:
that:
- "'401 Unauthorized' in _helm_registry_auth_wrong.stderr"
- "'401' in _helm_registry_auth_wrong.stderr"
- "'unauthorized' in _helm_registry_auth_wrong.stderr | lower"
- "'{{ wrong_password }}' not in _helm_registry_auth_correct.command"
- "'{{ wrong_password }}' not in _helm_registry_auth_correct.stdout"
- "'{{ wrong_password }}' not in _helm_registry_auth_correct.stderr"

View File

@@ -58,7 +58,7 @@
- "'managedFields' not in hf4.resources[0]['metadata']"
- name: Hiding a changed field should still result in a change
- name: Hiding a changed field should not result in a change
k8s:
definition: "{{ hide_fields_base_configmap | combine({'data':{'hello':'different'}}) }}"
hidden_fields:
@@ -67,10 +67,10 @@
register: hf5
diff: true
- name: Ensure that hidden changed field changed
- name: Ensure that hidden changed field not changed
assert:
that:
- hf5.changed
- not hf5.changed
- name: Apply works with hidden fields
k8s:

View File

@@ -0,0 +1,3 @@
k8s_json_patch
k8s
time=33

View File

@@ -0,0 +1,2 @@
---
test_namespace: "k8s-hide-fields"

View File

@@ -0,0 +1,2 @@
dependencies:
- setup_namespace

View File

@@ -0,0 +1,6 @@
---
- connection: local
gather_facts: false
hosts: localhost
roles:
- k8s_json_patch_hide_fields

View File

@@ -0,0 +1,5 @@
#!/usr/bin/env bash
set -eux
export ANSIBLE_CALLBACKS_ENABLED=profile_tasks
export ANSIBLE_ROLES_PATH=../
ansible-playbook playbook.yaml "$@"

View File

@@ -0,0 +1,91 @@
- vars:
pod: json-patch
k8s_wait_timeout: 400
block:
- name: Create a simple pod
kubernetes.core.k8s:
definition:
apiVersion: v1
kind: Pod
metadata:
namespace: "{{ test_namespace }}"
name: "{{ pod }}"
labels:
label1: foo
spec:
containers:
- image: busybox:musl
name: busybox
command:
- sh
- -c
- while true; do echo $(date); sleep 10; done
wait: yes
wait_timeout: "{{ k8s_wait_timeout | default(omit) }}"
- name: Add a label, and hide some fields
kubernetes.core.k8s_json_patch:
kind: Pod
namespace: "{{ test_namespace }}"
name: "{{ pod }}"
patch:
- op: add
path: /metadata/labels/label2
value: bar
hidden_fields:
- metadata.managedFields
register: hf1
- name: Ensure hidden fields are not present
assert:
that:
- "'managedFields' not in hf1.result['metadata']"
- name: Add a label, without hiding our fields
kubernetes.core.k8s_json_patch:
kind: Pod
namespace: "{{ test_namespace }}"
name: "{{ pod }}"
patch:
- op: add
path: /metadata/labels/label3
value: bar
hidden_fields:
- something.else
register: hf2
- name: Ensure hidden fields are present
assert:
that:
- "'managedFields' in hf2.result['metadata']"
- name: Patching the same resource with missing hidden fields should have no effect
kubernetes.core.k8s_json_patch:
kind: Pod
namespace: "{{ test_namespace }}"
name: "{{ pod }}"
patch:
- op: add
path: /metadata/labels/label2
value: bar
hidden_fields:
- does.not.exist
register: hf2
- name: Ensure no change with missing hidden fields
assert:
that:
- not hf2.changed
always:
- name: Remove namespace
k8s:
kind: Namespace
name: "{{ test_namespace }}"
state: absent
ignore_errors: true

View File

@@ -33,7 +33,6 @@
ports:
- containerPort: 80
- name: Crash the existing deployment
k8s:
state: present
@@ -228,7 +227,7 @@
hostPath:
path: /var/lib/docker/containers
register: crash
ignore_errors: true
ignore_errors: yes
- name: Assert that the Daemonset failed
assert:
@@ -291,6 +290,297 @@
that:
- failed_version | int + 1 == result.resources[0].metadata.annotations['deprecated.daemonset.template.generation'] | int
- name: Create deployment with specific labels for selector testing
k8s:
state: present
wait: yes
wait_timeout: "{{ k8s_wait_timeout }}"
definition:
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-labeled
namespace: "{{ namespace }}"
labels:
app: nginx
test-group: label-selector-test
spec:
replicas: 2
selector:
matchLabels:
app: nginx-labeled
template:
metadata:
labels:
app: nginx-labeled
spec:
containers:
- name: nginx
image: nginx:1.17
ports:
- containerPort: 80
- name: Update deployment to create second revision
k8s:
state: present
wait: yes
wait_timeout: 30
definition:
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-labeled
namespace: "{{ namespace }}"
labels:
app: nginx
test-group: label-selector-test
spec:
replicas: 2
selector:
matchLabels:
app: nginx-labeled
template:
metadata:
labels:
app: nginx-labeled
spec:
containers:
- name: nginx
image: nginx:1.18
ports:
- containerPort: 80
- name: Test rollback with label selectors
k8s_rollback:
api_version: apps/v1
kind: Deployment
name: nginx-labeled
namespace: "{{ namespace }}"
label_selectors:
- "test-group=label-selector-test"
register: result
- name: Assert label selector rollback worked
assert:
that:
- result is changed
- result.rollback_info | length == 1
- result.rollback_info[0].method == "patch"
- name: Create deployment with single revision
k8s:
state: present
wait: yes
wait_timeout: 30
definition:
apiVersion: apps/v1
kind: Deployment
metadata:
name: single-revision
namespace: "{{ namespace }}"
spec:
replicas: 1
selector:
matchLabels:
app: single-revision
template:
metadata:
labels:
app: single-revision
spec:
containers:
- name: nginx
image: nginx:1.17
ports:
- containerPort: 80
- name: Try to rollback deployment with no previous revisions
k8s_rollback:
api_version: apps/v1
kind: Deployment
name: single-revision
namespace: "{{ namespace }}"
register: result
- name: Assert warning is returned for no rollout history
assert:
that:
- not result.changed
- result.rollback_info[0].warnings is defined
- "'No rollout history found' in result.rollback_info[0].warnings[0]"
- name: Create a service for unsupported resource test
k8s:
state: present
definition:
apiVersion: v1
kind: Service
metadata:
name: test-service
namespace: "{{ namespace }}"
spec:
selector:
app: nginx
ports:
- port: 80
targetPort: 80
- name: Test rollback on unsupported resource type
k8s_rollback:
api_version: v1
kind: Service
name: test-service
namespace: "{{ namespace }}"
register: result
ignore_errors: yes
- name: Assert error message for unsupported resource
assert:
that:
- not result.changed
- "'Cannot perform rollback on resource of kind Service' in result.msg"
- name: Test rollback on non-existent deployment
k8s_rollback:
api_version: apps/v1
kind: Deployment
name: non-existent
namespace: "{{ namespace }}"
register: result
- name: Assert no resources found
assert:
that:
- not result.changed
- result.rollback_info | length == 0
- name: Create multiple deployments with same label
k8s:
state: present
wait: yes
wait_timeout: 30
definition:
apiVersion: apps/v1
kind: Deployment
metadata:
name: "multi-{{ item }}"
namespace: "{{ namespace }}"
labels:
group: multi-test
app: multi
spec:
replicas: 1
selector:
matchLabels:
app: "multi-{{ item }}"
template:
metadata:
labels:
app: "multi-{{ item }}"
spec:
containers:
- name: nginx
image: nginx:1.17
ports:
- containerPort: 80
loop: [1, 2, 3]
- name: Update multiple deployments to create second revisions
k8s:
state: present
wait: yes
wait_timeout: 30
definition:
apiVersion: apps/v1
kind: Deployment
metadata:
name: "multi-{{ item }}"
namespace: "{{ namespace }}"
labels:
group: multi-test
app: multi
spec:
replicas: 1
selector:
matchLabels:
app: "multi-{{ item }}"
template:
metadata:
labels:
app: "multi-{{ item }}"
spec:
containers:
- name: nginx
image: nginx:1.18
ports:
- containerPort: 80
loop: [1, 2, 3]
- name: Rollback multiple deployments using label selector
k8s_rollback:
api_version: apps/v1
kind: Deployment
name: "multi-{{ item }}"
namespace: "{{ namespace }}"
label_selectors:
- "group=multi-test"
register: result
loop: [1, 2, 3]
- name: Assert multiple resources were rolled back
assert:
that:
- result.results | length == 3
- result.results | selectattr('changed', 'equalto', true) | list | length == 3
- result.results | selectattr('rollback_info', 'defined') | list | length == 3
- result.results | map(attribute='rollback_info') | map('first') | map(attribute='method') | select('equalto', 'patch') | list | length == 3
- name: Validate rollback_info structure for deployment
assert:
that:
- result.results is defined
- result.results[0].rollback_info is defined
- result.results[0].rollback_info | length > 0
- result.results[0].rollback_info[0].method == "patch"
- result.results[0].rollback_info[0].body is defined
- result.results[0].rollback_info[0].resources is defined
- result.results[0].rollback_info[0].resources.metadata is defined
- result.results[0].rollback_info[0].resources.spec is defined
- name: Test rollback with field selectors
k8s_rollback:
api_version: apps/v1
kind: Deployment
name: multi-1
namespace: "{{ namespace }}"
field_selectors:
- "metadata.name=multi-1"
register: result
- name: Assert field selector rollback worked
assert:
that:
- result is changed
- result.rollback_info | length == 1
- result.rollback_info[0].resources.metadata.name == "multi-1"
- name: Test check mode return values
k8s_rollback:
api_version: apps/v1
kind: Deployment
name: multi-2
namespace: "{{ namespace }}"
register: result
check_mode: yes
- name: Validate check mode returns expected structure
assert:
that:
- result is changed
- result.rollback_info is defined
- result.rollback_info[0].method == "patch"
- result.rollback_info[0].body is defined
always:
- name: Delete {{ namespace }} namespace
k8s:

View File

@@ -2,50 +2,57 @@ from __future__ import absolute_import, division, print_function
__metaclass__ = type
import json
import re
import kubernetes
import pytest
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.core import (
AnsibleK8SModule,
)
from mock import MagicMock, patch
MINIMAL_K8S_VERSION = "24.2.0"
UNSUPPORTED_K8S_VERSION = "11.0.0"
@pytest.mark.parametrize("stdin", [{}], indirect=["stdin"])
def test_no_warn(monkeypatch, stdin, capfd):
class FakeAnsibleModule:
def __init__(self, **kwargs):
pass
def exit_json(self):
raise SystemExit(0)
@patch.object(AnsibleK8SModule, "warn")
def test_no_warn(m_ansible_k8s_module_warn, monkeypatch, capfd):
monkeypatch.setattr(kubernetes, "__version__", MINIMAL_K8S_VERSION)
module = AnsibleK8SModule(argument_spec={})
m_ansible_k8s_module_warn.side_effect = print
module = AnsibleK8SModule(argument_spec={}, module_class=FakeAnsibleModule)
with pytest.raises(SystemExit):
module.exit_json()
out, err = capfd.readouterr()
return_value = json.loads(out)
assert return_value.get("exception") is None
assert return_value.get("warnings") is None
assert return_value.get("failed") is None
m_ansible_k8s_module_warn.assert_not_called()
@pytest.mark.parametrize("stdin", [{}], indirect=["stdin"])
def test_warn_on_k8s_version(monkeypatch, stdin, capfd):
@patch.object(AnsibleK8SModule, "warn")
def test_warn_on_k8s_version(m_ansible_k8s_module_warn, monkeypatch, capfd):
monkeypatch.setattr(kubernetes, "__version__", UNSUPPORTED_K8S_VERSION)
module = AnsibleK8SModule(argument_spec={})
m_ansible_k8s_module_warn.side_effect = print
module = AnsibleK8SModule(argument_spec={}, module_class=FakeAnsibleModule)
with pytest.raises(SystemExit):
module.exit_json()
m_ansible_k8s_module_warn.assert_called_once()
out, err = capfd.readouterr()
return_value = json.loads(out)
assert return_value.get("warnings") is not None
warnings = return_value["warnings"]
assert len(warnings) == 1
assert "kubernetes" in str(warnings[0])
assert MINIMAL_K8S_VERSION in str(warnings[0])
assert (
re.search(
r"kubernetes<([0-9]+\.[0-9]+\.[0-9]+) is not supported or tested. Some features may not work.",
out,
)
is not None
)
dependencies = [
@@ -58,9 +65,17 @@ dependencies = [
@pytest.mark.parametrize(
"stdin,desired,actual,result", [({}, *d) for d in dependencies], indirect=["stdin"]
)
def test_has_at_least(monkeypatch, stdin, desired, actual, result, capfd):
@patch.object(AnsibleK8SModule, "warn")
def test_has_at_least(
m_ansible_k8s_module_warn, monkeypatch, stdin, desired, actual, result, capfd
):
monkeypatch.setattr(kubernetes, "__version__", actual)
def fake_warn(x):
print(x)
raise SystemExit(1)
m_ansible_k8s_module_warn.side_effect = fake_warn
module = AnsibleK8SModule(argument_spec={})
assert module.has_at_least("kubernetes", desired) is result
@@ -80,11 +95,18 @@ def test_requires_fails_with_message(
monkeypatch, stdin, dependency, version, msg, capfd
):
monkeypatch.setattr(kubernetes, "__version__", "24.2.0")
module = AnsibleK8SModule(argument_spec={})
module = AnsibleK8SModule(argument_spec={}, module_class=FakeAnsibleModule)
def fake_fail_json(**kwargs):
print(f"Printing message => {kwargs}")
print(kwargs.get("msg"))
raise SystemExit(1)
module.fail_json = MagicMock()
module.fail_json.side_effect = fake_fail_json
with pytest.raises(SystemExit):
module.requires(dependency, version)
module.fail_json.assert_called_once()
out, err = capfd.readouterr()
return_value = json.loads(out)
assert return_value.get("failed")
assert msg in return_value.get("msg")
assert msg in out