Compare commits

..
97 Commits
Author SHA1 Message Date
Bianca HendersonandGitHub 1a0914352a Prep 5.4.4 release (#1193)
* Fix ansible version for 5.4.3 release

* Prep release 5.4.4

(cherry picked from commit 44fbb83be4b2ea9d3ee4479f7aa131cf72b3b0e3)
2026-07-09 17:04:18 -04:00
Bianca HendersonandGitHub efe2d1aa69 Prep release 5.4.3 (#1187)
* Prep k8s collection release 5.4.3

* Update release date for 5.4.3

* Update changelog.yaml and changelog.rst mismatches
2026-07-08 11:04:38 -04:00
0cd0f3df9e Add meta/execution-environment.yml to fix EE builds on UBI images (#1142) (#1182)
ansible-builder builds fail with "No package matches 'openshift-clients'"
on UBI images because the openshift-clients RPM in bindep.txt requires
repos not available in standard UBI. This adds collection-level EE
metadata pointing to a minimal bindep file without openshift-clients,
while preserving the original bindep.txt for direct bindep usage.

Fixes #1141


(cherry picked from commit a80e2d067c)

Co-authored-by: Christopher Brown <snecklifter@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-07-07 09:48:42 -04:00
d0daf56ea7 Add lint ignore entry (#1184) (#1185)
(cherry picked from commit 75a5560aec)

Co-authored-by: Bianca Henderson <bianca@redhat.com>
2026-07-07 09:42:59 -04:00
3967f5e2ca feat(ci): add security check to block .claude/ and .vscode/ directories (#1173) (#1180)
* feat(ci): add security check to block .claude/ and .vscode/ directories

Add workflow that calls the security_check_directories action from
cloud-content-ci-automation to fail PRs containing files under .claude/
or .vscode/ directories.

Integrates with all_green_check.yaml as a required job for PRs.

Ref: ACA-6411



* fix(ci): suppress SonarCloud S7637 for reusable actions using @main

Internal reusable actions from ansible-network/github_actions and
ansible-collections/cloud-content-ci-automation use @main refs for
simpler maintenance. Suppress the 'use full commit SHA' rule for
workflow files.



* fix(ci): use correct org and pin action to commit SHA

Address review feedback:
- Change org from ansible-collections to ansible
- Pin to commit SHA 74b5fe87 instead of @main



* docs: add changelog fragment for security check workflow



* Update changelogs/fragments/1173-security-check-workflow.yml

---------



(cherry picked from commit 6bb9cce51b)

Co-authored-by: GomathiselviS <gomathiselvi@gmail.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: Bianca Henderson <beeankha@gmail.com>
2026-07-03 08:39:56 -04:00
7150d04f01 Point to Python 3.13 for ansible-core devel (#1174) (#1175)
(cherry picked from commit ceeafa8c6d)

Co-authored-by: Bianca Henderson <bianca@redhat.com>
2026-07-01 12:19:02 -04:00
Bianca HendersonandGitHub 00f3d12a1d [manual backport stable-5] Fix CI Test Collision (#1162) (#1166)
* Fix CI Test Collision (#1162)

* Fix CI concurrency issue

* More CI fixes

* Fix coverage job install

* Install correct test dependencies

(cherry picked from commit d211f316ad)

* Restore cancel-in-progress: true
2026-06-30 12:01:44 -04:00
33bb3b81ba ci: suppress SonarCloud python:S5443 for test code (#1165) (#1168)
Unit tests pass hardcoded '/tmp/...' strings as fake module arguments (for
example chart_ref) into fully mocked helm commands, so no file is ever
created and there is no real exposure. SonarCloud's python:S5443 still
raises a security hotspot on each literal and, because it only scores new
code, drops a PR's security rating even though the same pattern already
pervades the existing test suite.

Scope the suppression to tests/** only. Production code creates temporary
files via tempfile.mkstemp / NamedTemporaryFile and remains covered by the
rule, where it carries real value.

AI-assisted commit with Claude Opus

(cherry picked from commit 0836e96c2d)

Co-authored-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
2026-06-30 11:48:42 -04:00
e4b748a791 CI - configure precommit hook to block commit when files from .claude… (#1149) (#1170)
* CI - configure precommit hook to block commit when files from .claude/ and/or .vscode/ directories are staged

* fix sanity issue - shebang

* Remove local hook and update documentation

(cherry picked from commit a4fc40732a)

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>
2026-06-30 10:57:50 +02:00
c76cc63a75 Fix workflow concurrency issue (#1159) (#1160)
(cherry picked from commit bb80dde66d)

Co-authored-by: Bianca Henderson <bianca@redhat.com>
2026-06-26 12:03:21 -04:00
c9b918a453 Fix all-green CI workflow (#1153) (#1157)
(cherry picked from commit 8bf31513f5)

Co-authored-by: Bianca Henderson <bianca@redhat.com>
2026-06-26 10:53:45 -04:00
d3e408556b ci: suppress SonarCloud python:S7498 for argument_spec dict() convention (#1152) (#1154)
Ansible module argument_spec is conventionally defined with the dict(...)
constructor rather than {...} literals, for readability and consistency
across the collection. SonarCloud's python:S7498 ("Literal syntax should
be preferred...") flags this as a false positive and re-fires on every
new module argument. Ignore the rule project-wide via sonar-project.properties.

Fixes #1151

(cherry picked from commit 1c20b53bdc)

Co-authored-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
2026-06-25 14:07:10 -04:00
Bianca HendersonandGitHub 16f4b49c43 Manual backport of SonarQube configuration to stable-5 branch (#1137) 2026-05-29 17:31:39 -04:00
178611ef5d Fix unit test failures in CI (#1133) (#1134)
(cherry picked from commit f69761f37c)

Co-authored-by: Bianca Henderson <bianca@redhat.com>
2026-05-25 11:00:48 -04:00
2b52790a01 Update pod deletion conditions for local storage used in a daemon set pod (#1095) (#1127)
* Update pod deletion conditions for local storage used in a daemon set pod

Refactor pod deletion logic to handle local storage in daemon set pods correctly.

* Add bugfix for k8s_drain handling local storage pods

Fix logic for handling pods with local storage in k8s_drain.

* Refactor filter_pods function for clarity and efficiency

* Fix sanity and linter errors

---------


(cherry picked from commit b58b2ca70e)

Co-authored-by: Juan Morete <morete@gmail.com>
Co-authored-by: Bianca Henderson <bianca@redhat.com>
2026-05-15 15:16:07 -04:00
84cf83fe0f fix(helm_repository): strip trailing slashes from repo_url (#1121) (#1125)
Helm normalizes repository URLs internally, so a URL supplied with a
trailing slash and the same URL without one are treated as different
entries. This causes the module to fail every run when the user
provides a trailing slash, even though the repository is already
correctly registered.

Strip the trailing slash from repo_url before comparing against the
existing repository list so repeated runs with the same input are
idempotent.

Fixes #480

(cherry picked from commit 8a58d3b6de)

Co-authored-by: Yuriy Novostavskiy <yuriy@novostavskiy.kiev.ua>
2026-05-14 10:56:35 -04:00
a2aa079829 docs: add until example to k8s_info (#885) (#1118)
I would liked to have an example like this when I was using the
documentation.

(cherry picked from commit 4d7dc2a7d1)

Co-authored-by: Birger Johan Nordølum <33870508+MindTooth@users.noreply.github.com>
2026-05-06 10:16:35 -04:00
ca050aa3f6 Update URL reference in integration-test CI file (#1112) (#1113)
(cherry picked from commit 210467b26d)

Co-authored-by: Bianca Henderson <bianca@redhat.com>
2026-04-22 14:15:08 -04:00
84249fc4f1 ci: conditionally test turbo mode and cloud.common (#1109) (#1110)
The cloud.common collection is incompatible with ansible-core >= 2.19.0.
With the current testing matrix using Python 3.12 and the ansible
milestone (currently 2.22), this incompatibility causes integration
tests to fail.

Instead of completely removing turbo mode from the testing matrix, this
commit adds ansible-core 2.18 to the matrix and excludes the combination
of the ansible milestone and turbo mode. The checkout and installation
of the cloud.common collection are now conditionally executed only when
turbo mode is enabled.

(cherry picked from commit 11f619b69e)

Co-authored-by: Yuriy Novostavskiy <yuriy@novostavskiy.kiev.ua>
2026-04-21 14:51:49 -04:00
229575fe8f Add sanity test ignores for ansible-core 2.22 (#1102) (#1105)
The `devel` and `milestone` branches for ansible-core have been bumped to
`2.22.0.dev0` as the `stable-2.21` branch was created. Testing against `devel`
and `milestone` now uses 2.22, which requires creation of the
`tests/sanity/ignore-2.22.txt` file in all maintained collection branches.

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# On branch ignore-2.22
# Changes to be committed:
#	new file:   tests/sanity/ignore-2.22.txt
#

(cherry picked from commit 58f8f2e6e9)

Co-authored-by: Yuriy Novostavskiy <yuriy@novostavskiy.kiev.ua>
2026-04-20 18:34:47 -04:00
Bianca HendersonandGitHub 386f601ae0 Prep 5.4.2 release (#1083)
SUMMARY

Prep kubernetes.core 5.4.2 release

COMPONENT NAME

Multiple

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
Reviewed-by: Bikouo Aubin
Reviewed-by: Alina Buzachis
Reviewed-by: Mike Graves <mgraves@redhat.com>
2026-02-03 16:14:10 +00:00
Bianca HendersonandGitHub 3f2841be95 Remove references to non-existent test files from helm integration test target (#1085)
SUMMARY

While preparing the 5.4.2 release, an integration test failure indicated that there are references to non-existent test files in the helm integration test target in the stable-5 branch. This is because the changes from #955 were merged into main and stable-6 but not into stable-5 (which is correct, since it's a minor change) but there are references to those helm test targets in #1039, which got backported to both branches as a bugfix.

Reviewed-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
Reviewed-by: Mike Graves <mgraves@redhat.com>
2026-01-30 19:29:16 +00:00
patchback[bot]andGitHub 91f6827e23 Add idempotency to helm_pull module (#1055) (#1081)
This is a backport of PR #1055 as merged into main (34beacf).
SUMMARY
This PR implements idempotency for the helm_pull module, addressing issue #889.

New force parameter with defaults to False.
implemented chart_exists() function
checks chart existence before downloading, returns changed=False when chart exists

ISSUE TYPE

Bugfix Pull Request

COMPONENT NAME
helm_pull
ADDITIONAL INFORMATION
Force parameter added for backward compatibility and edge cases.
Implemented with the partial support of GitHub Copilot with Claude Sonnet 4.5 model

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2026-01-29 18:34:38 +00:00
patchback[bot]andGitHub 4136d6f606 Fix incorrect assertion in helm_pull integration test (#1077) (#1078)
This is a backport of PR #1077 as merged into main (23b6cec).
SUMMARY

The error message emitted for incorrect helm version has changed since the merge of #1039. This PR updates the related assertion in the helm_pull integration test

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2026-01-29 17:45:43 +00:00
Bianca HendersonandGitHub 12847a1555 Replace passing `warnings to exit_json with AnsibleModule.warn` for the few modules (#1033) (#1074)
This is a backport of PR #1033 as merged into main (3e32c12).
SUMMARY
Using exit_json or fail_json for warnings is deprecated in ansible-core>=2.19.0 and will be removed in ansible-core>=2.23.0
Tested with ansible-core 2.19.3 as the latest released version at the time of the start of this PR and with 2.16.0 as the lowest version supported by kubernetes.core 6.x
Resolves: #1031
ISSUE TYPE

Bugfix Pull Request

COMPONENT NAME
k8s_drain
k8s_rollback
k8s_scale
ADDITIONAL INFORMATION
The initial version of this PR covers only the module k8s_drain, with the following commits extended to k8s_rollback
k8s_scale

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
Reviewed-by: Mike Graves <mgraves@redhat.com>
2026-01-26 22:43:02 +00:00
GomathiselviS 8ddb19aade Fix cherry-pick spillover
rh-pre-commit.version: 2.3.2
rh-pre-commit.check-secrets: ENABLED
2026-01-26 11:22:13 -08:00
Yuriy NovostavskiyandGomathiselviS 0f6b4c873a Limit compatibility to Helm =>v3.0.0,<4.0.0 (#1039)
SUMMARY
Helm v4 is a major version with backward-incompatible changes, including to the flags and output of the Helm CLI and to the SDK. This version is currently not supported in the kubernetes.core. This PR is related to #1038 and is a short-term solution to mark compatibility explicitly
ISSUE TYPE

Bugfix Pull Request
Docs Pull Request

COMPONENT NAME

helm
helm_template
helm_info
helm_repository
helm_pull
helm_registry_auth
helm_plugin
helm_plugin_info

ADDITIONAL INFORMATION
Added `validate_helm_version()`` method to AnsibleHelmModule that enforces version constraint >=3.0.0,<4.0.0.
Fails fast with clear error message: "Helm version must be >=3.0.0,<4.0.0, current version is {version}"
Some modules (i.e. helm_registry_auth) technically is compatible with Helm v4, but validation was added to all helm modules.
Partially coauthored by GitHub Copilot with Claude Sonnet 4 model.
Addresses issue #1038

Reviewed-by: GomathiselviS <gomathiselvi@gmail.com>
Reviewed-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
Reviewed-by: Mike Graves <mgraves@redhat.com>
Reviewed-by: Alina Buzachis
Reviewed-by: Bianca Henderson <beeankha@gmail.com>
(cherry picked from commit 13791ec7bf)

rh-pre-commit.version: 2.3.2
rh-pre-commit.check-secrets: ENABLED
2026-01-26 11:03:26 -08:00
patchback[bot]andGitHub acc168e61f Fix K8S_AUTH_VERIFY_SSL environment value handling in kubectl connection plugin (#1049) (#1068)
This is a backport of PR #1049 as merged into main (12abc9b).
SUMMARY
Fixed a bug where setting K8S_AUTH_VERIFY_SSL=true (or any string value) caused the value to be treated as a separate kubectl command argument instead of being properly converted to a boolean.
The option key name is validate_certs, which does NOT end with "verify_ssl", so the original condition key.endswith("verify_ssl") at line 327 failed. This caused the code to fall through to the else block which added the value as separate
arguments: ["--insecure-skip-tls-verify", "true"], making "true" appear as a kubectl command.
Fixes #1021
ISSUE TYPE

Bugfix Pull Request

COMPONENT NAME
kubernetes.core.kubectl
ADDITIONAL INFORMATION
Changes Made

Changed condition from key.endswith("verify_ssl") to key == "validate_certs"
Added import of boolean function from ansible.module_utils.parsing.convert_bool
Added proper boolean conversion using boolean(self.get_option(key), strict=False)

Partially used LLM (GitHub Copilot with Claude Sonnet 4).
Before Fix
K8S_AUTH_VERIFY_SSL=true
Command: ['/usr/bin/kubectl', '--insecure-skip-tls-verify', 'true', 'exec', ...]

                                                            ^^^^^ treated as kubectl command (BUG!)

After Fix
K8S_AUTH_VERIFY_SSL=true
Command: ['/usr/bin/kubectl', '--insecure-skip-tls-verify=false', 'exec', ...]
                                                           ^^^^^ properly converted (FIXED!)

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2026-01-23 20:24:33 +00:00
patchback[bot]andGitHub 49f54edad2 chore(CI): prevent patchback bot from labeling new PRs (#1062) (#1066)
This is a backport of PR #1062 as merged into main (987c029).
SUMMARY
Currently, the patchback bot creates PRs with cherry-picks of PRs that are labeled with stable-* label, and this PR (as any new PR) gets labeled as needs_triage. This is unnecessary as it intentional PR created by the CI job.
This pull request introduces a small update to ensure that the workflow only runs if the pull request is not created by the patchback[bot] user to avoid unnecessary labels.
ISSUE TYPE

Bugfix Pull Request

COMPONENT NAME
.github/workflows/label-new-prs.yaml
ADDITIONAL INFORMATION
No changelog is required 

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2026-01-22 20:51:52 +00:00
patchback[bot]andGitHub c6519926a6 chore(doc): update typos (#1059) (#1067)
This is a backport of PR #1059 as merged into main (6c00f7c).
SUMMARY
This trivial documentation-only pull request correcting a few errors in README.md.

Documentation corrections:

Fixed a broken Markdown link for the GitHub repository in the support request section.
Corrected the reference from LICENCE to LICENSE to match the actual file name.



ISSUE TYPE

Docs Pull Request

COMPONENT NAME
README.md
ADDITIONAL INFORMATION
Trivial documentation-only change, no changelog is required.

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2026-01-22 20:51:27 +00:00
patchback[bot]andGitHub 0ff5c952b8 address sanity issues (#1056) (#1065)
This is a backport of PR #1056 as merged into main (bd1cacc).
SUMMARY


helm/helm_info - Deprecate some parameters and add new ones to resolve sanity issues.
k8s - the return block doc is not aligned with what the module returns


ISSUE TYPE


Bugfix Pull Request

COMPONENT NAME

helm, helm_info, k8s
Fixes: #1046

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2026-01-22 13:25:20 +00:00
patchback[bot]andGitHub 477a9b0b9e Add new workflow to label prs with needs_triage (#1045) (#1047)
This is a backport of PR #1045 as merged into main (9cfa903).
SUMMARY
This pr adds a new workflow for labeling new and reopened prs that are not marked as draft. The needs_triage label will be removed if the pr is marked as draft during development and re-added once the pr is marked as ready for review.
After consulting with the team, we decided to label prs in a new workflow to allow for the prs and issues to have different labels in the future.
ACA-2362
ISSUE TYPE

Feature Pull Request

COMPONENT NAME
github workflow
Reported CI Issues
Sanity tests: #1046

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2025-12-18 14:27:25 +00:00
patchback[bot]andGitHub eac3c0a88b Add 2.21 ignore file for sanity tests (#1032) (#1035)
This is a backport of PR #1032 as merged into main (1c16a2d).
SUMMARY

Resolves #1027

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2025-10-23 20:08:41 +00:00
patchback[bot]andGitHub e00d4fc9d7 Extend k8s action group (#992) (#1025)
This is a backport of PR #992 as merged into main (798f549).
SUMMARY


Add all k8s_* modules to the action group in order to esaily set kubeconfig parameter
ISSUE TYPE


Bugfix Pull Request

COMPONENT NAME

meta
ADDITIONAL INFORMATION

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2025-10-14 20:46:30 +00:00
patchback[bot]andGitHub 623b8b2716 Selectively redact sensitive kubeconfig data from logs (#1014) (#1023)
This is a backport of PR #1014 as merged into main (4fa3648).
SUMMARY

Resolves #782

ISSUE TYPE


Bugfix Pull Request

ADDITIONAL INFORMATION


The proper redaction of kubeconfig data can be seen by running this example playbook with verbosity of -vvv against the code in this PR.
Prior to these changes, all info was redacted (as shown in the example below):
ok: [local] => {
    "changed": false,
    "invocation": {
        "module_args": {
            "api_key": null,
            "binary_path": null,
            "ca_cert": null,
            "context": null,
            "get_all_values": false,
            "host": null,
            "kubeconfig": {
                "apiVersion": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
                "clusters": [
                    {
                        "cluster": {
                            "insecure-skip-tls-verify": true,
                            "server": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER"
                        },
                        "name": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER"
                    },
                    {
                        "cluster": {
                            "certificate-authority-data": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
                            "server": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER"
                        },
                        "name": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER"
                    },
                    {
                        "cluster": {
                            "certificate-authority": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
                            "extensions": [
                                {
                                    "extension": {
                                        "last-update": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
                                        "provider": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
                                        "version": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER"
                                    },
                                    "name": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER"
                                }
                            ],
                            "server": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER"
                        },
                        "name": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER"
                    }
                ],
                "contexts": [
                    {
                        "context": {
                            "cluster": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
                            "user": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER"
                        },
                        "name": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER"
                    },
                    {
                        "context": {
                            "cluster": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
                            "user": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER"
                        },
                        "name": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER"
                    },
[output shortened]

With the changes in this PR, only sensitive data is redacted:
ok: [local] => {
    "changed": false,
    "invocation": {
        "module_args": {
            "api_key": null,
            "binary_path": null,
            "ca_cert": null,
            "context": null,
            "get_all_values": false,
            "host": null,
            "kubeconfig": {
                "apiVersion": "v1",
                "clusters": [
                    {
                        "cluster": {
                            "insecure-skip-tls-verify": true,
                            "server": "<server address>"
                        },
                        "name": "exercise"
                    },
                    {
                        "cluster": {
                            "certificate-authority-data": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
                            "server": "<server address>"
                        },
                        "name": "kind-drain-test"
                    },
                    {
                        "cluster": {
                            "certificate-authority": "<path to .crt>",
                            "extensions": [
                                {
                                    "extension": {
                                        "last-update": "Tue, 07 Oct 2025 11:25:54 EDT",
                                        "provider": "minikube.sigs.k8s.io",
                                        "version": "v1.35.0"
                                    },
                                    "name": "cluster_info"
                                }
                            ],
                            "server": "<server address>"
                        },
                        "name": "minikube"
                    }
                ],
                "contexts": [
                    {
                        "context": {
                            "cluster": "exercise-pod",
                            "user": "bianca"
                        },
                        "name": "exercise"
                    },
                    {
                        "context": {
                            "cluster": "kind-drain-test",
                            "user": "kind-drain-test"
                        },
                        "name": "kind-drain-test"
                    },
[output shortened]

Reviewed-by: GomathiselviS <gomathiselvi@gmail.com>
2025-10-14 19:16:18 +00:00
patchback[bot]andGitHub 906c50f2c6 775 document proxy configurations (#1018) (#1019)
This is a backport of PR #1018 as merged into main (ae624cf).
SUMMARY
Added documentation for no_proxy, proxy, and proxy_headers parameters that were missing from the k8s lookup plugin. These parameters are already implemented in the codebase but were not documented.
no_proxy: Comma separated list of hosts that shouldn't use proxy
proxy: HTTP proxy URL for connections
proxy_headers: Dictionary of proxy headers with suboptions for proxy_basic_auth, basic_auth, and user_agent
Fixes #775
ISSUE TYPE

Docs Pull Request

COMPONENT NAME
k8s lookup
Additional comment
This is a reissue of #993, which was lost during the latest release due to me PR incorrectly from my fork's main branch. Linter errors on the previous PR should already be resolved.
This had the backport-5, backport-6 and skip-changelog labels.

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2025-10-10 17:30:27 +00:00
Mandar KulkarniandGitHub b16bb15d34 prepare release 5.4.1 (#1009)
SUMMARY


ISSUE TYPE


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

COMPONENT NAME

ADDITIONAL INFORMATION

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
Reviewed-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
2025-10-07 13:07:26 +00:00
patchback[bot]andGitHub 588f60adc8 update doc following #971 (#1006) (#1007)
This is a backport of PR #1006 as merged into main (200d64f).
SUMMARY
In the PR #971, support for copying files to initContainers, and this change includes a minor update for DOCUMENTATION for the k8s_cp module; however, docs/kubernetes.core.k8s_cp_module.rst wasn't updated, and it's a trivial change following the Updating documentation section of the CONTRIBUTING.md
ISSUE TYPE

Docs Pull Request

COMPONENT NAME
docs/kubernetes.core.k8s_cp_module.rst
ADDITIONAL INFORMATION
As it is a trivial change and related to #971, I didn't created a chnagelog fragment and suggest adding skip-changelog label.
To be backported to stable-5 and stable-6

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2025-10-02 20:21:19 +00:00
patchback[bot]andGitHub deac7719c2 Add the PR head as reference to the checkout action of the splitter job. (#981) (#1004)
This is a backport of PR #981 as merged into main (ec35c74).
SUMMARY
During the workflow checks of one of my previous pull requests, I ran into an error as result of a new integration test that was added in the main branch but which was not present in my pull request (https://github.com/ansible-collections/kubernetes.core/actions/runs/16787189478/job/47540604109). I'd find out that the reference for the repository checkout for the splitter job was not set and therefor it referenced to the main branch.
With this change, the head of the pull request is used as reference for the repository checkout action, in the splitter job. This way it will not fail when someone creates a PR that doesn't have newly added integration tests that were added to the main branch in the meantime. It also adds that newly added integration tests will be tested during the PR workflow checks already.
ISSUE TYPE

Bugfix Pull Request

COMPONENT NAME
bugfix in the workflow
ADDITIONAL INFORMATION
n/a

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2025-10-02 19:10:01 +00:00
patchback[bot]andGitHub cb4b792038 Added support for copying files to init Containers. (#971) (#1002)
This is a backport of PR #971 as merged into main (027700c).
SUMMARY
Was going trough the list with issues and found 958; which seemed a quick fix.
What I fixed with with this PR:

Added support for copying files to init containers.
Fixed the format message when an exec is failing for a pod (the order was wrong).
Added a check if the container that you try to run copy for is started.

ISSUE TYPE

Bugfix Pull Request

COMPONENT NAME
copy.py module
ADDITIONAL INFORMATION
Some testing.
Verify that the pod does not exist:
kubectl -n default get pod/yorick
Output:
Error from server (NotFound): pods "yorick" not found

Run the playbook to create the file, create the deployment, wait for the init container to be ready, copy the created file to the init container, cat the copied file (using kubernetes.core.k8s_exec) that is now in the init container and try to copy the created file to the (not started) container (which fails - to see the new error message for it):
cat << EOF | ansible-playbook /dev/stdin
- hosts: localhost
  gather_facts: False
  tasks:

  - ansible.builtin.copy:
      content: |
        Hi there
      dest: /tmp/yorick.txt

  - name: Deploy pod with initContainer with an unlimited while loop
    kubernetes.core.k8s:
      kubeconfig: "~/.kube/config"
      definition:
        apiVersion: v1
        kind: Pod
        metadata:
          name: "yorick"
          namespace: "default"
        spec:
          initContainers:
            - name: "yorick-init"
              image: busybox:latest
              command: ["/bin/sh"]
              args:
                - "-c"
                - |
                  echo "Init container started, waiting for file..."
                  # Wait for the file to be copied
                  while :;do
                    echo "Waiting for file"
                    sleep 5
                  done
                  echo "File received! Init container completing..."
          containers:
            - name: "yorick-container"
              image: busybox:latest
              command: ["/bin/sh"]
              args:
                - "-c"
                - |
                  # Keep container running for testing
                  sleep 300

  - kubernetes.core.k8s_info:
      kubeconfig: "~/.kube/config"
      api_version: v1
      kind: Pod
      name: "yorick"
      namespace: "default"
    register: pod_status
    until: >-
      pod_status.resources|length > 0
      and 'initContainerStatuses' in pod_status.resources.0.status
      and pod_status.resources.0.status.initContainerStatuses|length > 0
      and pod_status.resources.0.status.initContainerStatuses.0.started|bool

  - name: Copy /tmp/yorick.txt to the yorick-init init container
    kubernetes.core.k8s_cp:
      kubeconfig: "~/.kube/config"
      namespace: default
      pod: yorick
      remote_path: /tmp/yorick.txt
      local_path: /tmp/yorick.txt
      container: yorick-init

  - name: Execute a command
    kubernetes.core.k8s_exec:
      kubeconfig: "~/.kube/config"
      namespace: default
      pod: yorick
      container: yorick-init
      command: cat /tmp/yorick.txt
    register: exec_out

  - ansible.builtin.debug:
      var: exec_out.stdout

  - name: Try to copy /tmp/yorick.txt to the yorick-container container
    kubernetes.core.k8s_cp:
      kubeconfig: "~/.kube/config"
      namespace: default
      pod: yorick
      remote_path: /tmp/yorick.txt
      local_path: /tmp/yorick.txt
      container: yorick-container
EOF
Output:
PLAY [localhost] ********************************************************************************************************************************************************************

TASK [ansible.builtin.copy] *********************************************************************************************************************************************************
Thursday 31 July 2025  02:01:21 +0200 (0:00:00.016)       0:00:00.016 *********
ok: [localhost]

TASK [Deploy pod with initContainer with an unlimited while loop] *******************************************************************************************************************
Thursday 31 July 2025  02:01:21 +0200 (0:00:00.788)       0:00:00.804 *********
changed: [localhost]

TASK [kubernetes.core.k8s_info] *****************************************************************************************************************************************************
Thursday 31 July 2025  02:01:25 +0200 (0:00:03.963)       0:00:04.768 *********
FAILED - RETRYING: [localhost]: kubernetes.core.k8s_info (3 retries left).
ok: [localhost]

TASK [Copy /tmp/yorick.txt to the yorick-init init container] ***********************************************************************************************************************
Thursday 31 July 2025  02:01:32 +0200 (0:00:06.598)       0:00:11.366 *********
changed: [localhost]

TASK [Execute a command] ************************************************************************************************************************************************************
Thursday 31 July 2025  02:01:39 +0200 (0:00:07.017)       0:00:18.383 *********
changed: [localhost]

TASK [ansible.builtin.debug] ********************************************************************************************************************************************************
Thursday 31 July 2025  02:01:40 +0200 (0:00:00.644)       0:00:19.028 *********
ok: [localhost] => {
    "exec_out.stdout": "Hi there\n"
}

TASK [Try to copy /tmp/yorick.txt to the yorick-container container] ****************************************************************************************************************
Thursday 31 July 2025  02:01:40 +0200 (0:00:00.021)       0:00:19.050 *********
fatal: [localhost]: FAILED! => {
    "changed": false
}

MSG:

Pod container yorick-container is not started

PLAY RECAP **************************************************************************************************************************************************************************
localhost                  : ok=6    changed=3    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0

Playbook run took 0 days, 0 hours, 0 minutes, 21 seconds

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2025-09-25 15:10:52 +00:00
patchback[bot]andGitHub 6215ac763b fix(k8s,service): Hide fields first before creating diffs (#915) (#962)
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: Bianca Henderson <beeankha@gmail.com>
2025-09-24 20:36:59 +00:00
Bianca HendersonandGitHub d5599f1964 Minor updates to changelog to match stable-6 and main (#991)
This will make all stable-5 changelog content match main and stable-6 so there will no longer be formatting issues when doing release work in the future (basically a manual backport of #989).

Reviewed-by: Alina Buzachis
2025-09-22 19:58:15 +00:00
patchback[bot]andGitHub 90134ec3e0 [CI Fix] Remove ansible.module_utils.six imports (#998) (#999)
This is a backport of PR #998 as merged into main (448d3fe).
SUMMARY
This PR is essentially attempting Option B from issue #996 (Option A is implemented here); this code update accounts for the recent merge of sanity: warn on ansible.module_utils.six imports #85651.

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
Reviewed-by: Mandar Kulkarni <mandar242@gmail.com>
2025-09-22 16:54:06 +00:00
Bianca HendersonandGitHub dcbe52e722 Prep kubernetes.core 5.4.0 release (#970)
SUMMARY

Prep kubernetes.core 5.4.0 release

COMPONENT NAME
Multiple

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
Reviewed-by: Alina Buzachis
Reviewed-by: GomathiselviS <gomathiselvi@gmail.com>
2025-08-12 16:56:58 +00:00
patchback[bot]andGitHub 1e711d4da8 CI fix for 976 (#982) (#984)
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:41:03 +00:00
Bianca HendersonandGitHub 4b2dc4f974 Reapply "Remove kubeconfig value from module invocation log (#826)" (#899) (#965) (#980)
This reverts commit eb0aeeb from stable-5 (i.e., reapplies the changes from #965); 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:07 +00:00
patchback[bot]andGitHub eb0aeeb318 Revert "Remove kubeconfig value from module invocation log (#826)" (#899) (#965)
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:28:48 +00:00
patchback[bot]andGitHub f3d3696093 Fix the integration test for helm_registry_auth with helm >= 3.18.0 and clarify idempotency. (#946) (#961)
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: Bianca Henderson <beeankha@gmail.com>
2025-07-15 16:01:23 +00:00
patchback[bot]andGitHub e3da2f28fd Fix integration test with ansibe-core 2.20 (#951) (#959)
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:36 +00:00
Yuriy NovostavskiyandGitHub bb599542e8 add sanity/ignore for 2.20 and remove 2.16 and 2.14 (#954)
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  requires collection CI to be updated with using tests/sanity/ignore-2.20.txt. In the same time, ignore-2.14.txt ignore-2.15.txt is not required anymore as they are excluded from the matrix.
This PR is precific to stable-5 (and probably to be cherry-picked to stable-3) and is not required to main and stable-6 and such changes is already here.
ISSUE TYPE

CI Pull Request

COMPONENT NAME
CI
ADDITIONAL INFORMATION
It's required to have passed CI for #952

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
Reviewed-by: Alina Buzachis
2025-07-15 13:53:17 +00:00
patchback[bot]andGitHub 6560fb1c53 Fix unit tests (#939) (#940)
This is a backport of PR #939 as merged into main (34fd40d).
Some unit tests are broken with ansible-core 2.19, this PR aims to fix them.

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2025-07-11 02:23:06 +00:00
patchback[bot]andGitHub 20084d119e Push changes from 3.3.1 into main branch (#893) (#894)
This is a backport of PR #893 as merged into main (0e7229c).
Release 3.3.1 is out; push changes to main branch

Reviewed-by: Bikouo Aubin
Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2025-05-16 18:31:00 +00:00
Bikouo AubinandGitHub c47343d7b6 Prepare release 5.3.0 (#929)
Release 5.3.0

Update galaxy.yml and README.md
Update release files using antsibull-changelog

Reviewed-by: Alina Buzachis
Reviewed-by: Bianca Henderson <beeankha@gmail.com>
Reviewed-by: Yuriy Novostavskiy
2025-05-16 08:16:23 +00:00
Bianca HendersonandGitHub c213b51741 Add info to the README about stable-4 branch no longer being maintained (#931)
SUMMARY

Resolves ACA-2383 and #918.
Adjusting the changes made in #926 per #930.

ISSUE TYPE


Docs Pull Request

COMPONENT NAME

README.md
ADDITIONAL INFORMATION
Also made some minor capitalization edits.

Reviewed-by: Bikouo Aubin
2025-05-15 15:11:28 +00:00
patchback[bot]andGitHub 60b53b9dc9 Add helm insecure skip tls verify (#901) (#925)
This is a backport of PR #901 as merged into main (914a16e).
SUMMARY
Added the option insecure_skip_tls_verify  to the following helm modules:

helm_repository
helm
Unified the option with alias in helm_pull

For helm, added the option to the helm diff call, as it got fixed upstream.
Upstream Issue: databus23/helm-diff#503
Fixed with: helm/helm#12856
Fixes #694
ISSUE TYPE

Bugfix Pull Request

COMPONENT NAME

kubernetes.core.helm
kubernetes.core.helm_repository
kubernetes.core.helm_pull

ADDITIONAL INFORMATION
Basically the option was added in the parameters set in the ansible job, in the docs and then injected in the helm and helm diff binary calls if set. Defaults to False.
Example
---
- name: Test helm modules
  tasks:
    - name: Test helm repository insecure
      kubernetes.core.helm_repository:
        name: insecure
        repo_url: "<helm-repo-with-self-signed-tls>"
        state: present
        insecure_skip_tls_verify: true
    - name: Test helm pull insecure
      kubernetes.core.helm_pull:
        chart_ref: "oci://<helm-repo-with-self-signed-tls>/ptroject"
        destination: /tmp
        insecure_skip_tls_verify: true
    - name: Test helm insecure
      kubernetes.core.helm:
        name: insecure
        chart_ref: "oci://<helm-repo-with-self-signed-tls>/project"
        namespace: helm-insecure-test
        state: present
        insecure_skip_tls_verify: true
Note
Might need an alias for telm_template, as the option is called insecure_registry, in the manual and docs of helm it would be --insecure-skip-tls-verify as well though.
Not included, as it was recently merged with #805

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
Reviewed-by: Mike Graves <mgraves@redhat.com>
2025-05-06 23:32:56 +00:00
patchback[bot]andGitHub d531368d64 Update ansible-lint version to 25.1.2 (#919) (#921)
This is a backport of PR #919 as merged into main (b594d35).
Update ansible-lint version to 25.1.2

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2025-04-29 18:03:42 +00:00
patchback[bot]andGitHub c3bf5cc47f add reset_then_reuse_values support to helm module (#802) (#917)
This is a backport of PR #802 as merged into main (00699ac).
SUMMARY
Starting with version 3.14.0, Helm supports --reset-then-reuse-values. As discussed on the original PR. This greatly improves on --reuse-values as it allows to avoid templates errors when new features are added to an upgraded chart.
Closes #803
ISSUE TYPE

Feature Pull Request

COMPONENT NAME
helm
ADDITIONAL INFORMATION
This PR is greatly 'inspired' by #575 and because I wasn't sure how I could provide additional tests for it, I actually copied those build previously for --reuse-values (as it is an improvement on this feature.

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2025-04-29 17:54:15 +00:00
patchback[bot]andGitHub 349534b85b Rebase PR #898 (#905) (#913)
This is a backport of PR #905 as merged into main (d329e7e).
This PR is a rebase of #898 for CI to pass
Thanks @efussi for your collaboration.
Closes #892

Reviewed-by: Bikouo Aubin
Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2025-04-25 15:59:21 +00:00
92e3f98a20 Bugfix: fix unit-source for pre-release of ansible-core 2.20 (devel and milestone branch) (#903) (#909)
SUMMARY
CI fix for #904
ISSUE TYPE

Bugfix Pull Request

COMPONENT NAME
tests/unit
ADDITIONAL INFORMATION

Reviewed-by: Mike Graves <mgraves@redhat.com>
Reviewed-by: Bianca Henderson <beeankha@gmail.com>
(cherry picked from commit d4fc22c74e)

Co-authored-by: Yuriy Novostavskiy <yuriy@novostavskiy.kiev.ua>
2025-04-25 11:01:13 -04:00
d2dcb9e55f Run integration tests using ansible-core 2.19 (#888) (#895)
* fix integration test ``k8s_full`` running with ansible-core 2.19

* Fix templating issues

* fix test on current ansible version

* fix tests cases

* Fix additional tests

* fix the templating mechanism

* consider using variable_[start/end]_string while parsing template

* Remove support for omit into template option

* Remove unnecessary unit tests

(cherry picked from commit 2cb5d6c316)

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>
2025-04-25 16:49:10 +02:00
Mike GravesandGitHub 0eff03dd19 Prep 5.2.0 release (#891)
SUMMARY

Prep 5.2.0 release

ISSUE TYPE

COMPONENT NAME

ADDITIONAL INFORMATION

Reviewed-by: Yuriy Novostavskiy
Reviewed-by: Bikouo Aubin
Reviewed-by: Alina Buzachis
2025-03-31 17:20:25 +00:00
patchback[bot]andGitHub 81fb8662da waiter.py Add ClusterOperator Test (#879) (#882)
This is a backport of PR #879 as merged into main (7cdf0d0).
SUMMARY
Fixes #869
During an OpenShift installation, one of the checks to see that the cluster is ready to proceed with configuration is to check to ensure that the Cluster Operators are in an Available: True Degraded: False Progressing: False state. While you can currently use the k8s_info module to get a json response, the resulting json needs to be iterated over several times to get the appropriate status.
This PR adds functionality into waiter.py which loops over all resource instances of the cluster operators. If any of them is not ready, waiter returns False and the task false. If the task returns, you can assume that all the cluster operators are healthy.


ISSUE TYPE


Feature Pull Request

COMPONENT NAME

waiter.py
ADDITIONAL INFORMATION



A simple playbook will trigger the waiter.py to watch the ClusterOperator object

---
- name: get operators
  hosts: localhost
  gather_facts: false
  tasks:
    - name: Get cluster operators
      kubernetes.core.k8s_info:
        api_version: v1
        kind: ClusterOperator
        kubeconfig: "/home/ocp/one/auth/kubeconfig"
        wait: true
        wait_timeout: 30
      register: cluster_operators


This will produce the simple response if everything is functioning properly:
PLAY [get operators] *************************************************************************************************

TASK [Get cluster operators] *****************************************************************************************
ok: [localhost]

PLAY RECAP ***********************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

If the timeout is reached:
PLAY [get operators] *************************************************************************************************

TASK [Get cluster operators] *****************************************************************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions.CoreException: Failed to gather information about ClusterOperator(s) even after waiting for 30 seconds
fatal: [localhost]: FAILED! => {"changed": false, "msg": "Failed to gather information about ClusterOperator(s) even after waiting for 30 seconds"}

PLAY RECAP ***********************************************************************************************************
localhost                  : ok=0    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0   

UNSOLVED: How to know which Operators are failing

Reviewed-by: Bikouo Aubin
2025-03-26 15:50:36 +00:00
patchback[bot]andGitHub f74ee14d71 Extend hidden_fields to allow more complicated field definitions (#872) (#887)
This is a backport of PR #872 as merged into main (9ec6912).
SUMMARY
This allows us to ignore e.g. the last-applied-configuration annotation by specifying
metadata.annotations[kubectl.kubernetes.io/last-applied-configuration]
ISSUE TYPE

Feature Pull Request

COMPONENT NAME
hidden_fields
This replaces #643 as I no longer have permissions to push to branches in this repo

Reviewed-by: Bikouo Aubin
2025-03-25 13:36:12 +00:00
patchback[bot]andGitHub 6f75d86954 Fix linters in CI (#873) (#876)
This is a backport of PR #873 as merged into main (91df2f1).
SUMMARY
It seems that recent updates in linters break CI. Closes #874
ISSUE TYPE

Bugfix Pull Request

COMPONENT NAME
CI
ADDITIONAL INFORMATION

Reviewed-by: Mike Graves <mgraves@redhat.com>
2025-02-06 15:45:54 +00:00
Yuriy NovostavskiyandGitHub c93a7e2459 prepare release 5.1.0 (#865)
SUMMARY
This release came with new module helm_registry_auth, and improvements to the error messages in the k8s_drain module, new parameter insecure_registry for helm_template module and several bug fixes.
ISSUE TYPE

New release pull request

Changelog
Minor Changes

Bump version of ansible-lint to minimum 24.7.0 (#765).
Parameter insecure_registry added to helm_template as equivalent of insecure-skip-tls-verify (#805).
connection/kubectl.py - Added an example of using the kubectl connection plugin to the documentation (#741).
k8s_drain - Improve error message for pod disruption budget when draining a node (#797).

Bugfixes

helm - Helm version checks did not support RC versions. They now accept any version tags. (#745).
helm_pull - Apply no_log=True to pass_credentials to silence false positive warning.. (#796).
k8s_drain - Fix k8s_drain does not wait for single pod (#769).
k8s_drain - Fix k8s_drain runs into a timeout when evicting a pod which is part of a stateful set  (#792).
kubeconfig option should not appear in module invocation log (#782).
kustomize - kustomize plugin fails with deprecation warnings (#639).
waiter - Fix waiting for daemonset when desired number of pods is 0. (#756).

New Modules

helm_registry_auth - Helm registry authentication module

ADDITIONAL INFORMATION
Collection kubernets.core version 3.1.0 is compatible with ansible-core>=2.15.0

Reviewed-by: Mike Graves <mgraves@redhat.com>
2025-01-20 15:23:54 +00:00
patchback[bot]andGitHub 2d68a37a52 trivial doc: replace 2.5.0 with 3.0.0 (#831) (#856)
This is a backport of PR #831 as merged into main (bc0de24).
SUMMARY
Some parameters were added to the master in time where the latest version was 2.4.0 with version_added: 2.5.0, however the next version after 2.4.0 was a 3.0.0.
So, with this trivial doc PR (that most probably doesn't require a changelog fragment and including to changelog) I replacing  version_added: 2.5.0 to  version_added: 3.0.0 for:

reuse_values in kubernetes.core.helm module
reset_values in kubernetes.core.helm module
delete_all in  kubernetes.core.k8s module
hidden_fields  in  kubernetes.core.k8s module
hidden_fields   in  kubernetes.core.k8s_info module

All of them are introduced in kubernetes.core 3.0.0
ISSUE TYPE

Docs Pull Request

COMPONENT NAME

helm
k8s
8s_info


ADDITIONAL INFORMATION
PR to be backported to stable-3 and stable-5
2025-01-17 19:01:57 +00:00
c5f5398e9e Remove deprecated .github/stale.yml to address #837 (#838) (#860)
SUMMARY
I noticed that even config for probot/stale is present in the repo, but the old issues and PRs weren't marked as stale and not closed by the bot. Investigated and found that this bot was added to community.kubernetes as ansible-collections/community.kubernetes#53 but wasn't moved to kubernetes.core and never worked here.
Moreover, this bot is completely deprecated and down, ref: probot/stale#430
So, the config to be removed.
ISSUE TYPE

Bugfix Pull Request

COMPONENT NAME
.github/stale.yml
ADDITIONAL INFORMATION
Closes #837
Trivial change that not require changelog

Reviewed-by: Mike Graves <mgraves@redhat.com>
(cherry picked from commit eb731cd3a5)

Co-authored-by: Yuriy Novostavskiy <yuriy@novostavskiy.kiev.ua>
2025-01-17 11:53:31 -05:00
patchback[bot]andGitHub 05aea7727d helm_pull: Silence false no_log warning (#796) (#858)
This is a backport of PR #796 as merged into main (ecc64ca).
SUMMARY
Apply no_log=True to pass_credentials to silence false positive warning.
Fixes similar issue to: #423
ISSUE TYPE

Bugfix Pull Request

COMPONENT NAME
changelog/fragements/796-false-positive-helmull.yaml
plugins/modules/helm_pull.py
2025-01-17 16:21:23 +00:00
patchback[bot]andGitHub d3f6dd186c fix linters in github actions (#848) (#849)
This is a backport of PR #848 as merged into main (159a63a).
SUMMARY
After the release 25.0.0 of ansible-compat the linters in CI become failing. In the ansible-lint issue already created
COMPONENT NAME
.github/workflows/linters.yaml
ADDITIONAL INFORMATION
Fix bug #846
within this commit ansible/ansible-lint is updated to 24.12.2 and the ansible-lint config moved to the .config folder
2025-01-17 15:52:51 +00:00
patchback[bot]andGitHub 8cee9fddbe Clean up test namespace (#852) (#854)
This is a backport of PR #852 as merged into main (9f60b15).
SUMMARY

The helm_set_values test target did not clean up its namespace which is leading to unstable tests in the k8s_drain target.

ISSUE TYPE


Bugfix Pull Request

COMPONENT NAME

ADDITIONAL INFORMATION
2025-01-17 15:29:22 +00:00
05a942e41e helm_registry_auth module to authenticate in OCI registry (#800) (#836)
* new module helm_registry_auth

* Initial integration tests

* final update copyright and integration test before pr

* update link to pr in changelog fragment

* reformat plugins/module_utils/helm.py with black

to fix linters in actions

* attempt to fix unit test

unit test was missing initially

* fix https://pycqa.github.io/isort/ linter

* next attemp to fix unit-test

* remove unused and unsupported helm_args_common

* remove unused imports and fix other linters errors

* another fix for unit test

* fix issue introducied by commit ff02893a12a31f9c44b5c48f9a8bf85057295961

* add binary_path to arg_spec

* return helm_cmd in the output of check mode

remove changlog fragment

* description suggestion from reviewer/maintainer

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>

* description suggestion from reviewer/maintainer

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>

* description suggestion from reviewer/maintainer

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>

* description suggestion from reviewer/maintainer

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>

* description suggestion from reviewer/maintainer

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>

* description suggestion from reviewer/maintainer

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>

* description suggestion from reviewer/maintainer

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>

* description suggestion from reviewer/maintainer

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>

* remove changed from module return

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>

* remove redundant code

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>

* Update plugins/modules/helm_registry_auth.py

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>

* consider support of logout when user is not logged in

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>

* consider support helm < 3.0.0

* Revert "consider support helm < 3.0.0"

This reverts commit f20004d196.

* reintroduce support of helm version less than 3.8.0

reference: https://helm.sh/docs/topics/registries/#enabling-oci-support-prior-to-v380

* revert reintroducing support of helm < 3.8.0

reason: didn't find a quick way to deal with tests

* update documentation with the recent module updates

* Update plugins/modules/helm_registry_auth.py

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>

* add test of logout impendency

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>

* fix linters

* fix intendations in the integration tests

* create tests/integration/targets/helm_registry_auth/aliases

* fix integration test (typo)

* fix integration tests (test wrong cred)

* add stderr when module fail

* another attempt to fix integration test

* fix assertion in integration test to be not affceted by the #830

---------

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>
(cherry picked from commit aee847431a)

Co-authored-by: Yuriy Novostavskiy <yuriy@novostavskiy.kiev.ua>
2024-12-17 18:33:15 +01:00
fcd47ca995 Remove kubeconfig value from module invocation log (#826) (#840)
(cherry picked from commit 6efabd3418)

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>
2024-12-17 18:32:59 +01:00
f1729ce186 fix: typo (#804) (#834)
* fix: typo

replaces https://github.com/ansible-collections/kubernetes.core/pull/799

* doc: add changelog fragment

* Delete changelogs/fragments/804-drain-typo.yaml

---------

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>
(cherry picked from commit 219c747a24)

Co-authored-by: Pierre Ozoux <pierre@ozoux.net>
2024-12-17 17:49:56 +01:00
c37dc5b566 Parameter insecure_registry added to helm_template (#805) (#835)
* Parameter insecure_registry added to helm_template as equivalent of insecure-skip-tls-verify

(cherry picked from commit 6609abdd5a)

Co-authored-by: Yuriy Novostavskiy <yuriy@novostavskiy.kiev.ua>
2024-12-17 17:47:35 +01:00
410855cd36 Fix helm integration tests (#830) (#833)
SUMMARY
Fix charts ref on integration tests targets
ISSUE TYPE

Bugfix Pull Request

Reviewed-by: Yuriy Novostavskiy
Reviewed-by: Alina Buzachis
(cherry picked from commit 7559b65946)

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>
2024-12-17 12:16:41 +01:00
patchback[bot]andGitHub e1f52ddbee Fix helm tests (#827) (#828)
This is a backport of PR #827 as merged into main (c8a33c7).
SUMMARY

Some of the charts we've used for testing are no longer available at the old helm repository urls, as they've been moved to oci registries. This updates those charts.
In the longer term, we should find a better way to handle these kinds of test fixtures, probably by switching to local charts as much as possible.

ISSUE TYPE


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

COMPONENT NAME

ADDITIONAL INFORMATION

Reviewed-by: Bikouo Aubin
2024-12-16 08:32:45 +00:00
patchback[bot]andGitHub 5d038db848 Update README.md with removing outdated communication channels (#790) (#825)
This is a backport of PR #790 as merged into main (b8e9873).
SUMMARY
As part of the consolidating Ansible discussion platforms and communication channels was decided to use the Ansible forum as the main place for questions and discussion.
Reference: https://forum.ansible.com/t/proposal-consolidating-ansible-discussion-platforms/6812
As part of this change, the IRC channel was removed by the PRs #778 and #774.
However, the README.md file wasn't fully cleaned up from the outdated information.
The #ansible-kubernetes channel on libera.chat IRC isn't used by maintainers and contributors anymore.
The Wiki page on the https://github.com/ansible/community/ was deprecated a long time ago
ISSUE TYPE

Docs Pull Request

COMPONENT NAME
README.md
2024-12-11 20:35:22 +00:00
patchback[bot]andGitHub 9d3195641e CONTRIBUTING.md remove IRC (#778) (#824)
This is a backport of PR #778 as merged into main (c8a9326).
SUMMARY
As a part of https://forum.ansible.com/t/proposal-consolidating-ansible-discussion-platforms/6812
ISSUE TYPE

Docs Pull Request

COMPONENT NAME
CONTRIBUTING.md
2024-12-11 20:35:19 +00:00
Yuriy NovostavskiyandGitHub dac1448b9c README: Add Communication section with Forum information (#774) (#823)
SUMMARY


ISSUE TYPE


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

COMPONENT NAME

ADDITIONAL INFORMATION

Reviewed-by: Mike Graves <mgraves@redhat.com>
2024-12-11 18:54:13 +00:00
patchback[bot]andGitHub 4bdff5d672 Make k8s_drain work when only one pod is present (#770) (#820)
This is a backport of PR #770 as merged into main (4c305e7).
SUMMARY
Fixes #769 .
k8s_drain was not checking if a pod has been deleted when there was only one pod on the node to be drained.
The list of pods, pods, was being "popped" before the first iteration of the while loop:
        pod = pods.pop()
        while (_elapsed_time() < wait_timeout or wait_timeout == 0) and pods:
When pods contains only one element, the while loop is skipped.


ISSUE TYPE


Bugfix Pull Request

COMPONENT NAME

k8s_drain
2024-12-11 16:23:41 +00:00
patchback[bot]andGitHub 19a71c82ba Update Readme to match the template (#767) (#819)
This is a backport of PR #767 as merged into main (fdb8af7).
SUMMARY


Refer: https://issues.redhat.com/browse/ACA-1749
This PR updates the README doc to match the template
ISSUE TYPE


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

COMPONENT NAME

ADDITIONAL INFORMATION
2024-12-11 16:17:45 +00:00
patchback[bot]andGitHub c73f3e3f75 Bump the ansible-lint version to 24.7.0 (#765) (#818)
This is a backport of PR #765 as merged into main (a89f19b).
SUMMARY

Bump the ansible-lint version to 24.7.0

ISSUE TYPE

COMPONENT NAME

ADDITIONAL INFORMATION
2024-12-11 15:58:13 +00:00
patchback[bot]andGitHub 2cdcc195e6 fix shields.io badges in README.md (#749) (#817)
This is a backport of PR #749 as merged into main (0afd257).
SUMMARY
This PR fixes shields.io badges in README.md. It's just cosmetic bugfix
ISSUE TYPE

Bugfix Pull Request

COMPONENT NAME
README.md
ADDITIONAL INFORMATION
Current README.md:

This PR:
2024-12-11 15:26:43 +00:00
patchback[bot]andGitHub e98605eb16 Improve error message for pod disruption budget when draining a node (#798) (#816)
This is a backport of PR #798 as merged into main (52f2cb5).
SUMMARY
Closes #797 .
The error message "Too Many Requests" is confusing and is changed to a more meaningful message:
TASK [Drain node] *************************************************************************
Montag 25 November 2024  09:20:28 +0100 (0:00:00.014)       0:00:00.014 ******* 
fatal: [host -> localhost]: FAILED! => {"changed": false, "msg": "Failed to delete pod kube-public/draintest-6b84677b99-9jf7m due to: Cannot evict pod as it would violate the pod's disruption budget."}


The new task output would allow to deal with a pod disruption budget with the retries/until logic in a more controlled way:
---
- hosts: "{{ target }}"
  serial: 1
  gather_facts: false
  tasks:
    - name: Drain node
      kubernetes.core.k8s_drain:
        kubeconfig: "{{ kubeconfig_path }}"
        name: "{{ inventory_hostname }}"
        delete_options:
          ignore_daemonsets: true
          delete_emptydir_data: true
          wait_timeout: 100
          disable_eviction: false
          wait_sleep: 1
      delegate_to: localhost
      retries: 10
      delay: 5
      until: drain_result is success or 'disruption budget' not in drain_result.msg
      register: drain_result

ISSUE TYPE


Feature Pull Request

COMPONENT NAME
k8s_drain
2024-12-11 15:14:49 +00:00
patchback[bot]andGitHub e13a7fd0c6 update changelog with release 3.2.0 (#750) (#814)
This is a backport of PR #750 as merged into main (d192157).
SUMMARY
Minor/cosmetic documentation change with adding release 3.2.0 to changelog for master as the release is from stable-3 branch
ISSUE TYPE

Docs Pull Request

COMPONENT NAME
CHANGELOG.md
ADDITIONAL INFORMATION
Most probably this PR should be backported to the stable-5 branch after the merge to the main and should be with a skip-changelog tag.
2024-12-11 15:14:44 +00:00
patchback[bot]andGitHub 2098dfea5e Fix k8s_drain runs into timeout with pods from stateful sets. (#793) (#808)
This is a backport of PR #793 as merged into main (fca0dc0).
SUMMARY
Fixes #792 .
The function wait_for_pod_deletion in k8s_drain never checks on which node a pod is actually running:
            try:
                response = self._api_instance.read_namespaced_pod(
                    namespace=pod[0], name=pod[1]
                )
                if not response:
                    pod = None
                time.sleep(wait_sleep)
This means that if a pod is successfully evicted and restarted with the same name on a new node, k8s_drain does not notice and thinks that the original pod is still running. This is the case for pods which are part of a stateful set.

ISSUE TYPE


Bugfix Pull Request

COMPONENT NAME
k8s_drain
2024-12-11 14:12:35 +00:00
patchback[bot]andGitHub 10a9b9e811 Remove kubevirt integration test workflow (#806) (#810)
This is a backport of PR #806 as merged into main (513ff66).
SUMMARY

This removes the kubevirt integration tests. We don't maintain that collection or have any permissions on that repo, so there's no reason for these tests to be here.

ISSUE TYPE


Bugfix Pull Request


COMPONENT NAME

ADDITIONAL INFORMATION

Reviewed-by: Mike Graves <mgraves@redhat.com>
2024-12-10 18:22:42 +00:00
patchback[bot]andGitHub 67868442f3 [ci] fix github actions post 2.18 (#789) (#812)
This is a backport of PR #789 as merged into main (cd68631).
This PR includes a trivial fix for the GitHub Actions issue #788 and related to switching milestone and devel branches of ansible/ansible to version 2.19 and prepare repo to be ready to include test with Python 3.13 when ansible-network/github_actions/pull/162 is merged.
ISSUE TYPE

Bugfix Pull Request

COMPONENT NAME
GitHub actions/test

Reviewed-by: Mike Graves <mgraves@redhat.com>
2024-12-10 17:13:53 +00:00
patchback[bot]andGitHub 5eefa9c308 fix: kustomize plugin fails with deprecation warnings (#728) (#764)
This is a backport of PR #728 as merged into main (5bc53db).
SUMMARY

error judgments are based on the exit codes of command execution, where 0 represents success and non-zero represents failure.
Optimize the run_command function to return a tuple like the run_command method of AnsibleModule.

Fixes #639
ISSUE TYPE


Bugfix Pull Request

COMPONENT NAME

kustomize lookup plugin
ADDITIONAL INFORMATION

Reviewed-by: Mike Graves <mgraves@redhat.com>
2024-07-15 13:56:34 +00:00
patchback[bot]andGitHub 4ed9105797 Fix waiting for daemonset when desired number of pods is 0 (#756) (#762)
This is a backport of PR #756 as merged into main (b07fbd6).
Fixes #755
SUMMARY
Because we don't have any node with non_exisiting_label (see code below) desired number of Pods will be 0. Kubernetes won't create .status.updatedNumberScheduled field (at least on version v1.27), because we still are not going to create any Pods. So that if .status.updatedNumberScheduled doesn't exist we should assume that number is 0
Code to reproduce:
- name: Create daemonset
  kubernetes.core.k8s:
    state: present
    wait: true
    definition:
      apiVersion: apps/v1
      kind: DaemonSet
      metadata:
        name: my-daemonset
        namespace: default
      spec:
        selector:
          matchLabels:
            app: my-app
        template:
          metadata:
            labels:
              app: my-app
          spec:
            containers:
              - name: my-container
                image: nginx
            nodeSelector:
              non_exisiting_label: 1
ISSUE TYPE

Bugfix Pull Request

COMPONENT NAME
kubernetes.core.plugins.module_utils.k8s.waiter
ADDITIONAL INFORMATION



TASK [Create daemonset] **********************************************************************************************************************************
changed: [controlplane] => {"changed": true, "duration": 5, "method": "create", "result": {"apiVersion": "apps/v1", "kind": "DaemonSet", "metadata": {"annotations": {"deprecated.daemonset.template.generation": "1"}, "creationTimestamp": "2024-06-28T08:23:41Z", "generation": 1, "managedFields": [{"apiVersion": "apps/v1", "fieldsType": "FieldsV1", "fieldsV1": {"f:metadata": {"f:annotations": {".": {}, "f:deprecated.daemonset.template.generation": {}}}, "f:spec": {"f:revisionHistoryLimit": {}, "f:selector": {}, "f:template": {"f:metadata": {"f:labels": {".": {}, "f:app": {}}}, "f:spec": {"f:containers": {"k:{\"name\":\"my-container\"}": {".": {}, "f:image": {}, "f:imagePullPolicy": {}, "f:name": {}, "f:resources": {}, "f:terminationMessagePath": {}, "f:terminationMessagePolicy": {}}}, "f:dnsPolicy": {}, "f:nodeSelector": {}, "f:restartPolicy": {}, "f:schedulerName": {}, "f:securityContext": {}, "f:terminationGracePeriodSeconds": {}}}, "f:updateStrategy": {"f:rollingUpdate": {".": {}, "f:maxSurge": {}, "f:maxUnavailable": {}}, "f:type": {}}}}, "manager": "OpenAPI-Generator", "operation": "Update", "time": "2024-06-28T08:23:41Z"}, {"apiVersion": "apps/v1", "fieldsType": "FieldsV1", "fieldsV1": {"f:status": {"f:observedGeneration": {}}}, "manager": "kube-controller-manager", "operation": "Update", "subresource": "status", "time": "2024-06-28T08:23:41Z"}], "name": "my-daemonset", "namespace": "default", "resourceVersion": "1088421", "uid": "faafdbf7-4388-4cec-88d5-84657966312d"}, "spec": {"revisionHistoryLimit": 10, "selector": {"matchLabels": {"app": "my-app"}}, "template": {"metadata": {"creationTimestamp": null, "labels": {"app": "my-app"}}, "spec": {"containers": [{"image": "nginx", "imagePullPolicy": "Always", "name": "my-container", "resources": {}, "terminationMessagePath": "/dev/termination-log", "terminationMessagePolicy": "File"}], "dnsPolicy": "ClusterFirst", "nodeSelector": {"non_exisiting_label": "1"}, "restartPolicy": "Always", "schedulerName": "default-scheduler", "securityContext": {}, "terminationGracePeriodSeconds": 30}}, "updateStrategy": {"rollingUpdate": {"maxSurge": 0, "maxUnavailable": 1}, "type": "RollingUpdate"}}, "status": {"currentNumberScheduled": 0, "desiredNumberScheduled": 0, "numberMisscheduled": 0, "numberReady": 0, "observedGeneration": 1}}}

~$ kubectl get ds
NAME           DESIRED   CURRENT   READY   UP-TO-DATE   AVAILABLE   NODE SELECTOR           AGE
my-daemonset   0         0         0       0            0           non_exisiting_label=1   30s

Reviewed-by: Mike Graves <mgraves@redhat.com>
2024-07-10 14:32:11 +00:00
patchback[bot]andGitHub 46f8e4adfb [PR #731/c0666a51 backport][stable-5] kubevirt.core collection cross testing (#760)
This is a backport of PR #731 as merged into main (c0666a5).
SUMMARY

The kubevirt.core collection has dependency with this collection. We define new workflows to ensure that nothing is broken on that collection when pushing new changes on this collection.

ISSUE TYPE


Feature Pull Request

COMPONENT NAME

CI

Reviewed-by: Mike Graves <mgraves@redhat.com>
2024-07-10 13:57:49 +00:00
patchback[bot]andGitHub 5761205513 helm: Accept release candidate versions for compatibility checks (#745) (#754)
This is a backport of PR #745 as merged into main (6a04f42).
SUMMARY

If the helm CLI version includes -rc.1 for example, the version checks fails due to an incomplete regex.
The error can be triggered if you use helm v3.15.0-rc.1 for example, and apply a helm chart with wait: true 
ISSUE TYPE


Bugfix Pull Request

COMPONENT NAME
helm
helm_pull
ADDITIONAL INFORMATION

Reviewed-by: Mike Graves <mgraves@redhat.com>
2024-06-18 13:05:55 +00:00
Bikouo AubinandGitHub 7b0190f8d5 Prepare release 5.0.0 (#733) 2024-06-10 15:39:42 +02:00
patchback[bot]andGitHub c47e691101 Doc: add example of using kubectl connection plugin (#741) (#744)
[PR #741/fb80d973 backport][stable-5] Doc: add example of using kubectl connection plugin

This is a backport of PR #741 as merged into main (fb80d97).
SUMMARY
Currently documentation for collection don't include any examples of using kubenrenes.core.kubectl connection plugin and it's hard to start using that plugin.
ISSUE TYPE

Docs Pull Request

COMPONENT NAME
kubenrenes.core.kubectl connection plugin
ADDITIONAL INFORMATION
This PR was inspired by #288 and based on feedback on that PR and my own experience. Thanks @tpo for his try and @geerlingguy for his Ansible for DevOps book

Reviewed-by: Mike Graves <mgraves@redhat.com>
2024-06-06 14:34:01 +00:00
8ae6469696 Defer removal of inventory/k8s to 6.0.0 (#734) (#740)
Defer removal of inventory/k8s to 6.0.0

SUMMARY
Defer removal of inventory plugin k8s to release 6.0.0.

ISSUE TYPE

Feature Pull Request

Reviewed-by: Alina Buzachis
Reviewed-by: Mike Graves <mgraves@redhat.com>
(cherry picked from commit 0c5233a650)

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>
2024-05-31 10:09:39 +02:00
1174fee5c9 Remove support for ansible-core<2.15 (#737) (#739)
Drop support for ansible-core<2.15

SUMMARY

Remove support for ansible-core<2.15

ISSUE TYPE

Feature Pull Request

Reviewed-by: Mike Graves <mgraves@redhat.com>
(cherry picked from commit 8363a4debf)

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>
2024-05-31 10:06:48 +02:00
Bikouo AubinandGitHub f22ffcab18 Prepare release 4.0.0 (#727)
* Prepare release 4.0.0

* update documentation
2024-05-28 11:37:32 +02:00
231 changed files with 3391 additions and 9333 deletions
-3
View File
@@ -1,9 +1,6 @@
--- ---
profile: production profile: production
warn_list:
- no-log-password
exclude_paths: exclude_paths:
- .ansible/ - .ansible/
- .github/ - .github/
+4
View File
@@ -1,4 +1,8 @@
# https://docs.ansible.com/ansible-lint/docs/rules/ # https://docs.ansible.com/ansible-lint/docs/rules/
# no-changed-when is not requried for examples
plugins/connection/kubectl.py no-changed-when
# false positive result
plugins/connection/kubectl.py var-naming[no-reserved]
plugins/connection/kubectl.py jinja[invalid] plugins/connection/kubectl.py jinja[invalid]
# collection EE metadata is not an ansible-builder definition file # collection EE metadata is not an ansible-builder definition file
meta/execution-environment.yml schema[execution-environment] meta/execution-environment.yml schema[execution-environment]
+27 -3
View File
@@ -81,6 +81,8 @@ jobs:
steps: steps:
- run: | - run: |
python -c " python -c "
import sys
required = ['sanity', 'units', 'coverage'] required = ['sanity', 'units', 'coverage']
if '${{ github.event_name }}' == 'pull_request': if '${{ github.event_name }}' == 'pull_request':
required = ['security-check', 'linters', 'sanity', 'units', 'coverage'] required = ['security-check', 'linters', 'sanity', 'units', 'coverage']
@@ -91,7 +93,29 @@ jobs:
'units': '${{ needs.units.result }}', 'units': '${{ needs.units.result }}',
'coverage': '${{ needs.coverage.result }}', 'coverage': '${{ needs.coverage.result }}',
} }
ok = all(results[j] == 'success' for j in required)
skipped_ok = all(results[j] in ('success', 'skipped') for j in results) for name in required:
assert ok and skipped_ok, f'required={required} results={results}' if results[name] == 'failure':
print(f'all_green: required job failed: {name} results={results}', file=sys.stderr)
sys.exit(1)
# cancel-in-progress superseded this run; do not fail (newer run is authoritative)
if any(v == 'cancelled' for v in results.values()):
print(
'all_green: one or more jobs cancelled (usually concurrency); skipping strict gate.',
results,
)
sys.exit(0)
not_ok = [j for j in required if results[j] != 'success']
if not_ok:
print(f'all_green: required jobs not success: {not_ok} results={results}', file=sys.stderr)
sys.exit(1)
for job, status in results.items():
if job not in required and status not in ('success', 'skipped'):
print(f'all_green: unexpected {job}={status} results={results}', file=sys.stderr)
sys.exit(1)
print('all_green OK', results)
" "
-20
View File
@@ -1,20 +0,0 @@
---
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
@@ -1,210 +0,0 @@
name: Integration tests Helm
concurrency:
group: integration-tests-helm-${{ github.head_ref }}
cancel-in-progress: true
on:
pull_request:
types:
- opened
- reopened
- labeled
- unlabeled
- synchronize
branches:
- main
- stable-*
permissions: {}
jobs:
splitter:
env:
source_dir: "./source"
runs-on: ubuntu-latest
outputs:
helm_targets: ${{ steps.select-targets.outputs.targets }}
permissions:
pull-requests: read
contents: read
steps:
- name: Checkout the collection repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
path: ${{ env.source_dir }}
fetch-depth: "0"
ref: ${{ github.event.pull_request.head.sha }}
persist-credentials: false
- name: list changes for pull request
id: splitter
uses: ansible-network/github_actions/.github/actions/ansible_test_splitter@4678c74a7d712d55e663c88f66eec6d9c3642550
with:
collections_to_test: ${{ env.source_dir }}
total_jobs: 8
- name: Select Helm targets
id: select-targets
run: |
import os, json
with open(os.environ.get('GITHUB_OUTPUT'), "a", encoding="utf-8") as fh:
data = os.environ.get("ALL_TEST_TARGETS")
targets = []
for target in data.split(";"):
if target and ':' in target:
targets.extend([v for v in target.split(':', maxsplit=1)[1].split(',') if v.startswith('helm')])
fh.write(f'targets={json.dumps(targets)}\n')
shell: python
env:
ALL_TEST_TARGETS: ${{ steps.splitter.outputs.test_targets }}
integration:
runs-on: ubuntu-latest
timeout-minutes: 60
needs:
- splitter
if: ${{ needs.splitter.outputs.helm_targets != '' && needs.splitter.outputs.helm_targets != '[]' }}
env:
source: "./source"
ansible_posix: "./ansible_posix"
community_general: "./community_general"
ansible-version: "milestone"
python-version: "3.13"
permissions:
contents: read
strategy:
fail-fast: false
matrix:
helm-version:
- v3.0.0
- v3.1.0
- v3.8.0
- v3.10.3
- v3.15.4
- v3.16.0
- v3.17.0
- v3.22.0
- v4.0.0
- v4.2.1
- latest
ansible_test_target: ${{ fromJson(needs.splitter.outputs.helm_targets) }}
exclude:
# helm_registry_auth: only test against recent versions to reduce CI cost
- ansible_test_target: "helm_registry_auth"
helm-version: "v3.0.0"
- ansible_test_target: "helm_registry_auth"
helm-version: "v3.1.0"
- ansible_test_target: "helm_registry_auth"
helm-version: "v3.8.0"
- ansible_test_target: "helm_registry_auth"
helm-version: "v3.10.3"
- ansible_test_target: "helm_registry_auth"
helm-version: "v3.15.4"
- ansible_test_target: "helm_registry_auth"
helm-version: "v3.16.0"
# helm install/upgrade --create-namespace requires helm >= 3.2.0
- ansible_test_target: "helm_diff"
helm-version: "v3.0.0"
- ansible_test_target: "helm_diff"
helm-version: "v3.1.0"
- ansible_test_target: "helm_diff"
helm-version: "v3.8.0"
- ansible_test_target: "helm_diff"
helm-version: "v3.10.3"
# UPGRADE FAILED: conflict occurred while applying object helm-diff/test-chart-another-configmap /v1
- ansible_test_target: "helm_diff"
helm-version: "v4.0.0"
- ansible_test_target: "helm_repository"
helm-version: "v3.0.0"
- ansible_test_target: "helm_repository"
helm-version: "v3.1.0"
- ansible_test_target: "helm_kubeconfig"
helm-version: "v3.0.0"
- ansible_test_target: "helm_kubeconfig"
helm-version: "v3.1.0"
- ansible_test_target: "helm_set_values"
helm-version: "v3.0.0"
- ansible_test_target: "helm_set_values"
helm-version: "v3.1.0"
- ansible_test_target: "helm_set_values"
helm-version: "v3.8.0"
- ansible_test_target: "helm"
helm-version: "v3.0.0"
- ansible_test_target: "helm"
helm-version: "v3.1.0"
- ansible_test_target: "helm_uninstall"
helm-version: "v3.0.0"
- ansible_test_target: "helm_uninstall"
helm-version: "v3.1.0"
name: "${{ matrix.ansible_test_target }}-${{ matrix.helm-version }}"
steps:
- name: Checkout kubernetes.core repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
path: ${{ env.source }}
ref: ${{ github.event.pull_request.head.sha }}
persist-credentials: false
- name: Set up Python ${{ env.python-version }}
uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
with:
python-version: ${{ env.python-version }}
# install ansible
- name: Install ansible-core (${{ env.ansible-version }})
env:
ANSIBLE_VERSION: ${{ env.ansible-version }}
run: |
curl -sSL --proto '=https' --tlsv1.2 --retry 5 --retry-delay 10 --retry-all-errors \
"https://github.com/ansible/ansible/archive/${ANSIBLE_VERSION}.tar.gz" \
-o ansible.tar.gz
python3 -m pip install --disable-pip-version-check ./ansible.tar.gz
rm ansible.tar.gz
shell: bash
- name: Build and install collection
id: install-src
uses: ansible-network/github_actions/.github/actions/build_install_collection@4678c74a7d712d55e663c88f66eec6d9c3642550
with:
install_python_dependencies: true
source_path: ${{ env.source }}
- name: create kubernetes cluster
uses: helm/kind-action@ef37e7f390d99f746eb8b610417061a60e82a6cc # v1.14.0
with:
node_image: "kindest/node:v1.29.2"
- name: "Install Helm version ${{ matrix.helm-version }}"
uses: azure/setup-helm@9bc31f4ebc9c6b171d7bfbaa5d006ae7abdb4310 # v5.0.1
with:
version: '${{ matrix.helm-version }}'
- name: Verify Helm Installation
run: helm version
- name: Disable selinux with selinux_please_lie_to_me
run: |
python3 -m pip uninstall -y selinux
python3 -m pip install --only-binary=:all: selinux_please_lie_to_me==1.0.1
shell: bash
- name: Install python requirements
run: python3 -m pip install -r requirements.txt -r test-requirements.txt
shell: bash
working-directory: ${{ steps.install-src.outputs.collection_path }}
- name: Run integration tests
run: >-
ansible-test integration
--diff
--no-temp-workdir
--color
--skip-tags False
--retry-on-error
--continue-on-error
--python ${{ env.python-version }}
-v
${{ matrix.ansible_test_target }}
shell: bash
working-directory: ${{ steps.install-src.outputs.collection_path }}
+11 -43
View File
@@ -17,8 +17,9 @@ jobs:
source_dir: "./source" source_dir: "./source"
runs-on: ubuntu-latest runs-on: ubuntu-latest
outputs: outputs:
test_targets: ${{ steps.select-targets.outputs.targets }} test_targets: ${{ steps.splitter.outputs.test_targets }}
test_jobs: ${{ steps.select-targets.outputs.jobs }} test_targets_json: ${{ steps.splitter.outputs.test_targets_json }}
test_jobs: ${{ steps.splitter.outputs.test_jobs }}
steps: steps:
- name: Checkout the collection repository - name: Checkout the collection repository
uses: actions/checkout@v3 uses: actions/checkout@v3
@@ -34,40 +35,18 @@ jobs:
collections_to_test: ${{ env.source_dir }} collections_to_test: ${{ env.source_dir }}
total_jobs: 8 total_jobs: 8
- name: Remove all Helm related targets
id: select-targets
run: |
import os, json
with open(os.environ.get('GITHUB_OUTPUT'), "a", encoding="utf-8") as fh:
data = os.environ.get("ALL_TEST_TARGETS")
index = 0
result = {}
for target in data.split(";"):
if target and ':' in target:
k8s = [v for v in target.split(':', maxsplit=1)[1].split(',') if not v.startswith('helm')]
if k8s:
result[index] = ' '.join(k8s)
index += 1
fh.write(f'targets={json.dumps(result)}\n')
fh.write(f'jobs={json.dumps(list(result.keys()))}\n')
shell: python
env:
ALL_TEST_TARGETS: ${{ steps.splitter.outputs.test_targets }}
- name: Display splitter output - name: Display splitter output
env:
TARGETS: ${{ steps.select-targets.outputs.targets }}
JOBS: ${{ steps.select-targets.outputs.jobs }}
run: | run: |
echo "targets => $TARGETS" echo "test_targets=${{ steps.splitter.outputs.test_targets }}"
echo "jobs => $JOBS" echo "test_targets_json=${{ steps.splitter.outputs.test_targets_json }}"
echo "test_jobs=${{ steps.splitter.outputs.test_jobs }}"
shell: bash shell: bash
integration: integration:
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 60 timeout-minutes: 60
needs: needs:
- splitter - splitter
if: ${{ needs.splitter.outputs.test_jobs != '' && needs.splitter.outputs.test_jobs != '[]' }} if: ${{ needs.splitter.outputs.test_targets != '' }}
env: env:
source: "./source" source: "./source"
cloud_common: "./cloudcommon" cloud_common: "./cloudcommon"
@@ -77,24 +56,15 @@ jobs:
fail-fast: false fail-fast: false
matrix: matrix:
# Ref must match a branch/tag on github.com/ansible/ansible (e.g. stable-2.18, not 2.18). # 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] enable-turbo-mode: [true, false]
python-version: ["3.12", "3.13"] python-version: ["3.12", "3.13"]
exclude: 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" - ansible-version: "milestone"
enable-turbo-mode: true enable-turbo-mode: true
- ansible-version: "stable-2.21" # stable-2.18 supports 3.12; milestone (devel) requires >=3.13
enable-turbo-mode: true
# stable-2.18 supports 3.12
- ansible-version: "stable-2.18" - ansible-version: "stable-2.18"
python-version: "3.13" python-version: "3.13"
- ansible-version: "stable-2.21"
python-version: "3.12"
- ansible-version: "milestone" - ansible-version: "milestone"
python-version: "3.12" python-version: "3.12"
workflow-id: ${{ fromJson(needs.splitter.outputs.test_jobs) }} workflow-id: ${{ fromJson(needs.splitter.outputs.test_jobs) }}
@@ -108,14 +78,12 @@ jobs:
fh.write(f'ansible_test_targets={json.loads(os.environ.get("ALL_TEST_TARGETS")).get(os.environ.get("WORKFLOW_ID"))}\n') fh.write(f'ansible_test_targets={json.loads(os.environ.get("ALL_TEST_TARGETS")).get(os.environ.get("WORKFLOW_ID"))}\n')
shell: python shell: python
env: env:
ALL_TEST_TARGETS: ${{ needs.splitter.outputs.test_targets }} ALL_TEST_TARGETS: ${{ needs.splitter.outputs.test_targets_json }}
WORKFLOW_ID: ${{ matrix.workflow-id }} WORKFLOW_ID: ${{ matrix.workflow-id }}
- name: Display ansible test targets - name: Display ansible test targets
env:
ANSIBLE_TEST_TARGETS: ${{ steps.read-targets.outputs.ansible_test_targets }}
run: | run: |
echo "ansible_test_targets -> $ANSIBLE_TEST_TARGETS" echo "ansible_test_targets -> ${{ steps.read-targets.outputs.ansible_test_targets }}"
- name: Checkout kubernetes.core repository - name: Checkout kubernetes.core repository
uses: actions/checkout@v3 uses: actions/checkout@v3
-18
View File
@@ -1,18 +0,0 @@
---
name: label new issues
on:
issues:
types:
- opened
- reopened
jobs:
add_label:
runs-on: ubuntu-latest
permissions:
contents: write
issues: write
steps:
- uses: actions-ecosystem/action-add-labels@v1
with:
labels: needs_triage
+1 -3
View File
@@ -16,13 +16,11 @@ tests/integration/cloud-config-*
.ansible .ansible
# Helm charts # Helm charts
tests/integration/*.tgz tests/integration/*-chart-*.tgz
tests/integration/targets/*/*.tgz
# ansible-test generated file # ansible-test generated file
tests/integration/inventory tests/integration/inventory
tests/integration/*-*.yml tests/integration/*-*.yml
tests/integration/integration_config.yml
# IDE and editor settings # IDE and editor settings
.vscode/ .vscode/
+1 -1
View File
@@ -1,6 +1,6 @@
repos: repos:
- repo: https://github.com/ansible/cloud-content-ci-automation - repo: https://github.com/ansible/cloud-content-ci-automation
rev: 77f45b0357b6b3c27b04e934f0f51c9b50b7aa25 rev: precommit_hook
hooks: hooks:
- id: block-ide-ai-files - id: block-ide-ai-files
always_run: true always_run: true
+3 -226
View File
@@ -4,229 +4,6 @@ Kubernetes Collection Release Notes
.. contents:: Topics .. 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
======
Release Summary
---------------
This release implements minor changes and bug fixes such as a new ``remove`` value to the ``behavior`` option of the ``kubeconfig`` module, allowing entries to be deleted from the kubeconfig file by name, as well as Helm v4 compatibility across the Helm modules.
Minor Changes
-------------
- helm - add the ``server_side`` and ``force_conflicts`` options to control Helm v4 server-side apply when installing or upgrading a release (https://github.com/ansible-collections/kubernetes.core/pull/1164).
- helm_plugin - add ``--keyring`` argument to allow changing the keyring default location. The option is only accepted with ``state=present`` (the ``helm plugin install`` subcommand), as that is the only implemented subcommand that supports ``--keyring`` (https://github.com/ansible-collections/kubernetes.core/pull/1150).
- helm_registry_auth - document that, as of Helm 4.2.1, registry success messages such as ``Login Succeeded`` are printed to stdout instead of stderr (https://github.com/ansible-collections/kubernetes.core/pull/1147).
- kubeconfig - add ``remove`` value to the ``behavior`` option, allowing entries to be deleted from the kubeconfig file by name (https://github.com/ansible-collections/kubernetes.core/pull/1123).
Bugfixes
--------
- ee - added ``meta/execution-environment.yml`` to decouple ansible-builder EE builds from the ``openshift-clients`` system dependency declared in ``bindep.txt``, which is not available in standard UBI repositories and caused builds to fail with ``No package matches 'openshift-clients'`` (https://github.com/ansible-collections/kubernetes.core/issues/1141).
- helm - use ``--server-side=false --force-replace`` instead of the deprecated/removed ``--force`` flag when ``force=true`` is used with Helm v4, preserving the Helm v3 client-side replacement behaviour and avoiding the server-side apply conflict (https://github.com/ansible-collections/kubernetes.core/pull/1164).
- helm - use the ``--rollback-on-failure`` flag instead of the deprecated/removed ``--atomic`` flag when ``atomic=true`` is used with Helm v4 (https://github.com/ansible-collections/kubernetes.core/pull/1144).
- helm_repository - correct handling of repository URLs with trailing slashes (https://github.com/ansible-collections/kubernetes.core/pull/1121).
- k8s_drain - Fix logic for handling pods with local storage to correctly check for empty_dir volumes in replicated pods and pods managed by DaemonSets (https://github.com/ansible-collections/kubernetes.core/pull/1095).
New Modules
-----------
- kubeconfig - Generate, update, and optionally write Kubernetes kubeconfig files
v6.4.0
======
Release Summary
---------------
This release adds Helm v4 compatibility across the Helm modules and improves ``k8s_drain`` with check mode. When you explicitly allow evicting unmanaged pods, pods with local storage, or pods managed by a ``DaemonSet``, those cases are reported as informational output instead of module warnings.
Minor Changes
-------------
- helm_info - Ensure compatibility with Helm v4 (https://github.com/ansible-collections/kubernetes.core/issues/1038).
- helm_plugin - Ensure compatibility with Helm v4 (https://github.com/ansible-collections/kubernetes.core/issues/1038).
- helm_plugin_info - Ensure compatibility with Helm v4 (https://github.com/ansible-collections/kubernetes.core/issues/1038).
- helm_pull - Ensure compatibility with Helm v4 (https://github.com/ansible-collections/kubernetes.core/issues/1038).
- helm_registry_auth - Ensure compatibility with Helm v4 (https://github.com/ansible-collections/kubernetes.core/issues/1038).
- helm_registry_auth - add new option plain_http to allow insecure http connection when running ``helm registry login`` (https://github.com/ansible-collections/kubernetes.core/pull/1090).
- helm_repository - Ensure compatibility with Helm v4 (https://github.com/ansible-collections/kubernetes.core/issues/1038).
- k8s_drain - Add support for ``check_mode`` (https://github.com/ansible-collections/kubernetes.core/pull/1086).
- k8s_drain - Convert module warnings into informational displays when users explicitly request the deletion of unmanaged pods, pods with local storage, or those managed by a ``DaemonSet`` (https://github.com/ansible-collections/kubernetes.core/issues/1037).
Bugfixes
--------
- Helm - Allow taking ownership of existing Kubernetes resources on the first installation of a Helm release. Previously, the ``take_ownership`` parameter was always disabled during the initial install, preventing resource adoption (https://github.com/ansible-collections/kubernetes.core/pull/1034).
v6.3.0
======
Release Summary
---------------
This release includes bugfixes such as implementing idempotency for the ``helm_pull`` module as well as a security update for selectively redacting sensitive information from kubeconfig.
Minor Changes
-------------
- Remove deprecated import from ``ansible.module_utils._text`` (https://github.com/ansible-collections/kubernetes.core/pull/1053).
- helm - add ``release_values`` key to ``status`` return value that can be accessed using Jinja2 dot notation (https://github.com/ansible-collections/kubernetes.core/pull/1056).
- helm_info - add ``release_values`` key to ``status`` return value that can be accessed using Jinja2 dot notation (https://github.com/ansible-collections/kubernetes.core/pull/1056).
Deprecated Features
-------------------
- helm - the ``status.values`` return value has been deprecated and will be removed in a release after 2027-01-08. Use ``status.release_values`` instead (https://github.com/ansible-collections/kubernetes.core/pull/1056).
- helm_info - the ``status.values`` return value has been deprecated and will be removed in a release after 2027-01-08. Use ``status.release_values`` instead (https://github.com/ansible-collections/kubernetes.core/pull/1056).
Security Fixes
--------------
- Selectively redact sensitive info from kubeconfig instead of applying blanket ``no_log=True`` (https://github.com/ansible-collections/kubernetes.core/pull/1014).
Bugfixes
--------
- Add idempotency for ``helm_pull`` module (https://github.com/ansible-collections/kubernetes.core/pull/1055).
- Fixed a bug where setting ``K8S_AUTH_VERIFY_SSL=true`` (or any string value) caused the value to be treated as a separate ``kubectl`` command argument. (https://github.com/ansible-collections/kubernetes.core/pull/1049).
- Limit supported versions of Helm to <4.0.0 (https://github.com/ansible-collections/kubernetes.core/pull/1039).
- Replace passing ``warnings`` to ``exit_json`` with ``AnsibleModule.warn`` in the ``k8s_drain``, ``k8s_rollback.py`` and ``k8s_scale.py`` modules as it deprecated in ``ansible-core>=2.19.0`` and will be removed in ``ansible-core>=2.23.0`` (https://github.com/ansible-collections/kubernetes.core/pull/1033).
- k8s - Fix return block from the module documentation (https://github.com/ansible-collections/kubernetes.core/pull/1056).
- meta - Add ``k8s_cluster_info``, ``k8s_json_patch`` and ``k8s_rollback`` to k8s action group (https://github.com/ansible-collections/kubernetes.core/pull/992).
v6.2.0
======
Release Summary
---------------
This release adds minor changes and bugfixes, including support of skip-schema-validation in ``helm`` module and removing deprecated ``ansible.module_utils.six`` imports.
Minor Changes
-------------
- Add support of skip-schema-validation in ``helm`` module (https://github.com/ansible-collections/kubernetes.core/pull/995)
- kustomize - Add support of local environ (https://github.com/ansible-collections/kubernetes.core/pull/786).
Bugfixes
--------
- Remove ``ansible.module_utils.six`` imports to avoid warnings (https://github.com/ansible-collections/kubernetes.core/pull/998).
- Update the ``k8s_cp`` module to also work for init containers (https://github.com/ansible-collections/kubernetes.core/pull/971).
v6.1.0
======
Release Summary
---------------
This release adds ``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`` does 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
======
Release Summary
---------------
This major release removes the deprecated ``k8s`` inventory plugin and also removes ``ansible-core<2.16`` support.
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.5.0
======
Release Summary
---------------
This minor release deprecates Ansible Turbo mode (``ENABLE_TURBO_MODE``), the ``status.values`` return value of the ``helm`` and ``helm_info`` modules, the ``wait_timeout`` parameter of the ``helm`` module, the ``return_code`` return value of the ``k8s_exec`` module, and the ``merge_type=json`` option of the ``k8s_service`` module. It also includes bugfixes for ``helm_repository`` URL comparison and for empty template output handling in ``k8s_info``.
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).
- 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).
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_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).
- 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_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).
v5.4.4 v5.4.4
====== ======
@@ -253,7 +30,7 @@ Bugfixes
- ee - Add ``meta/execution-environment.yml`` to decouple ansible-builder EE builds from the ``openshift-clients`` system dependency declared in ``bindep.txt``, which is not available in standard UBI repositories and caused builds to fail with ``No package matches 'openshift-clients'`` (https://github.com/ansible-collections/kubernetes.core/issues/1141). - ee - Add ``meta/execution-environment.yml`` to decouple ansible-builder EE builds from the ``openshift-clients`` system dependency declared in ``bindep.txt``, which is not available in standard UBI repositories and caused builds to fail with ``No package matches 'openshift-clients'`` (https://github.com/ansible-collections/kubernetes.core/issues/1141).
- helm_repository - Correct handling of repository URLs with trailing slashes (https://github.com/ansible-collections/kubernetes.core/pull/1121). - helm_repository - Correct handling of repository URLs with trailing slashes (https://github.com/ansible-collections/kubernetes.core/pull/1121).
- k8s_drain - Fix logic for handling pods with local storage to correctly check for empty_dir volumes in replicated pods and pods managed by DaemonSets (https://github.com/ansible-collections/kubernetes.core/pull/1095). - k8s_drain - Fix logic for handling pods with local storage to correctly check for ``empty_dir`` volumes in replicated pods and pods managed by DaemonSets (https://github.com/ansible-collections/kubernetes.core/pull/1095).
v5.4.2 v5.4.2
====== ======
@@ -261,7 +38,7 @@ v5.4.2
Release Summary Release Summary
--------------- ---------------
This release includes bugfixes such as replacing the passing of ``warnings`` to ``exit_json`` with ``AnsibleModule.warn`` as well as a security update for selectively redacting sensitive information from kubeconfig, and adds a new ``release_values`` key to the ``status`` return value. This release includes bugfixes such as replacing the passing of ``warnings`` to ``exit_json`` with ``AnsibleModule.warn`` as well as a security update for selectively redacting sensitive information from kubeconfig.
Minor Changes Minor Changes
------------- -------------
@@ -302,7 +79,7 @@ Bugfixes
-------- --------
- Remove ``ansible.module_utils.six`` imports to avoid warnings (https://github.com/ansible-collections/kubernetes.core/pull/998). - Remove ``ansible.module_utils.six`` imports to avoid warnings (https://github.com/ansible-collections/kubernetes.core/pull/998).
- Update the ``k8s_cp`` module to also work for init containers (https://github.com/ansible-collections/kubernetes.core/pull/971). - Update the `k8s_cp` module to also work for init containers (https://github.com/ansible-collections/kubernetes.core/pull/971).
- module_utils/k8s/service - hide fields first before creating diffs (https://github.com/ansible-collections/kubernetes.core/pull/915). - module_utils/k8s/service - hide fields first before creating diffs (https://github.com/ansible-collections/kubernetes.core/pull/915).
v5.4.0 v5.4.0
+1 -1
View File
@@ -1,5 +1,5 @@
# Also needs to be updated in galaxy.yml # Also needs to be updated in galaxy.yml
VERSION = 7.0.0-dev0 VERSION = 5.4.4
TEST_ARGS ?= "" TEST_ARGS ?= ""
PYTHON_VERSION ?= `python -c 'import platform; print(".".join(platform.python_version_tuple()[0:2]))'` PYTHON_VERSION ?= `python -c 'import platform; print(".".join(platform.python_version_tuple()[0:2]))'`
+22 -28
View File
@@ -19,17 +19,22 @@ The collection includes a variety of Ansible content to help automate the manage
Click on the name of a plugin or module to view that content's documentation: Click on the name of a plugin or module to view that content's documentation:
<!--start collection content--> <!--start collection content-->
### Connection plugins ### Connection Plugins
Name | Description 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/main/docs/kubernetes.core.kubectl_connection.rst)|Execute tasks in pods running on Kubernetes.
### K8s filter plugins ### K8s filter Plugins
Name | Description Name | Description
--- | --- --- | ---
kubernetes.core.k8s_config_resource_name|Generate resource name for the given resource of type ConfigMap, Secret kubernetes.core.k8s_config_resource_name|Generate resource name for the given resource of type ConfigMap, Secret
### Lookup plugins ### Inventory Plugins
Name | Description
--- | ---
[kubernetes.core.k8s](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_inventory.rst)|Kubernetes (K8s) inventory source
### Lookup Plugins
Name | Description 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.k8s](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_lookup.rst)|Query the K8s API
@@ -58,17 +63,18 @@ Name | Description
[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_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_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.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
<!--end collection content--> <!--end collection content-->
## Requirements ## Requirements
<!--start requires_ansible--> <!--start requires_ansible-->
## Ansible version compatibility ### Ansible version compatibility
This collection has been tested against the 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. Plugins and modules within a collection may be tested with only specific Ansible versions.
A collection may contain metadata that identifies these versions. A collection may contain metadata that identifies these versions.
PEP440 is the schema used to describe the versions of Ansible. PEP440 is the schema used to describe the versions of Ansible.
@@ -76,7 +82,7 @@ PEP440 is the schema used to describe the versions of Ansible.
### Helm Version Compatibility ### Helm Version Compatibility
This collection supports Helm v3.x and newer. Please note that specific modules or certain parameters may have additional version requirements. Helm modules in this collection are compatible with Helm v3.x and are not yet compatible with Helm v4. Individual modules and their parameters may support a more specific range of Helm versions.
### Python Support ### Python Support
@@ -94,27 +100,23 @@ Before using the Kubernetes collection, you need to install it with the Ansible
ansible-galaxy collection install kubernetes.core ansible-galaxy collection install kubernetes.core
Red Hat customers can install certified content from [Ansible Automation Hub](https://console.redhat.com/ansible/automation-hub). Configure Automation Hub as the primary content source for the Ansible Galaxy CLI by following the [Red Hat configuration guide](https://docs.redhat.com/en/documentation/red_hat_ansible_automation_platform/2.4/html/getting_started_with_automation_hub/configure-hub-primary), then install the collection with `ansible-galaxy collection install kubernetes.core`.
You can also include it in a `requirements.yml` file and install it via `ansible-galaxy collection install -r requirements.yml`, using the format: You can also include it in a `requirements.yml` file and install it via `ansible-galaxy collection install -r requirements.yml`, using the format:
```yaml ```yaml
--- ---
collections: collections:
- name: kubernetes.core - name: kubernetes.core
version: 6.6.0 version: 5.4.4
``` ```
### Installing the Kubernetes Python Library ### Installing the Kubernetes Python Library
Content in this collection requires the [Kubernetes Python client](https://pypi.org/project/kubernetes/) to interact with Kubernetes' APIs. For installs outside an execution environment, install it with: Content in this collection requires the [Kubernetes Python client](https://pypi.org/project/kubernetes/) to interact with Kubernetes' APIs. You can install it with:
```bash ```bash
pip3 install kubernetes pip3 install kubernetes
``` ```
Execution environments install this dependency when they are built with `ansible-builder`; you do not need to install it separately with `pip3` in that case.
## Use Cases ## Use Cases
It's preferable to use content in this collection using their Fully Qualified Collection Namespace (FQCN), for example `kubernetes.core.k8s_info`: It's preferable to use content in this collection using their Fully Qualified Collection Namespace (FQCN), for example `kubernetes.core.k8s_info`:
@@ -185,11 +187,7 @@ For documentation on how to use individual modules and other content included in
## Ansible Turbo Mode Tech Preview ## Ansible Turbo Mode Tech Preview
> **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. The ``kubernetes.core`` collection supports Ansible Turbo mode as a tech preview via the ``cloud.common`` collection. 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:
> **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:
```yaml ```yaml
--- ---
@@ -219,8 +217,6 @@ You can run the collection's test suites with the commands:
make test-integration make test-integration
make test-unit make test-unit
For instructions on running Helm integration tests locally, see the [integration tests README](https://github.com/ansible-collections/kubernetes.core/blob/main/tests/integration/README.md).
### Testing with `molecule` ### Testing with `molecule`
There are also integration tests in the `molecule` directory which are meant to be run against a local Kubernetes cluster, e.g. using [KinD](https://kind.sigs.k8s.io) or [Minikube](https://minikube.sigs.k8s.io). To set up a local cluster using KinD and run Molecule: There are also integration tests in the `molecule` directory which are meant to be run against a local Kubernetes cluster, e.g. using [KinD](https://kind.sigs.k8s.io) or [Minikube](https://minikube.sigs.k8s.io). To set up a local cluster using KinD and run Molecule:
@@ -232,7 +228,7 @@ There are also integration tests in the `molecule` directory which are meant to
If you want to develop new content for this collection or improve what is already here, clone the Git repository into one of the configured [`COLLECTIONS_PATHS`](https://docs.ansible.com/ansible/latest/reference_appendices/config.html#collections-paths) and work on it there. If you want to develop new content for this collection or improve what is already here, clone the Git repository into one of the configured [`COLLECTIONS_PATHS`](https://docs.ansible.com/ansible/latest/reference_appendices/config.html#collections-paths) and work on it there.
See [Contributing to kubernetes.core](https://github.com/ansible-collections/kubernetes.core/blob/main/CONTRIBUTING.md). See [Contributing to kubernetes.core](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/CONTRIBUTING.md).
Join the Ansible community: Join the Ansible community:
@@ -249,8 +245,6 @@ This project follows the [Ansible Code of Conduct](https://docs.ansible.com/ansi
## Support ## Support
This collection is maintained by Red Hat Ansible Cloud Content.
As Red Hat Ansible Certified Content, this collection is entitled to support through the Ansible Automation Platform (AAP) using the **Create issue** button on the top right corner. If a support case cannot be opened with Red Hat and the collection has been obtained either from Galaxy or GitHub, there may be community help available on the [Ansible Forum](https://forum.ansible.com/). As Red Hat Ansible Certified Content, this collection is entitled to support through the Ansible Automation Platform (AAP) using the **Create issue** button on the top right corner. If a support case cannot be opened with Red Hat and the collection has been obtained either from Galaxy or GitHub, there may be community help available on the [Ansible Forum](https://forum.ansible.com/).
> **Note:** The `stable-4` branch (all `4.x.y` releases) is no longer supported. No backports or releases are performed on `stable-4`. > **Note:** The `stable-4` branch (all `4.x.y` releases) is no longer supported. No backports or releases are performed on `stable-4`.
@@ -259,7 +253,7 @@ We announce releases and important changes through Ansible's [The Bullhorn newsl
We take part in the global quarterly [Ansible Contributor Summit](https://github.com/ansible/community/wiki/Contributor-Summit). Track The Bullhorn and join when announced. We take part in the global quarterly [Ansible Contributor Summit](https://github.com/ansible/community/wiki/Contributor-Summit). Track The Bullhorn and join when announced.
For the latest supported versions, see [Release Notes and Roadmap](https://github.com/ansible-collections/kubernetes.core/blob/main/README.md#release-notes-and-roadmap). For the latest supported versions, see [Release Notes and Roadmap](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/README.md#release-notes-and-roadmap).
Report bugs, request features, or ask questions by opening an issue in the [GitHub repository](https://github.com/ansible-collections/kubernetes.core/). Report bugs, request features, or ask questions by opening an issue in the [GitHub repository](https://github.com/ansible-collections/kubernetes.core/).
@@ -271,7 +265,7 @@ Releases are automatically built and pushed to Ansible Galaxy for any new tag. B
1. The `version` in `galaxy.yml` 1. The `version` in `galaxy.yml`
2. This README's `requirements.yml` example 2. This README's `requirements.yml` example
3. The `VERSION` in `Makefile` 3. The `VERSION` in `Makefile`
2. Update the [CHANGELOG](CHANGELOG.rst): 2. Update the CHANGELOG:
1. Make sure you have [`antsibull-changelog`](https://pypi.org/project/antsibull-changelog/) installed. 1. Make sure you have [`antsibull-changelog`](https://pypi.org/project/antsibull-changelog/) installed.
2. Make sure there are fragments for all known changes in `changelogs/fragments`. 2. Make sure there are fragments for all known changes in `changelogs/fragments`.
3. Run `antsibull-changelog release`. 3. Run `antsibull-changelog release`.
@@ -286,9 +280,9 @@ The process for [uploading a supported release to Automation Hub](https://docs.r
* [Using Ansible collections](https://docs.ansible.com/ansible/devel/user_guide/collections_using.html) * [Using Ansible collections](https://docs.ansible.com/ansible/devel/user_guide/collections_using.html)
* [Ansible communication guide](https://docs.ansible.com/ansible/devel/community/communication.html) * [Ansible communication guide](https://docs.ansible.com/ansible/devel/community/communication.html)
* [Continuous integration (CI) overview](https://github.com/ansible-collections/kubernetes.core/blob/main/CI.md) * [Continuous integration (CI) overview](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/CI.md)
* [SonarCloud integration](https://github.com/ansible-collections/kubernetes.core/blob/main/SONARCLOUD.md) * [SonarCloud integration](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/SONARCLOUD.md)
* [Ansible Turbo mode (tech preview)](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/ansible_turbo_mode.rst) * [Ansible Turbo mode (tech preview)](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/docs/ansible_turbo_mode.rst)
### Code of conduct ### Code of conduct
@@ -300,4 +294,4 @@ If you encounter abusive behavior, please refer to the [policy violations](https
GNU General Public License v3.0 or later GNU General Public License v3.0 or later
See [LICENSE](https://github.com/ansible-collections/kubernetes.core/blob/main/LICENSE) to see the full text. See [LICENSE](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/LICENSE) to see the full text.
+1 -1
View File
@@ -21,7 +21,7 @@ Workflow files:
Scanner configuration lives in [sonar-project.properties](sonar-project.properties). Scanner configuration lives in [sonar-project.properties](sonar-project.properties).
The **coverage** job (in **`all_green`**) uses **`ansible-test`** (`units --coverage`, then **`coverage combine`** / **`coverage xml`**), then writes **`coverage.xml`** with workspace paths normalized for Sonar. **`pytest-cov`** is listed in **`tests/unit/requirements.txt`** for parity and any direct pytest runs; **`ansible-test`** still owns the coverage data used in CI. The **coverage** job (in **`all_green`**) uses **`ansible-test`** (`units --coverage`, then **`coverage combine`** / **`coverage xml`**) with **ansible-core `stable-2.18`** on **`stable-5`**, then writes **`coverage.xml`** with workspace paths normalized for Sonar. **`pytest-cov`** is listed in **`tests/unit/requirements.txt`** for parity and any direct pytest runs; **`ansible-test`** still owns the coverage data used in CI.
**`sonarcloud.yml`** declares a required secret **`ANSIBLE_COLLECTIONS_ORG_SONAR_TOKEN_CICD_BOT`** and **`permissions: contents: read`**, **`pull-requests: read`**. **`sonarcloud.yml`** declares a required secret **`ANSIBLE_COLLECTIONS_ORG_SONAR_TOKEN_CICD_BOT`** and **`permissions: contents: read`**, **`pull-requests: read`**.
+12 -355
View File
@@ -1027,13 +1027,14 @@ releases:
changes: changes:
bugfixes: bugfixes:
- module_utils/k8s/service - fix issue when trying to delete resource using - 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). `delete_options` and `check_mode=true` (https://github.com/ansible-collections/kubernetes.core/issues/892).
minor_changes: minor_changes:
- 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 - action/k8s_info - update templating mechanism with changes from ``ansible-core
2.19`` (https://github.com/ansible-collections/kubernetes.core/pull/888). 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 ``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 support for ``insecure_skip_tls_verify`` option to helm and ``helm_repository``
(https://github.com/ansible-collections/kubernetes.core/issues/694).
- kubernetes.core - Bump version of ``ansible-lint`` to ``25.1.2`` (https://github.com/ansible-collections/kubernetes.core/pull/919).
release_summary: This release includes minor changes, bug fixes and also bumps release_summary: This release includes minor changes, bug fixes and also bumps
``ansible-lint`` version to ``25.1.2``. ``ansible-lint`` version to ``25.1.2``.
fragments: fragments:
@@ -1062,7 +1063,7 @@ releases:
changes: changes:
bugfixes: bugfixes:
- Remove ``ansible.module_utils.six`` imports to avoid warnings (https://github.com/ansible-collections/kubernetes.core/pull/998). - Remove ``ansible.module_utils.six`` imports to avoid warnings (https://github.com/ansible-collections/kubernetes.core/pull/998).
- Update the ``k8s_cp`` module to also work for init containers (https://github.com/ansible-collections/kubernetes.core/pull/971). - Update the `k8s_cp` module to also work for init containers (https://github.com/ansible-collections/kubernetes.core/pull/971).
- module_utils/k8s/service - hide fields first before creating diffs (https://github.com/ansible-collections/kubernetes.core/pull/915). - module_utils/k8s/service - hide fields first before creating diffs (https://github.com/ansible-collections/kubernetes.core/pull/915).
release_summary: This release includes bugfixes for k8s service field handling, release_summary: This release includes bugfixes for k8s service field handling,
k8s_cp init containers support, and removes deprecated ansible.module_utils.six k8s_cp init containers support, and removes deprecated ansible.module_utils.six
@@ -1096,14 +1097,13 @@ releases:
be removed in a release after 2027-01-08. Use ``status.release_values`` instead be removed in a release after 2027-01-08. Use ``status.release_values`` instead
(https://github.com/ansible-collections/kubernetes.core/pull/1056). (https://github.com/ansible-collections/kubernetes.core/pull/1056).
minor_changes: minor_changes:
- helm - Add ``release_values`` key to ``status`` return value that can be accessed - helm - Add ``release_values`` key to ``status`` return value that can be
using Jinja2 dot notation (https://github.com/ansible-collections/kubernetes.core/pull/1056). accessed using Jinja2 dot notation (https://github.com/ansible-collections/kubernetes.core/pull/1056).
- helm_info - Add ``release_values`` key to ``status`` return value that can - helm_info - Add ``release_values`` key to ``status`` return value that can
be accessed using Jinja2 dot notation (https://github.com/ansible-collections/kubernetes.core/pull/1056). be accessed using Jinja2 dot notation (https://github.com/ansible-collections/kubernetes.core/pull/1056).
release_summary: This release includes bugfixes such as replacing the passing release_summary: This release includes bugfixes such as replacing the passing of ``warnings`` to ``exit_json``
of ``warnings`` to ``exit_json`` with ``AnsibleModule.warn`` as well as a with ``AnsibleModule.warn`` as well as a security update for selectively redacting sensitive information
security update for selectively redacting sensitive information from kubeconfig, from kubeconfig, and adds a new ``release_values`` key to the ``status`` return value.
and adds a new ``release_values`` key to the ``status`` return value.
security_fixes: security_fixes:
- Selectively redact sensitive info from kubeconfig instead of applying blanket - Selectively redact sensitive info from kubeconfig instead of applying blanket
``no_log=True`` (https://github.com/ansible-collections/kubernetes.core/pull/1014). ``no_log=True`` (https://github.com/ansible-collections/kubernetes.core/pull/1014).
@@ -1140,349 +1140,6 @@ releases:
5.4.4: 5.4.4:
changes: changes:
bugfixes: bugfixes:
- meta - Update ``requires_ansible`` in ``runtime.yml`` and README to ``>=2.16.0`` - meta - Update ``requires_ansible`` in ``runtime.yml`` and README to ``>=2.16.0`` to match the actual minimum supported ``ansible-core`` version (https://github.com/ansible-collections/kubernetes.core/pull/1193).
to match the actual minimum supported ``ansible-core`` version (https://github.com/ansible-collections/kubernetes.core/pull/1193). release_summary: This release corrects the documented and enforced minimum ``ansible-core`` version to ``>=2.16.0``.
release_summary: This release corrects the documented and enforced minimum ``ansible-core``
version to ``>=2.16.0``.
release_date: '2026-07-09' release_date: '2026-07-09'
5.5.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_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).
- 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_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).
- 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).
release_summary: This minor release deprecates Ansible Turbo mode (``ENABLE_TURBO_MODE``),
the ``status.values`` return value of the ``helm`` and ``helm_info`` modules,
the ``wait_timeout`` parameter of the ``helm`` module, the ``return_code``
return value of the ``k8s_exec`` module, and the ``merge_type=json`` option
of the ``k8s_service`` module. It also includes bugfixes for ``helm_repository``
URL comparison and for empty template output handling in ``k8s_info``.
fragments:
- 1253-k8s-lookup-turbo-version-check.yml
- 20250108-fix-empty-template-output.yaml
- 20260723-remove-module-utils-six.yaml
- 20260908-helm-repository-trailing-slash.yaml
- 20260911-deprecate-status-values.yaml
- 20260911-update-deprecation-notices.yaml
- 5.5.0.yml
- deprecate-enable-turbo-mode.yml
- fix-ansible-lint-warnings.yaml
release_date: '2026-09-15'
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`` does 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 adds ``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'
6.2.0:
changes:
bugfixes:
- Remove ``ansible.module_utils.six`` imports to avoid warnings (https://github.com/ansible-collections/kubernetes.core/pull/998).
- Update the ``k8s_cp`` module to also work for init containers (https://github.com/ansible-collections/kubernetes.core/pull/971).
minor_changes:
- Add support of skip-schema-validation in ``helm`` module (https://github.com/ansible-collections/kubernetes.core/pull/995)
- kustomize - Add support of local environ (https://github.com/ansible-collections/kubernetes.core/pull/786).
release_summary: This release adds minor changes and bugfixes, including support
of skip-schema-validation in ``helm`` module and removing deprecated ``ansible.module_utils.six``
imports.
fragments:
- 20241030-support-of-evrion-for-kustomize-lookup-plugin.yaml
- 20250731-fix-k8s_cp-initcontainers.yaml
- 20250916-skip-schema-validation.yaml
- 20250922-remove-ansible-six-imports.yaml
- 6_2_0.yml
release_date: '2025-10-07'
6.3.0:
changes:
bugfixes:
- Add idempotency for ``helm_pull`` module (https://github.com/ansible-collections/kubernetes.core/pull/1055).
- Fixed a bug where setting ``K8S_AUTH_VERIFY_SSL=true`` (or any string value)
caused the value to be treated as a separate ``kubectl`` command argument.
(https://github.com/ansible-collections/kubernetes.core/pull/1049).
- Limit supported versions of Helm to <4.0.0 (https://github.com/ansible-collections/kubernetes.core/pull/1039).
- Replace passing ``warnings`` to ``exit_json`` with ``AnsibleModule.warn``
in the ``k8s_drain``, ``k8s_rollback.py`` and ``k8s_scale.py`` modules as
it deprecated in ``ansible-core>=2.19.0`` and will be removed in ``ansible-core>=2.23.0``
(https://github.com/ansible-collections/kubernetes.core/pull/1033).
- k8s - Fix return block from the module documentation (https://github.com/ansible-collections/kubernetes.core/pull/1056).
- meta - Add ``k8s_cluster_info``, ``k8s_json_patch`` and ``k8s_rollback`` to
k8s action group (https://github.com/ansible-collections/kubernetes.core/pull/992).
deprecated_features:
- helm - the ``status.values`` return value has been deprecated and will be
removed in a release after 2027-01-08. Use ``status.release_values`` instead
(https://github.com/ansible-collections/kubernetes.core/pull/1056).
- helm_info - the ``status.values`` return value has been deprecated and will
be removed in a release after 2027-01-08. Use ``status.release_values`` instead
(https://github.com/ansible-collections/kubernetes.core/pull/1056).
minor_changes:
- Remove deprecated import from ``ansible.module_utils._text`` (https://github.com/ansible-collections/kubernetes.core/pull/1053).
- helm - add ``release_values`` key to ``status`` return value that can be accessed
using Jinja2 dot notation (https://github.com/ansible-collections/kubernetes.core/pull/1056).
- helm_info - add ``release_values`` key to ``status`` return value that can
be accessed using Jinja2 dot notation (https://github.com/ansible-collections/kubernetes.core/pull/1056).
release_summary: This release includes bugfixes such as implementing idempotency
for the ``helm_pull`` module as well as a security update for selectively
redacting sensitive information from kubeconfig.
security_fixes:
- Selectively redact sensitive info from kubeconfig instead of applying blanket
``no_log=True`` (https://github.com/ansible-collections/kubernetes.core/pull/1014).
fragments:
- 1033-warnings-deprecations.yaml
- 20251002-fix-k8s-actiongroup.yaml
- 20251007-selective-kubeconfig-redaction.yaml
- 20251115-limit-versions-of-helm.yaml
- 20251220-fix-K8S_AUTH_VERIFY_SSL-in-kubectl-connecton-plugion.yaml
- 20251228-1053-remove-deprecated-import.yaml
- 20260107-add-idempodency-for-helm-pull.yaml
- 20260108-fix-sanity-failures.yml
- 6-3-0.yaml
release_date: '2026-02-03'
6.4.0:
changes:
bugfixes:
- Helm - Allow taking ownership of existing Kubernetes resources on the first
installation of a Helm release. Previously, the ``take_ownership`` parameter
was always disabled during the initial install, preventing resource adoption
(https://github.com/ansible-collections/kubernetes.core/pull/1034).
minor_changes:
- helm_info - Ensure compatibility with Helm v4 (https://github.com/ansible-collections/kubernetes.core/issues/1038).
- helm_plugin - Ensure compatibility with Helm v4 (https://github.com/ansible-collections/kubernetes.core/issues/1038).
- helm_plugin_info - Ensure compatibility with Helm v4 (https://github.com/ansible-collections/kubernetes.core/issues/1038).
- helm_pull - Ensure compatibility with Helm v4 (https://github.com/ansible-collections/kubernetes.core/issues/1038).
- helm_registry_auth - Ensure compatibility with Helm v4 (https://github.com/ansible-collections/kubernetes.core/issues/1038).
- helm_registry_auth - add new option plain_http to allow insecure http connection
when running ``helm registry login`` (https://github.com/ansible-collections/kubernetes.core/pull/1090).
- helm_repository - Ensure compatibility with Helm v4 (https://github.com/ansible-collections/kubernetes.core/issues/1038).
- k8s_drain - Add support for ``check_mode`` (https://github.com/ansible-collections/kubernetes.core/pull/1086).
- k8s_drain - Convert module warnings into informational displays when users
explicitly request the deletion of unmanaged pods, pods with local storage,
or those managed by a ``DaemonSet`` (https://github.com/ansible-collections/kubernetes.core/issues/1037).
release_summary: This release adds Helm v4 compatibility across the Helm modules
and improves ``k8s_drain`` with check mode. When you explicitly allow evicting
unmanaged pods, pods with local storage, or pods managed by a ``DaemonSet``,
those cases are reported as informational output instead of module warnings.
fragments:
- 20251224-take-ownership-helm-initialization.yaml
- 20260203-k8s_drain-warning-fixes.yaml
- 20260213-support-helm-v4-for-helm-plugin-modules.yaml
- release-6-4-0.yml
release_date: '2026-04-22'
6.5.0:
changes:
bugfixes:
- ee - added ``meta/execution-environment.yml`` to decouple ansible-builder
EE builds from the ``openshift-clients`` system dependency declared in ``bindep.txt``,
which is not available in standard UBI repositories and caused builds to fail
with ``No package matches 'openshift-clients'`` (https://github.com/ansible-collections/kubernetes.core/issues/1141).
- helm - use ``--server-side=false --force-replace`` instead of the deprecated/removed
``--force`` flag when ``force=true`` is used with Helm v4, preserving the
Helm v3 client-side replacement behaviour and avoiding the server-side apply
conflict (https://github.com/ansible-collections/kubernetes.core/pull/1164).
- helm - use the ``--rollback-on-failure`` flag instead of the deprecated/removed
``--atomic`` flag when ``atomic=true`` is used with Helm v4 (https://github.com/ansible-collections/kubernetes.core/pull/1144).
- helm_repository - correct handling of repository URLs with trailing slashes
(https://github.com/ansible-collections/kubernetes.core/pull/1121).
- k8s_drain - Fix logic for handling pods with local storage to correctly check
for empty_dir volumes in replicated pods and pods managed by DaemonSets (https://github.com/ansible-collections/kubernetes.core/pull/1095).
minor_changes:
- helm - add the ``server_side`` and ``force_conflicts`` options to control
Helm v4 server-side apply when installing or upgrading a release (https://github.com/ansible-collections/kubernetes.core/pull/1164).
- helm_plugin - add ``--keyring`` argument to allow changing the keyring default
location. The option is only accepted with ``state=present`` (the ``helm plugin
install`` subcommand), as that is the only implemented subcommand that supports
``--keyring`` (https://github.com/ansible-collections/kubernetes.core/pull/1150).
- helm_registry_auth - document that, as of Helm 4.2.1, registry success messages
such as ``Login Succeeded`` are printed to stdout instead of stderr (https://github.com/ansible-collections/kubernetes.core/pull/1147).
- kubeconfig - add ``remove`` value to the ``behavior`` option, allowing entries
to be deleted from the kubeconfig file by name (https://github.com/ansible-collections/kubernetes.core/pull/1123).
release_summary: This release implements minor changes and bug fixes such as
a new ``remove`` value to the ``behavior`` option of the ``kubeconfig`` module,
allowing entries to be deleted from the kubeconfig file by name, as well as
Helm v4 compatibility across the Helm modules.
fragments:
- 1123-kubeconfig-remove-behavior.yml
- 1173-security-check-workflow.yml
- 20260306-k8s_drain-delete-logic-fixes-for-daemonsets.yaml
- 20260506-improve_idempotency_for_helm_repository.yaml
- 20260611-helm-atomic-helm-v4.yml
- 20260612-helm-registry-output-stream.yml
- 20260620-add-plugin-keyring-option.yaml
- 20260629-helm-force-helm-v4.yml
- 6-5-0.yml
- fix-openshift-clients-ee-dependency.yaml
modules:
- description: Generate, update, and optionally write Kubernetes kubeconfig files
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'
@@ -1,3 +0,0 @@
---
bugfixes:
- helm - Remove `--plain-http` option from `helm diff upgrade`, as it is not supported by the helm-diff plugin (https://github.com/ansible-collections/kubernetes.core/pull/1232).
@@ -1,4 +0,0 @@
---
bugfixes:
- k8s, k8s_service - emit warnings through ``AnsibleModule.warn`` instead of putting them in the result dict that is unpacked into ``exit_json``/``fail_json``. Passing ``warnings`` that way is deprecated since ansible-core 2.19 and will be removed in 2.23, so every run that produced a warning (for example the "No meaningful diff was generated" hint, warnings returned by the Kubernetes API, or ``validate`` findings) also emitted a deprecation warning (https://github.com/ansible-collections/kubernetes.core/pull/1267).
- k8s - warnings raised while processing a multi-document manifest are now shown to the user. They were previously nested under ``result.results[*].warnings``, where ansible-core never picked them up, so they were silently dropped whenever more than one resource was processed (https://github.com/ansible-collections/kubernetes.core/pull/1267).
+2 -17
View File
@@ -12,20 +12,6 @@ Following document provides overview of Ansible Turbo mode in ``kubernetes.core`
:depth: 1 :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``,
Turbo mode is ignored and a warning is emitted; modules run without it.
Synopsis Synopsis
-------- --------
- A brief introduction about Ansible Turbo mode in ``kuberentes.core`` collection. - A brief introduction about Ansible Turbo mode in ``kuberentes.core`` collection.
@@ -34,9 +20,8 @@ Synopsis
Requirements Requirements
------------ ------------
The following requirements are needed on the host that executes this module. The following requirement is needed on the host that executes this module.
- ``ansible-core`` version lower than 2.19.
- The ``cloud.common`` collection (https://github.com/ansible-collections/cloud.common) - 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:: 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::
@@ -159,4 +144,4 @@ You may want to manually start the server. This can be done with the following c
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 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. You can use the ``--help`` argument to get a list of the optional parameters.
@@ -17,7 +17,7 @@ Requirements
To use the modules, you'll need the following: To use the modules, you'll need the following:
- Ansible 2.16.0 or latest installed - Ansible 2.9.17 or latest installed
- `Kubernetes Python client <https://pypi.org/project/kubernetes/>`_ installed on the host that will execute the modules. - `Kubernetes Python client <https://pypi.org/project/kubernetes/>`_ installed on the host that will execute the modules.
@@ -42,92 +42,6 @@ Basic authentication is also supported using the ``username`` and ``password`` o
To disable SSL certificate verification, set ``verify_ssl`` to false. 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 Reporting an issue
================== ==================
@@ -0,0 +1,88 @@
.. _ansible_collections.kubernetes.core.docsite.k8s_ansible_inventory:
*****************************************
Using Kubernetes dynamic inventory plugin
*****************************************
.. contents::
:local:
Kubernetes dynamic inventory plugin
===================================
The best way to interact with your Pods is to use the Kubernetes dynamic inventory plugin, which queries Kubernetes APIs using ``kubectl`` command line available on controller node and tells Ansible what Pods can be managed.
Requirements
------------
To use the Kubernetes dynamic inventory plugins, you must install `Kubernetes Python client <https://github.com/kubernetes-client/python>`_, `kubectl <https://github.com/kubernetes/kubectl>`_ on your control node (the host running Ansible).
.. code-block:: bash
$ pip install kubernetes
Please refer to Kubernetes official documentation for `installing kubectl <https://kubernetes.io/docs/tasks/tools/install-kubectl/>`_ on the given operating systems.
To use this Kubernetes dynamic inventory plugin, you need to enable it first by specifying the following in the ``ansible.cfg`` file:
.. code-block:: ini
[inventory]
enable_plugins = kubernetes.core.k8s
Then, create a file that ends in ``.k8s.yml`` or ``.k8s.yaml`` in your working directory.
The ``kubernetes.core.k8s`` inventory plugin takes in the same authentication information as any other Kubernetes modules.
Here's an example of a valid inventory file:
.. code-block:: yaml
plugin: kubernetes.core.k8s
Executing ``ansible-inventory --list -i <filename>.k8s.yml`` will create a list of Pods that are ready to be configured using Ansible.
You can also provide the namespace to gather information about specific pods from the given namespace. For example, to gather information about Pods under the ``test`` namespace you will specify the ``namespaces`` parameter:
.. code-block:: yaml
plugin: kubernetes.core.k8s
connections:
- namespaces:
- test
Using vaulted configuration files
=================================
Since the inventory configuration file contains Kubernetes related sensitive information in plain text, a security risk, you may want to
encrypt your entire inventory configuration file.
You can encrypt a valid inventory configuration file as follows:
.. code-block:: bash
$ ansible-vault encrypt <filename>.k8s.yml
New Vault password:
Confirm New Vault password:
Encryption successful
$ echo "MySuperSecretPassw0rd!" > /path/to/vault_password_file
And you can use this vaulted inventory configuration file using:
.. code-block:: bash
$ ansible-inventory -i <filename>.k8s.yml --list --vault-password-file=/path/to/vault_password_file
.. seealso::
`Kubernetes Python client - Issue Tracker <https://github.com/kubernetes-client/python/issues>`_
The issue tracker for Kubernetes Python client
`Kubectl installation <https://kubernetes.io/docs/tasks/tools/install-kubectl/>`_
Installation guide for installing Kubectl
:ref:`working_with_playbooks`
An introduction to playbooks
:ref:`playbooks_vault`
Using Vault in playbooks
+1
View File
@@ -13,5 +13,6 @@ To get started, please select one of the following topics.
:maxdepth: 1 :maxdepth: 1
kubernetes_scenarios/k8s_intro kubernetes_scenarios/k8s_intro
kubernetes_scenarios/k8s_inventory
kubernetes_scenarios/k8s_scenarios kubernetes_scenarios/k8s_scenarios
+3 -38
View File
@@ -25,7 +25,7 @@ Requirements
------------ ------------
The below requirements are needed on the host that executes this module. The below requirements are needed on the host that executes this module.
- helm >= 3.0.0 (https://github.com/helm/helm/releases) - helm (https://github.com/helm/helm/releases)
- yaml (https://pypi.org/project/PyYAML/) - yaml (https://pypi.org/project/PyYAML/)
@@ -268,7 +268,7 @@ Examples
Return Values Return Values
------------- -------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module: Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html .. raw:: html
@@ -410,40 +410,6 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
<br/> <br/>
</td> </td>
</tr> </tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>release_values</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.3.0</div>
</td>
<td>always</td>
<td>
<div>Dict of Values used to deploy.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>release_values</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.3.0</div>
</td>
<td>always</td>
<td>
<div>Dict of Values used to deploy.</div>
<br/>
</td>
</tr>
<tr> <tr>
<td class="elbow-placeholder">&nbsp;</td> <td class="elbow-placeholder">&nbsp;</td>
<td colspan="1"> <td colspan="1">
@@ -499,13 +465,12 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
<b>values</b> <b>values</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a> <a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small"> <div style="font-size: small">
<span style="color: purple">dictionary</span> <span style="color: purple">string</span>
</div> </div>
</td> </td>
<td>always</td> <td>always</td>
<td> <td>
<div>Dict of Values used to deploy</div> <div>Dict of Values used to deploy</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/> <br/>
</td> </td>
</tr> </tr>
+8 -210
View File
@@ -25,7 +25,7 @@ Requirements
------------ ------------
The below requirements are needed on the host that executes this module. The below requirements are needed on the host that executes this module.
- helm >= 3.0.0 (https://github.com/helm/helm/releases) - helm (https://github.com/helm/helm/releases)
- yaml (https://pypi.org/project/PyYAML/) - yaml (https://pypi.org/project/PyYAML/)
@@ -73,7 +73,6 @@ Parameters
</td> </td>
<td> <td>
<div>If set, the installation process deletes the installation on failure.</div> <div>If set, the installation process deletes the installation on failure.</div>
<div>With Helm v4 this is translated to the <code>--rollback-on-failure</code> flag, since <code>--atomic</code> was renamed; with Helm v3 the <code>--atomic</code> flag is used. The O(atomic) option works the same way regardless of the installed Helm version.</div>
</td> </td>
</tr> </tr>
<tr> <tr>
@@ -157,29 +156,6 @@ Parameters
<div>Chart version to install. If this is not specified, the latest version is installed.</div> <div>Chart version to install. If this is not specified, the latest version is installed.</div>
</td> </td>
</tr> </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>&nbsp;&larr;</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> <tr>
<td colspan="2"> <td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -278,30 +254,6 @@ Parameters
</td> </td>
<td> <td>
<div>Helm option to force reinstall, ignore on new install.</div> <div>Helm option to force reinstall, ignore on new install.</div>
<div>With Helm v4 this performs a client-side replacement. Helm v4 deprecated <code>--force</code> (split into <code>--force-replace</code> and <code>--force-conflicts</code>) and enables server-side apply by default, so for Helm v4 the module emits <code>--server-side=false --force-replace</code> to preserve the Helm v3 behaviour. With Helm v3 the <code>--force</code> flag is used. The O(force) option works the same way regardless of the installed Helm version.</div>
<div>Mutually exclusive with O(server_side) and O(force_conflicts).</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>force_conflicts</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.5.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 server-side apply is enabled (the Helm v4 default), force changes against conflicts instead of failing.</div>
<div>Maps to the <code>--force-conflicts</code> flag.</div>
<div>This option requires Helm v4, cannot be combined with O(server_side=false), and is mutually exclusive with O(force).</div>
</td> </td>
</tr> </tr>
<tr> <tr>
@@ -378,27 +330,6 @@ Parameters
<div style="font-size: small; color: darkgreen"><br/>aliases: kubeconfig_path</div> <div style="font-size: small; color: darkgreen"><br/>aliases: kubeconfig_path</div>
</td> </td>
</tr> </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> <tr>
<td colspan="2"> <td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -545,9 +476,7 @@ Parameters
</td> </td>
<td> <td>
<div>When upgrading package, reset the values to the ones built into the chart, apply the last release&#x27;s values and merge in any overrides from parameters O(release_values), O(values_files) or O(set_values).</div> <div>When upgrading package, reset the values to the ones built into the chart, apply the last release&#x27;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> 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>If O(reset_values) or O(reuse_values) is set to V(True), this is ignored.</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 &gt;= 3.9.12.</div> <div>This feature requires helm diff &gt;= 3.9.12.</div>
</td> </td>
</tr> </tr>
@@ -569,7 +498,6 @@ Parameters
</td> </td>
<td> <td>
<div>When upgrading package, reset the values to the ones built into the chart.</div> <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> </td>
</tr> </tr>
<tr> <tr>
@@ -589,33 +517,8 @@ Parameters
</ul> </ul>
</td> </td>
<td> <td>
<div>When upgrading package, specifies whether to reuse the last release&#x27;s values and merge in any overrides from parameters O(release_values), O(values_files) or O(set_values).</div> <div>When upgrading package, specifies wether to reuse the last release&#x27;s values and merge in any overrides from parameters <em>release_values</em>, <em>values_files</em> or <em>set_values</em>.</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>If <em>reset_values</em> is set to <code>True</code>, this is ignored.</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>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>server_side</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.5.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>auto</li>
<li>true</li>
<li>false</li>
</ul>
</td>
<td>
<div>Control Helm v4 server-side apply when installing or upgrading a release.</div>
<div>Maps to the <code>--server-side</code> flag, which accepts <code>true</code>, <code>false</code> or <code>auto</code>.</div>
<div>This option requires Helm v4 and is mutually exclusive with O(force).</div>
</td> </td>
</tr> </tr>
<tr> <tr>
@@ -698,48 +601,6 @@ Parameters
<div>Skip custom resource definitions when installing or upgrading.</div> <div>Skip custom resource definitions when installing or upgrading.</div>
</td> </td>
</tr> </tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>skip_schema_validation</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.2.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>Disables JSON schema validation for Chart and values.</div>
<div>This feature requires helm &gt;= 3.16.0</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>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> <tr>
<td colspan="2"> <td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -839,28 +700,6 @@ 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&gt;=3.7.0. Added in version 2.3.0.</div> <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&gt;=3.7.0. Added in version 2.3.0.</div>
</td> </td>
</tr> </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>&nbsp;&larr;</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 &gt;= 3.5.0</div>
</td>
</tr>
<tr> <tr>
<td colspan="2"> <td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -874,7 +713,7 @@ Parameters
</td> </td>
<td> <td>
<div>Timeout when wait option is enabled (helm2 is a number of seconds, helm3 is a duration).</div> <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 in version 7.0.0. Use O(timeout) instead.</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>
</td> </td>
</tr> </tr>
</table> </table>
@@ -971,12 +810,6 @@ Examples
chart_ref: "https://github.com/grafana/helm-charts/releases/download/grafana-5.6.0/grafana-5.6.0.tgz" chart_ref: "https://github.com/grafana/helm-charts/releases/download/grafana-5.6.0/grafana-5.6.0.tgz"
release_namespace: monitoring 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 # Using complex Values
- name: Deploy new-relic client chart - name: Deploy new-relic client chart
kubernetes.core.helm: kubernetes.core.helm:
@@ -985,7 +818,6 @@ Examples
release_namespace: default release_namespace: default
force: True force: True
wait: True wait: True
wait_for_jobs: True
replace: True replace: True
update_repo_cache: True update_repo_cache: True
disable_hook: True disable_hook: True
@@ -1005,37 +837,21 @@ Examples
enabled: True enabled: True
# Deploy latest version # 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 - name: Deploy latest version of Grafana chart using reuse_values
kubernetes.core.helm: kubernetes.core.helm:
name: test name: test
chart_ref: stable/grafana chart_ref: stable/grafana
release_namespace: monitoring release_namespace: monitoring
reuse_values: true reuse_values: true
reset_values: false
values: values:
replicas: 2 replicas: 2
version: 3e8ec0b2dffa40fb97d5342e4af887de95faa8c61a62480dd7f8aa03dffcf533 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 Return Values
------------- -------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module: Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html .. raw:: html
@@ -1141,23 +957,6 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
<br/> <br/>
</td> </td>
</tr> </tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>release_values</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.3.0</div>
</td>
<td>always</td>
<td>
<div>Dict of Values used to deploy.</div>
<br/>
</td>
</tr>
<tr> <tr>
<td class="elbow-placeholder">&nbsp;</td> <td class="elbow-placeholder">&nbsp;</td>
<td colspan="1"> <td colspan="1">
@@ -1213,13 +1012,12 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
<b>values</b> <b>values</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a> <a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small"> <div style="font-size: small">
<span style="color: purple">dictionary</span> <span style="color: purple">string</span>
</div> </div>
</td> </td>
<td>always</td> <td>always</td>
<td> <td>
<div>Dict of Values used to deploy.</div> <div>Dict of Values used to deploy</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/> <br/>
</td> </td>
</tr> </tr>
@@ -25,7 +25,7 @@ Requirements
------------ ------------
The below requirements are needed on the host that executes this module. The below requirements are needed on the host that executes this module.
- helm >= 3.0.0 (https://github.com/helm/helm/releases) - helm (https://github.com/helm/helm/releases)
Parameters Parameters
@@ -196,7 +196,7 @@ Examples
Return Values Return Values
------------- -------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module: Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html .. raw:: html
+2 -42
View File
@@ -25,7 +25,7 @@ Requirements
------------ ------------
The below requirements are needed on the host that executes this module. The below requirements are needed on the host that executes this module.
- helm >= 3.0.0 (https://github.com/helm/helm/releases) - helm (https://github.com/helm/helm/releases)
Parameters Parameters
@@ -120,24 +120,6 @@ Parameters
<div>Provide a URL for accessing the API. Can also be specified via <code>K8S_AUTH_HOST</code> environment variable.</div> <div>Provide a URL for accessing the API. Can also be specified via <code>K8S_AUTH_HOST</code> environment variable.</div>
</td> </td>
</tr> </tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>keyring</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.5.0</div>
</td>
<td>
</td>
<td>
<div>Location of public keys used for verification.</div>
<div>Only valid with <code>state=present</code>, which maps to the <code>helm plugin install</code> subcommand.</div>
<div>This option requires helm version &gt;= 4.0.0.</div>
</td>
</tr>
<tr> <tr>
<td colspan="1"> <td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -249,28 +231,6 @@ Parameters
<div style="font-size: small; color: darkgreen"><br/>aliases: verify_ssl</div> <div style="font-size: small; color: darkgreen"><br/>aliases: verify_ssl</div>
</td> </td>
</tr> </tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>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 6.4.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>no</li>
<li><div style="color: blue"><b>yes</b>&nbsp;&larr;</div></li>
</ul>
</td>
<td>
<div>Verify the plugin signature before installing.</div>
<div>This option requires helm version &gt;= 4.0.0</div>
<div>Used with <em>state=present</em>.</div>
</td>
</tr>
</table> </table>
<br/> <br/>
@@ -312,7 +272,7 @@ Examples
Return Values Return Values
------------- -------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module: Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html .. raw:: html
+1 -22
View File
@@ -27,7 +27,7 @@ Requirements
------------ ------------
The below requirements are needed on the host that executes this module. The below requirements are needed on the host that executes this module.
- helm >= 3.0.0 (https://github.com/helm/helm/releases) - helm >= 3.0, <4.0.0 (https://github.com/helm/helm/releases)
Parameters Parameters
@@ -215,27 +215,6 @@ Parameters
<div>Pass credentials to all domains.</div> <div>Pass credentials to all domains.</div>
</td> </td>
</tr> </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> <tr>
<td colspan="1"> <td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -25,7 +25,7 @@ Requirements
------------ ------------
The below requirements are needed on the host that executes this module. The below requirements are needed on the host that executes this module.
- helm (https://github.com/helm/helm/releases) >= 3.8.0 - helm (https://github.com/helm/helm/releases) >= 3.8.0, <4.0.0
Parameters Parameters
@@ -151,27 +151,6 @@ Parameters
<div style="font-size: small; color: darkgreen"><br/>aliases: repo_password</div> <div style="font-size: small; color: darkgreen"><br/>aliases: repo_password</div>
</td> </td>
</tr> </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.4.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 insecure HTTP connections for <code>helm registry login</code>.</div>
<div>Requires Helm &gt;= 3.18.0</div>
</td>
</tr>
<tr> <tr>
<td colspan="1"> <td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -289,9 +268,7 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
</td> </td>
<td>always</td> <td>always</td>
<td> <td>
<div>Full <code>helm</code> command stderr, in case you want to display it or examine the event log.</div> <div>Full <code>helm</code> command stderr, in case you want to display it or examine the event log. Please be note that helm binnary may print messages to stderr even if the command is successful.</div>
<div>Please note that the helm binary may print messages to stderr even if the command is successful.</div>
<div>On Helm versions earlier than 4.2.1, success messages such as <code>Login Succeeded</code> are printed here; as of Helm 4.2.1 they are printed to stdout (see <a href='https://github.com/helm/helm/pull/32056'>https://github.com/helm/helm/pull/32056</a>).</div>
<br/> <br/>
<div style="font-size: smaller"><b>Sample:</b></div> <div style="font-size: smaller"><b>Sample:</b></div>
<div style="font-size: smaller; color: blue; word-wrap: break-word; word-break: break-all;">Login Succeeded\n</div> <div style="font-size: smaller; color: blue; word-wrap: break-word; word-break: break-all;">Login Succeeded\n</div>
@@ -323,17 +300,14 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
</td> </td>
<td>always</td> <td>always</td>
<td> <td>
<div>Full <code>helm</code> command stdout, in case you want to display it or examine the event log.</div> <div>Full <code>helm</code> command stdout, in case you want to display it or examine the event log</div>
<div>As of Helm 4.2.1 success messages such as <code>Login Succeeded</code> are printed to stdout (see <a href='https://github.com/helm/helm/pull/32056'>https://github.com/helm/helm/pull/32056</a>). On earlier versions they are printed to stderr.</div>
<br/> <br/>
<div style="font-size: smaller"><b>Sample:</b></div>
<div style="font-size: smaller; color: blue; word-wrap: break-word; word-break: break-all;">Login Succeeded\n</div>
</td> </td>
</tr> </tr>
<tr> <tr>
<td colspan="1"> <td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div> <div class="ansibleOptionAnchor" id="return-"></div>
<b>stdout_lines</b> <b>stout_lines</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a> <a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small"> <div style="font-size: small">
<span style="color: purple">list</span> <span style="color: purple">list</span>
@@ -25,7 +25,7 @@ Requirements
------------ ------------
The below requirements are needed on the host that executes this module. The below requirements are needed on the host that executes this module.
- helm >= 3.0.0 (https://github.com/helm/helm/releases) - helm (https://github.com/helm/helm/releases)
- yaml (https://pypi.org/project/PyYAML/) - yaml (https://pypi.org/project/PyYAML/)
@@ -336,7 +336,7 @@ Examples
Return Values Return Values
------------- -------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module: Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html .. raw:: html
+1 -29
View File
@@ -20,13 +20,6 @@ Synopsis
Requirements
------------
The below requirements are needed on the host that executes this module.
- helm >= 3.0.0 (https://github.com/helm/helm/releases)
- yaml (https://pypi.org/project/PyYAML/)
Parameters Parameters
---------- ----------
@@ -201,27 +194,6 @@ Parameters
<div>If the directory already exists, it will be overwritten.</div> <div>If the directory already exists, it will be overwritten.</div>
</td> </td>
</tr> </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> <tr>
<td colspan="2"> <td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -437,7 +409,7 @@ Examples
Return Values Return Values
------------- -------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module: Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html .. raw:: html
@@ -416,7 +416,7 @@ Examples
Return Values Return Values
------------- -------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module: Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html .. raw:: html
+1 -21
View File
@@ -152,25 +152,6 @@ Parameters
<div>The name of a context found in the config file. Can also be specified via K8S_AUTH_CONTEXT environment variable.</div> <div>The name of a context found in the config file. Can also be specified via K8S_AUTH_CONTEXT environment variable.</div>
</td> </td>
</tr> </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> <tr>
<td colspan="2"> <td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -531,7 +512,6 @@ Notes
.. note:: .. note::
- the tar binary is required on the container when copying from local filesystem to pod. - 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. - 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. - 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.
@@ -591,7 +571,7 @@ Examples
Return Values Return Values
------------- -------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module: Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html .. raw:: html
+1 -1
View File
@@ -627,7 +627,7 @@ Examples
Return Values Return Values
------------- -------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module: Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html .. raw:: html
+2 -2
View File
@@ -481,7 +481,7 @@ Examples
Return Values Return Values
------------- -------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module: Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html .. raw:: html
@@ -535,7 +535,7 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
</td> </td>
<td></td> <td></td>
<td> <td>
<div>The command status code. This attribute is deprecated and will be removed in version 7.0.0. Use RV(result.rc) instead.</div> <div>The command status code. This attribute is deprecated and will be removed in a future release. Please use rc instead.</div>
<br/> <br/>
</td> </td>
</tr> </tr>
+1 -30
View File
@@ -280,29 +280,6 @@ Parameters
<div>List of label selectors to use to filter results</div> <div>List of label selectors to use to filter results</div>
</td> </td>
</tr> </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>&nbsp;&larr;</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> <tr>
<td colspan="2"> <td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -739,17 +716,11 @@ Examples
retries: 60 retries: 60
delay: 15 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 Return Values
------------- -------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module: Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html .. raw:: html
+372
View File
@@ -0,0 +1,372 @@
.. _kubernetes.core.k8s_inventory:
*******************
kubernetes.core.k8s
*******************
**Kubernetes (K8s) inventory source**
.. contents::
:local:
:depth: 1
DEPRECATED
----------
:Removed in collection release after
:Why: As discussed in https://github.com/ansible-collections/kubernetes.core/issues/31, we decided to
remove the k8s inventory plugin in release 6.0.0.
:Alternative: Use :ref:`kubernetes.core.k8s_info <kubernetes.core.k8s_info_module>` and :ref:`ansible.builtin.add_host <ansible.builtin.add_host_module>` instead.
Synopsis
--------
- Fetch containers and services for one or more clusters.
- Groups by cluster name, namespace, namespace_services, namespace_pods, and labels.
- Uses the kubectl connection plugin to access the Kubernetes cluster.
- Uses k8s.(yml|yaml) YAML configuration file to set parameter values.
Requirements
------------
The below requirements are needed on the local Ansible controller node that executes this inventory.
- python >= 3.9
- kubernetes >= 24.2.0
- PyYAML >= 3.11
Parameters
----------
.. raw:: html
<table border=0 cellpadding=0 class="documentation-table">
<tr>
<th colspan="2">Parameter</th>
<th>Choices/<font color="blue">Defaults</font></th>
<th>Configuration</th>
<th width="100%">Comments</th>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>connections</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Optional list of cluster connection settings. If no connections are provided, the default <em>~/.kube/config</em> and active context will be used, and objects will be returned for all namespaces the active user is authorized to access.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>api_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Token used to authenticate with the API. Can also be specified via K8S_AUTH_API_KEY environment variable.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>ca_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Path to a CA certificate used to authenticate with the API. Can also be specified via K8S_AUTH_SSL_CA_CERT environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: ssl_ca_cert</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Path to a certificate used to authenticate with the API. Can also be specified via K8S_AUTH_CERT_FILE environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: cert_file</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Path to a key file used to authenticate with the API. Can also be specified via K8S_AUTH_KEY_FILE environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: key_file</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>context</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<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 class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>host</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Provide a URL for accessing the API. Can also be specified via K8S_AUTH_HOST environment variable.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>kubeconfig</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Path to an existing Kubernetes config file. If not provided, and no other connection options are provided, the Kubernetes client will attempt to load the default configuration file from <em>~/.kube/config</em>. Can also be specified via K8S_AUTH_KUBECONFIG environment variable.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>name</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Optional name to assign to the cluster. If not provided, a name is constructed from the server and port.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>namespaces</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>List of namespaces. If not specified, will fetch all containers for all namespaces user is authorized to access.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>password</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Provide a password for authenticating with the API. Can also be specified via K8S_AUTH_PASSWORD environment variable.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>username</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Provide a username for authenticating with the API. Can also be specified via K8S_AUTH_USERNAME environment variable.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>validate_certs</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>no</li>
<li>yes</li>
</ul>
</td>
<td>
</td>
<td>
<div>Whether or not to verify the API server&#x27;s SSL certificates. Can also be specified via K8S_AUTH_VERIFY_SSL environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: verify_ssl</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>plugin</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
/ <span style="color: red">required</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>kubernetes.core.k8s</li>
<li>k8s</li>
<li>community.kubernetes.k8s</li>
</ul>
</td>
<td>
</td>
<td>
<div>token that ensures this is a source file for the &#x27;k8s&#x27; plugin.</div>
</td>
</tr>
</table>
<br/>
Examples
--------
.. code-block:: yaml
# File must be named k8s.yaml or k8s.yml
- name: Authenticate with token, and return all pods and services for all namespaces
plugin: kubernetes.core.k8s
connections:
- host: https://192.168.64.4:8443
api_key: xxxxxxxxxxxxxxxx
validate_certs: false
- name: Use default config (~/.kube/config) file and active context, and return objects for a specific namespace
plugin: kubernetes.core.k8s
connections:
- namespaces:
- testing
- name: Use a custom config file, and a specific context.
plugin: kubernetes.core.k8s
connections:
- kubeconfig: /path/to/config
context: 'awx/192-168-64-4:8443/developer'
Status
------
- This inventory will be removed in version 6.0.0. *[deprecated]*
- For more information see `DEPRECATED`_.
Authors
~~~~~~~
- Chris Houseknecht (@chouseknecht)
- Fabian von Feilitzsch (@fabianvf)
.. hint::
Configuration entries for each entry type have a low to high priority order. For example, a variable that is lower in the list will override a variable that is higher up.
+1 -20
View File
@@ -140,25 +140,6 @@ Parameters
<div>The name of a context found in the config file. Can also be specified via K8S_AUTH_CONTEXT environment variable.</div> <div>The name of a context found in the config file. Can also be specified via K8S_AUTH_CONTEXT environment variable.</div>
</td> </td>
</tr> </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> <tr>
<td colspan="2"> <td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -640,7 +621,7 @@ Examples
Return Values Return Values
------------- -------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module: Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html .. raw:: html
+1 -1
View File
@@ -612,7 +612,7 @@ Examples
Return Values Return Values
------------- -------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module: Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html .. raw:: html
+20 -133
View File
@@ -38,13 +38,13 @@ Parameters
<table border=0 cellpadding=0 class="documentation-table"> <table border=0 cellpadding=0 class="documentation-table">
<tr> <tr>
<th colspan="2">Parameter</th> <th colspan="1">Parameter</th>
<th>Choices/<font color="blue">Defaults</font></th> <th>Choices/<font color="blue">Defaults</font></th>
<th>Configuration</th> <th>Configuration</th>
<th width="100%">Comments</th> <th width="100%">Comments</th>
</tr> </tr>
<tr> <tr>
<td colspan="2"> <td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
<b>api_key</b> <b>api_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a> <a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -61,7 +61,7 @@ Parameters
</td> </td>
</tr> </tr>
<tr> <tr>
<td colspan="2"> <td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
<b>api_version</b> <b>api_version</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a> <a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -79,7 +79,7 @@ Parameters
</td> </td>
</tr> </tr>
<tr> <tr>
<td colspan="2"> <td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
<b>ca_cert</b> <b>ca_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a> <a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -97,7 +97,7 @@ Parameters
</td> </td>
</tr> </tr>
<tr> <tr>
<td colspan="2"> <td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_cert</b> <b>client_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a> <a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -115,7 +115,7 @@ Parameters
</td> </td>
</tr> </tr>
<tr> <tr>
<td colspan="2"> <td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_key</b> <b>client_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a> <a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -133,7 +133,7 @@ Parameters
</td> </td>
</tr> </tr>
<tr> <tr>
<td colspan="2"> <td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
<b>cluster_info</b> <b>cluster_info</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a> <a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -150,7 +150,7 @@ Parameters
</td> </td>
</tr> </tr>
<tr> <tr>
<td colspan="2"> <td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
<b>context</b> <b>context</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a> <a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -167,7 +167,7 @@ Parameters
</td> </td>
</tr> </tr>
<tr> <tr>
<td colspan="2"> <td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
<b>field_selector</b> <b>field_selector</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a> <a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -184,7 +184,7 @@ Parameters
</td> </td>
</tr> </tr>
<tr> <tr>
<td colspan="2"> <td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
<b>host</b> <b>host</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a> <a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -201,7 +201,7 @@ Parameters
</td> </td>
</tr> </tr>
<tr> <tr>
<td colspan="2"> <td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
<b>kind</b> <b>kind</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a> <a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -219,7 +219,7 @@ Parameters
</td> </td>
</tr> </tr>
<tr> <tr>
<td colspan="2"> <td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
<b>kubeconfig</b> <b>kubeconfig</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a> <a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -236,7 +236,7 @@ Parameters
</td> </td>
</tr> </tr>
<tr> <tr>
<td colspan="2"> <td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
<b>label_selector</b> <b>label_selector</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a> <a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -253,7 +253,7 @@ Parameters
</td> </td>
</tr> </tr>
<tr> <tr>
<td colspan="2"> <td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
<b>namespace</b> <b>namespace</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a> <a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -270,26 +270,7 @@ Parameters
</td> </td>
</tr> </tr>
<tr> <tr>
<td colspan="2"> <td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>no_proxy</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>The comma separated list of hosts/domains/IP/CIDR that shouldn&#x27;t go through proxy. Can also be specified via K8S_AUTH_NO_PROXY environment variable.</div>
<div>Please note that this module does not pick up typical proxy settings from the environment (e.g. NO_PROXY).</div>
<div>This feature requires kubernetes&gt;=19.15.0. When kubernetes library is less than 19.15.0, it fails even if no_proxy is set correctly.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
<b>password</b> <b>password</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a> <a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -306,101 +287,7 @@ Parameters
</td> </td>
</tr> </tr>
<tr> <tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>The URL of an HTTP proxy to use for the connection. Can also be specified via K8S_AUTH_PROXY environment variable.</div>
<div>Please note that this module does not pick up typical proxy settings from the environment (e.g. HTTP_PROXY).</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy_headers</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>The Header used for the HTTP proxy.</div>
<div>Documentation can be found here <a href='https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html?highlight=proxy_headers#urllib3.util.make_headers'>https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html?highlight=proxy_headers#urllib3.util.make_headers</a>.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1"> <td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>basic_auth</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Colon-separated username:password for basic authentication header.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_BASIC_AUTH environment.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy_basic_auth</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Colon-separated username:password for proxy basic authentication header.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_PROXY_BASIC_AUTH environment.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>user_agent</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>String representing the user-agent you want, such as foo/1.0.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_USER_AGENT environment.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
<b>resource_definition</b> <b>resource_definition</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a> <a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -417,7 +304,7 @@ Parameters
</td> </td>
</tr> </tr>
<tr> <tr>
<td colspan="2"> <td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
<b>resource_name</b> <b>resource_name</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a> <a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -434,7 +321,7 @@ Parameters
</td> </td>
</tr> </tr>
<tr> <tr>
<td colspan="2"> <td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
<b>src</b> <b>src</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a> <a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -452,7 +339,7 @@ Parameters
</td> </td>
</tr> </tr>
<tr> <tr>
<td colspan="2"> <td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
<b>username</b> <b>username</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a> <a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -469,7 +356,7 @@ Parameters
</td> </td>
</tr> </tr>
<tr> <tr>
<td colspan="2"> <td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
<b>validate_certs</b> <b>validate_certs</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a> <a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -545,7 +432,7 @@ Examples
Return Values Return Values
------------- -------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this lookup: Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this lookup:
.. raw:: html .. raw:: html
+24 -163
View File
@@ -813,7 +813,7 @@ Parameters
</ul> </ul>
</td> </td>
<td> <td>
<div>Determines if an object should be created, patched, or deleted. When set to <code>present</code>, an object will be created if it does not already exist, and an existing object will be patched if its attributes differ from those specified using <em>resource_definition</em> or <em>src</em>. If set to <code>absent</code>, an existing object will be deleted.</div> <div>Determines if an object should be created, patched, or deleted. When set to <code>present</code>, an object will be created, if it does not already exist. If set to <code>absent</code>, an existing object will be deleted. If set to <code>present</code>, an existing object will be patched, if its attributes differ from those specified using <em>resource_definition</em> or <em>src</em>.</div>
<div><code>patched</code> state is an existing resource that has a given patch applied. If the resource doesn&#x27;t exist, silently skip it (do not raise an error).</div> <div><code>patched</code> state is an existing resource that has a given patch applied. If the resource doesn&#x27;t exist, silently skip it (do not raise an error).</div>
</td> </td>
</tr> </tr>
@@ -1279,35 +1279,18 @@ Examples
Return Values Return Values
------------- -------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module: Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html .. raw:: html
<table border=0 cellpadding=0 class="documentation-table"> <table border=0 cellpadding=0 class="documentation-table">
<tr> <tr>
<th colspan="3">Key</th> <th colspan="2">Key</th>
<th>Returned</th> <th>Returned</th>
<th width="100%">Description</th> <th width="100%">Description</th>
</tr> </tr>
<tr> <tr>
<td colspan="3"> <td colspan="2">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>method</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>success</td>
<td>
<div>The method used to deploy the resource.</div>
<br/>
<div style="font-size: smaller"><b>Sample:</b></div>
<div style="font-size: smaller; color: blue; word-wrap: break-word; word-break: break-all;">create</div>
</td>
</tr>
<tr>
<td colspan="3">
<div class="ansibleOptionAnchor" id="return-"></div> <div class="ansibleOptionAnchor" id="return-"></div>
<b>result</b> <b>result</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a> <a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
@@ -1323,105 +1306,6 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
</tr> </tr>
<tr> <tr>
<td class="elbow-placeholder">&nbsp;</td> <td class="elbow-placeholder">&nbsp;</td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>api_version</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>when O(resource_definition) or O(src) contains a single object.</td>
<td>
<div>The versioned schema of this representation of an object.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>duration</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">integer</span>
</div>
</td>
<td>when <code>wait</code> is true</td>
<td>
<div>elapsed time of task in seconds</div>
<br/>
<div style="font-size: smaller"><b>Sample:</b></div>
<div style="font-size: smaller; color: blue; word-wrap: break-word; word-break: break-all;">48</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>error</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">complex</span>
</div>
</td>
<td>error</td>
<td>
<div>error while trying to create/delete the object.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>kind</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>when O(resource_definition) or O(src) contains a single object.</td>
<td>
<div>Represents the REST resource this object represents.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>metadata</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">complex</span>
</div>
</td>
<td>when O(resource_definition) or O(src) contains a single object.</td>
<td>
<div>Standard object metadata. Includes name, namespace, annotations, labels, etc.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>results</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">complex</span>
</div>
</td>
<td>when O(resource_definition) or O(src) contains a list of objects.</td>
<td>
<div>An array of created, patched, or otherwise present objects.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1"> <td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div> <div class="ansibleOptionAnchor" id="return-"></div>
<b>api_version</b> <b>api_version</b>
@@ -1430,7 +1314,7 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
<span style="color: purple">string</span> <span style="color: purple">string</span>
</div> </div>
</td> </td>
<td>when O(resource_definition) or O(src) contains a single object.</td> <td>success</td>
<td> <td>
<div>The versioned schema of this representation of an object.</div> <div>The versioned schema of this representation of an object.</div>
<br/> <br/>
@@ -1438,7 +1322,6 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
</tr> </tr>
<tr> <tr>
<td class="elbow-placeholder">&nbsp;</td> <td class="elbow-placeholder">&nbsp;</td>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1"> <td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div> <div class="ansibleOptionAnchor" id="return-"></div>
<b>duration</b> <b>duration</b>
@@ -1457,7 +1340,6 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
</tr> </tr>
<tr> <tr>
<td class="elbow-placeholder">&nbsp;</td> <td class="elbow-placeholder">&nbsp;</td>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1"> <td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div> <div class="ansibleOptionAnchor" id="return-"></div>
<b>error</b> <b>error</b>
@@ -1474,6 +1356,21 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
</tr> </tr>
<tr> <tr>
<td class="elbow-placeholder">&nbsp;</td> <td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>items</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
</div>
</td>
<td>when resource_definition or src contains list of objects</td>
<td>
<div>Returned only when multiple yaml documents are passed to src or resource_definition</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td> <td class="elbow-placeholder">&nbsp;</td>
<td colspan="1"> <td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div> <div class="ansibleOptionAnchor" id="return-"></div>
@@ -1483,7 +1380,7 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
<span style="color: purple">string</span> <span style="color: purple">string</span>
</div> </div>
</td> </td>
<td>when O(resource_definition) or O(src) contains a single object.</td> <td>success</td>
<td> <td>
<div>Represents the REST resource this object represents.</div> <div>Represents the REST resource this object represents.</div>
<br/> <br/>
@@ -1491,7 +1388,6 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
</tr> </tr>
<tr> <tr>
<td class="elbow-placeholder">&nbsp;</td> <td class="elbow-placeholder">&nbsp;</td>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1"> <td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div> <div class="ansibleOptionAnchor" id="return-"></div>
<b>metadata</b> <b>metadata</b>
@@ -1500,7 +1396,7 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
<span style="color: purple">complex</span> <span style="color: purple">complex</span>
</div> </div>
</td> </td>
<td>when O(resource_definition) or O(src) contains a single object.</td> <td>success</td>
<td> <td>
<div>Standard object metadata. Includes name, namespace, annotations, labels, etc.</div> <div>Standard object metadata. Includes name, namespace, annotations, labels, etc.</div>
<br/> <br/>
@@ -1508,7 +1404,6 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
</tr> </tr>
<tr> <tr>
<td class="elbow-placeholder">&nbsp;</td> <td class="elbow-placeholder">&nbsp;</td>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1"> <td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div> <div class="ansibleOptionAnchor" id="return-"></div>
<b>spec</b> <b>spec</b>
@@ -1517,7 +1412,7 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
<span style="color: purple">complex</span> <span style="color: purple">complex</span>
</div> </div>
</td> </td>
<td>when O(resource_definition) or O(src) contains a single object.</td> <td>success</td>
<td> <td>
<div>Specific attributes of the object. Will vary based on the <em>api_version</em> and <em>kind</em>.</div> <div>Specific attributes of the object. Will vary based on the <em>api_version</em> and <em>kind</em>.</div>
<br/> <br/>
@@ -1525,7 +1420,6 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
</tr> </tr>
<tr> <tr>
<td class="elbow-placeholder">&nbsp;</td> <td class="elbow-placeholder">&nbsp;</td>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1"> <td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div> <div class="ansibleOptionAnchor" id="return-"></div>
<b>status</b> <b>status</b>
@@ -1534,40 +1428,7 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
<span style="color: purple">complex</span> <span style="color: purple">complex</span>
</div> </div>
</td> </td>
<td>when O(resource_definition) or O(src) contains a single object.</td> <td>success</td>
<td>
<div>Current status details for the object.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>spec</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">complex</span>
</div>
</td>
<td>when O(resource_definition) or O(src) contains a single object.</td>
<td>
<div>Specific attributes of the object. Will vary based on the <em>api_version</em> and <em>kind</em>.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>status</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">complex</span>
</div>
</td>
<td>when O(resource_definition) or O(src) contains a single object.</td>
<td> <td>
<div>Current status details for the object.</div> <div>Current status details for the object.</div>
<br/> <br/>
+1 -1
View File
@@ -503,7 +503,7 @@ Examples
Return Values Return Values
------------- -------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module: Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html .. raw:: html
+1 -1
View File
@@ -686,7 +686,7 @@ Examples
Return Values Return Values
------------- -------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module: Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html .. raw:: html
+2 -3
View File
@@ -247,7 +247,6 @@ 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>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>If more than one <code>merge_type</code> is given, the merge_types will be tried in order</div>
<div>This defaults to <code>[&#x27;strategic-merge&#x27;, &#x27;merge&#x27;]</code>, which is ideal for using the same parameters on resource kinds that combine Custom Resources and built-in resources.</div> <div>This defaults to <code>[&#x27;strategic-merge&#x27;, &#x27;merge&#x27;]</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> </td>
</tr> </tr>
<tr> <tr>
@@ -509,7 +508,7 @@ Parameters
</ul> </ul>
</td> </td>
<td> <td>
<div>Determines if an object should be created, patched, or deleted. When set to <code>present</code>, an object will be created if it does not already exist, and an existing object will be patched if its attributes differ from those specified using <em>resource_definition</em> or <em>src</em>. If set to <code>absent</code>, an existing object will be deleted.</div> <div>Determines if an object should be created, patched, or deleted. When set to <code>present</code>, an object will be created, if it does not already exist. If set to <code>absent</code>, an existing object will be deleted. If set to <code>present</code>, an existing object will be patched, if its attributes differ from those specified using <em>resource_definition</em> or <em>src</em>.</div>
</td> </td>
</tr> </tr>
<tr> <tr>
@@ -615,7 +614,7 @@ Examples
Return Values Return Values
------------- -------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module: Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html .. raw:: html
+1 -1
View File
@@ -541,7 +541,7 @@ Examples
Return Values Return Values
------------- -------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module: Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html .. raw:: html
-863
View File
@@ -1,863 +0,0 @@
.. _kubernetes.core.kubeconfig_module:
**************************
kubernetes.core.kubeconfig
**************************
**Generate, update, and optionally write Kubernetes kubeconfig files**
Version added: 6.5.0
.. contents::
:local:
:depth: 1
Synopsis
--------
- Build, update, and manage Kubernetes kubeconfig files using structured input.
- Supports loading an existing kubeconfig file and merging clusters, users, and contexts.
- Can optionally write the resulting kubeconfig to a destination path.
- Ensures idempotent behavior by only updating files when changes occur.
Requirements
------------
The below requirements are needed on the host that executes this module.
- PyYAML >= 5.1
Parameters
----------
.. raw:: html
<table border=0 cellpadding=0 class="documentation-table">
<tr>
<th colspan="3">Parameter</th>
<th>Choices/<font color="blue">Defaults</font></th>
<th width="100%">Comments</th>
</tr>
<tr>
<td colspan="3">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>clusters</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=dictionary</span>
</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">[]</div>
</td>
<td>
<div>List of cluster definitions to merge into the kubeconfig.</div>
<div>Each cluster is identified by its <code>name</code>.</div>
<div>When <code>name</code> matches an existing cluster, the default <code>behavior</code> is V(merge).</div>
<div>See the <code>behavior</code> suboption for V(replace), V(keep), and V(remove).</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>behavior</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>merge</b>&nbsp;&larr;</div></li>
<li>replace</li>
<li>keep</li>
<li>remove</li>
</ul>
</td>
<td>
<div>How to handle merging if a cluster with this name already exists.</div>
<div><code>merge</code> - Update only the specified fields, preserve others (default).</div>
<div><code>replace</code> - Replace the entire cluster definition.</div>
<div><code>keep</code> - Keep existing cluster, skip this entry.</div>
<div><code>remove</code> - Remove the cluster entry entirely. Silently skipped if the entry does not exist.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>cluster</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
</td>
<td>
</td>
<td>
<div>Cluster configuration details.</div>
<div>Not required when <code>behavior</code> is V(remove).</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>certificate-authority</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to a CA certificate file for validating the API server certificate.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>certificate-authority-data</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Base64 encoded CA certificate data.</div>
<div>Use this instead of <code>certificate-authority</code> for embedded certificates.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<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>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>no</li>
<li>yes</li>
</ul>
</td>
<td>
<div>If true, the server&#x27;s certificate will not be validated.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy-url</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Optional proxy URL for cluster connections.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>server</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
/ <span style="color: red">required</span>
</div>
</td>
<td>
</td>
<td>
<div>Kubernetes API server URL (e.g., <code>https://k8s.example.com:6443</code>).</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>tls-server-name</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Server name to use for server certificate validation.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>name</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
/ <span style="color: red">required</span>
</div>
</td>
<td>
</td>
<td>
<div>Unique name identifier for the cluster.</div>
</td>
</tr>
<tr>
<td colspan="3">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>contexts</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=dictionary</span>
</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">[]</div>
</td>
<td>
<div>List of context definitions linking users and clusters.</div>
<div>Each context is identified by its <code>name</code>.</div>
<div>When <code>name</code> matches an existing context, the default <code>behavior</code> is V(merge).</div>
<div>See the <code>behavior</code> suboption for V(replace), V(keep), and V(remove).</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>behavior</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>merge</b>&nbsp;&larr;</div></li>
<li>replace</li>
<li>keep</li>
<li>remove</li>
</ul>
</td>
<td>
<div>How to handle merging if a context with this name already exists.</div>
<div><code>merge</code> - Update only the specified fields, preserve others (default).</div>
<div><code>replace</code> - Replace the entire context definition.</div>
<div><code>keep</code> - Keep existing context, skip this entry.</div>
<div><code>remove</code> - Remove the context entry entirely. Silently skipped if the entry does not exist.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>context</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
</td>
<td>
</td>
<td>
<div>Context configuration linking cluster and user.</div>
<div>Not required when <code>behavior</code> is V(remove).</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>cluster</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
/ <span style="color: red">required</span>
</div>
</td>
<td>
</td>
<td>
<div>Name of the cluster to use (must match a cluster name in O(clusters)).</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>namespace</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Default namespace to use for this context.</div>
<div>If not specified, defaults to <code>default</code>.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>user</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
/ <span style="color: red">required</span>
</div>
</td>
<td>
</td>
<td>
<div>Name of the user to authenticate as (must match a user name in O(users)).</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>name</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
/ <span style="color: red">required</span>
</div>
</td>
<td>
</td>
<td>
<div>Unique name identifier for the context.</div>
</td>
</tr>
<tr>
<td colspan="3">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>current_context</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Name of the context to set as current/active.</div>
<div>This context will be used by default when using kubectl.</div>
<div>Must match one of the context names defined in O(contexts).</div>
</td>
</tr>
<tr>
<td colspan="3">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>dest</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Destination path where the final kubeconfig should be written.</div>
<div>If not specified, the kubeconfig will be saved to O(path).</div>
<div>Allows copying and modifying a kubeconfig to a new location.</div>
</td>
</tr>
<tr>
<td colspan="3">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>path</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
/ <span style="color: red">required</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to an existing kubeconfig file to load and merge from.</div>
<div>If the file does not exist, a new kubeconfig will be created.</div>
<div>This becomes the default destination if O(dest) is not specified.</div>
</td>
</tr>
<tr>
<td colspan="3">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>preferences</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">{}</div>
</td>
<td>
<div>Kubeconfig preferences.</div>
<div>Used for client-side settings like color output, default editor, etc.</div>
</td>
</tr>
<tr>
<td colspan="3">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>users</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=dictionary</span>
</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">[]</div>
</td>
<td>
<div>List of user authentication configurations.</div>
<div>Each user is identified by its <code>name</code>.</div>
<div>When <code>name</code> matches an existing user, the default <code>behavior</code> is V(merge).</div>
<div>See the <code>behavior</code> suboption for V(replace), V(keep), and V(remove).</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>behavior</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>merge</b>&nbsp;&larr;</div></li>
<li>replace</li>
<li>keep</li>
<li>remove</li>
</ul>
</td>
<td>
<div>How to handle merging if a user with this name already exists.</div>
<div><code>merge</code> - Update only the specified fields, preserve others (default).</div>
<div><code>replace</code> - Replace the entire user definition.</div>
<div><code>keep</code> - Keep existing user, skip this entry.</div>
<div><code>remove</code> - Remove the user entry entirely. Silently skipped if the entry does not exist.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>name</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
/ <span style="color: red">required</span>
</div>
</td>
<td>
</td>
<td>
<div>Unique name identifier for the user.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>user</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
</td>
<td>
</td>
<td>
<div>User authentication configuration.</div>
<div>Not required when <code>behavior</code> is V(remove).</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>auth-provider</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
</td>
<td>
</td>
<td>
<div>Authentication provider configuration (e.g., for GCP, Azure).</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client-certificate</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to client certificate file.</div>
<div>Used for certificate-based authentication.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client-certificate-data</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Base64 encoded client certificate.</div>
<div>Use instead of <code>client-certificate</code> for embedded certificates.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client-key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to client private key file.</div>
<div>Must be provided with <code>client-certificate</code>.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client-key-data</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Base64 encoded client private key.</div>
<div>Use instead of <code>client-key</code> for embedded keys.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>exec</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
</td>
<td>
</td>
<td>
<div>Exec-based credential plugin configuration.</div>
<div>Used for external authentication providers.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>password</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Password for basic authentication.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>token</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Bearer token for authentication.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>username</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Username for basic authentication.</div>
</td>
</tr>
</table>
<br/>
Notes
-----
.. note::
- Input data is merged by resource name (cluster, user, context).
- Updates under O(clusters), O(users), and O(contexts) are matched by ``name`` against the kubeconfig loaded from O(path).
- For an existing ``name``, each entry's ``behavior`` suboption controls the update.
- The default is V(merge), which merges nested ``cluster``, ``user``, and ``context`` data so unspecified keys are preserved.
- With V(replace), the previous entry for that name is dropped and only the new definition is used.
- With V(keep), the existing entry is left unchanged.
- With V(remove), the existing entry is deleted from the kubeconfig entirely. If no entry with that name exists, the operation is silently skipped.
- This can be used to move kubeconfig files to a different location with different content.
- This module does not validate cluster connectivity or authentication.
- The module supports ``check_mode`` and will not write files when enabled.
- The structure follows standard Kubernetes kubeconfig format as defined in the Kubernetes documentation.
- Tokens and sensitive data should be protected using ansible-vault or environment variables.
See Also
--------
.. seealso::
`Kubernetes kubeconfig documentation <https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/>`_
Official Kubernetes documentation for kubeconfig files
`kubectl config documentation <https://kubernetes.io/docs/reference/kubectl/generated/kubectl_config/>`_
kubectl commands for working with kubeconfig files
Examples
--------
.. code-block:: yaml
# Create a new kubeconfig file with a single cluster
- name: Create basic kubeconfig
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
clusters:
- name: production-cluster
cluster:
server: https://prod.k8s.example.com:6443
certificate-authority-data: LS0tLS1CRUdJTi...
users:
- name: admin-user
user:
token: eyJhbGciOiJSUzI1NiIsImtpZCI6IiJ9...
contexts:
- name: prod-admin
context:
cluster: production-cluster
user: admin-user
namespace: production
current_context: prod-admin
- name: Add a second cluster to an existing kubeconfig without touching other entries
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
clusters:
- name: staging-cluster
cluster:
server: https://staging.k8s.example.com:6443
insecure-skip-tls-verify: true
users:
- name: staging-user
user:
client-certificate: /path/to/staging.crt
client-key: /path/to/staging.key
contexts:
- name: staging-admin
context:
cluster: staging-cluster
user: staging-user
namespace: staging
- name: Update only the token for an existing user, preserving all other user fields
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
users:
- name: admin-user
behavior: merge
user:
token: "{{ new_admin_token }}"
- name: Replace a cluster definition entirely.
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
clusters:
- name: production-cluster
behavior: replace
cluster:
server: https://new-prod.k8s.example.com:6443
certificate-authority-data: LS0tLS1CRUdJTi...
- name: Remove a decommissioned cluster, user, and context
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
clusters:
- name: old-cluster
behavior: remove
users:
- name: old-user
behavior: remove
contexts:
- name: old-context
behavior: remove
- name: Switch the active context
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
current_context: staging-admin
- name: Copy a kubeconfig to a new location with an additional cluster merged in
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
dest: /home/user/.kube/config-ci
clusters:
- name: ci-cluster
cluster:
server: https://ci.k8s.example.com:6443
insecure-skip-tls-verify: true
Return Values
-------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html
<table border=0 cellpadding=0 class="documentation-table">
<tr>
<th colspan="1">Key</th>
<th>Returned</th>
<th width="100%">Description</th>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>dest</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>always</td>
<td>
<div>The path where the kubeconfig was written.</div>
<br/>
<div style="font-size: smaller"><b>Sample:</b></div>
<div style="font-size: smaller; color: blue; word-wrap: break-word; word-break: break-all;">/home/user/.kube/config</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>kubeconfig</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
</td>
<td>always</td>
<td>
<div>The complete kubeconfig data structure.</div>
<br/>
</td>
</tr>
</table>
<br/><br/>
Status
------
Authors
~~~~~~~
- Youssef Khalid Ali (@YoussefKhalidAli)
@@ -383,7 +383,6 @@ Examples
# and requires python to be installed in the image # and requires python to be installed in the image
- name: Run a command in a pod - name: Run a command in a pod
ansible.builtin.command: echo "Hello, World!" ansible.builtin.command: echo "Hello, World!"
changed_when: false
- name: Run a command in a pod using local kubectl with inventory variables - name: Run a command in a pod using local kubectl with inventory variables
# Example inventory: # Example inventory:
@@ -408,7 +407,6 @@ Examples
# and requires python to be installed in the image # and requires python to be installed in the image
- name: Run a command in a pod - name: Run a command in a pod
ansible.builtin.command: echo "Hello, World!" ansible.builtin.command: echo "Hello, World!"
changed_when: false
- name: Run a command in a pod using dynamic inventory - name: Run a command in a pod using dynamic inventory
hosts: localhost hosts: localhost
@@ -442,7 +440,6 @@ Examples
# be aware that the command is executed as the user that started the container # be aware that the command is executed as the user that started the container
# and requires python to be installed in the image # and requires python to be installed in the image
ansible.builtin.command: echo "Hello, World!" ansible.builtin.command: echo "Hello, World!"
changed_when: false
delegate_to: "{{ my_app_pod_name }}" delegate_to: "{{ my_app_pod_name }}"
+1 -29
View File
@@ -95,26 +95,6 @@ Parameters
<div>Enable the helm chart inflation generator</div> <div>Enable the helm chart inflation generator</div>
</td> </td>
</tr> </tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>environment</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">raw</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.2.0</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">{}</div>
</td>
<td>
</td>
<td>
<div>The environment variables to pass to the kustomize or kubectl command.</div>
<div>This can be a dictionary or a string in the format key=value, multiple pairs separated by space.</div>
</td>
</tr>
<tr> <tr>
<td colspan="1"> <td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div> <div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -165,19 +145,11 @@ Examples
kubernetes.core.k8s: kubernetes.core.k8s:
definition: "{{ lookup('kubernetes.core.kustomize', dir='/path/to/kustomization', enable_helm=True) }}" definition: "{{ lookup('kubernetes.core.kustomize', dir='/path/to/kustomization', enable_helm=True) }}"
- name: Create kubernetes resources for lookup output with environment variables in string format
kubernetes.core.k8s:
definition: "{{ lookup('kubernetes.core.kustomize', binary_path='/path/to/kubectl', environment='HTTP_PROXY=http://proxy.example.com:3128') }}"
- name: Create kubernetes resources for lookup output with environment variables in dict format
kubernetes.core.k8s:
definition: "{{ lookup('kubernetes.core.kustomize', binary_path='/path/to/kubectl', environment={'HTTP_PROXY': 'http://proxy.example.com:3128'}) }}"
Return Values Return Values
------------- -------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this lookup: Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this lookup:
.. raw:: html .. raw:: html
+1 -1
View File
@@ -25,7 +25,7 @@ tags:
- openshift - openshift
- okd - okd
- cluster - cluster
version: 7.0.0-dev0 version: 5.4.4
build_ignore: build_ignore:
- .DS_Store - .DS_Store
- "*.tar.gz" - "*.tar.gz"
-1
View File
@@ -1,5 +1,4 @@
--- ---
version: 3
dependencies: dependencies:
python: requirements.txt python: requirements.txt
system: meta/ee-bindep.txt system: meta/ee-bindep.txt
+3 -10
View File
@@ -1,17 +1,10 @@
--- ---
requires_ansible: '>=2.16.0' 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: action_groups:
helm: helm:
- helm - helm
- helm_info - helm_info
- helm_plugin
- helm_plugin_info
- helm_repository - helm_repository
k8s: k8s:
- k8s - k8s
@@ -25,17 +18,17 @@ action_groups:
- k8s_rollback - k8s_rollback
- k8s_scale - k8s_scale
- k8s_service - k8s_service
- k8s_taint
plugin_routing: plugin_routing:
inventory: inventory:
openshift: openshift:
redirect: community.okd.openshift redirect: community.okd.openshift
k8s: k8s:
tombstone: deprecation:
removal_version: 6.0.0 removal_version: 6.0.0
warning_text: >- 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. The k8s inventory plugin has been deprecated and
will be removed in release 6.0.0.
modules: modules:
k8s_auth: k8s_auth:
redirect: community.okd.k8s_auth redirect: community.okd.k8s_auth
+3 -12
View File
@@ -20,7 +20,7 @@ from ansible.errors import (
AnsibleError, AnsibleError,
AnsibleFileNotFound, AnsibleFileNotFound,
) )
from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.module_utils.parsing.convert_bool import boolean from ansible.module_utils.parsing.convert_bool import boolean
from ansible.plugins.action import ActionBase from ansible.plugins.action import ActionBase
@@ -35,11 +35,7 @@ def _from_yaml_to_definition(buffer):
import yaml import yaml
except ImportError: except ImportError:
raise AnsibleError("Failed to import the required Python library (PyYAML).") 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 ":" ENV_KUBECONFIG_PATH_SEPARATOR = ";" if platform.system() == "Windows" else ":"
@@ -384,15 +380,10 @@ class ActionModule(ActionBase):
template = self._task.args.get("template", None) template = self._task.args.get("template", None)
if template: if template:
self.load_template(template, new_module_args, task_vars) 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") local_path = self._task.args.get("local_path")
state = self._task.args.get("state", None) state = self._task.args.get("state", None)
is_local_pod_upload = local_path and state == "to_pod" and not remote_transport if 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) new_module_args["local_path"] = self.get_file_realpath(local_path)
# Execute the k8s_* module. # Execute the k8s_* module.
+5 -8
View File
@@ -196,7 +196,6 @@ EXAMPLES = r"""
# and requires python to be installed in the image # and requires python to be installed in the image
- name: Run a command in a pod - name: Run a command in a pod
ansible.builtin.command: echo "Hello, World!" ansible.builtin.command: echo "Hello, World!"
changed_when: false
- name: Run a command in a pod using local kubectl with inventory variables - name: Run a command in a pod using local kubectl with inventory variables
# Example inventory: # Example inventory:
@@ -221,20 +220,19 @@ EXAMPLES = r"""
# and requires python to be installed in the image # and requires python to be installed in the image
- name: Run a command in a pod - name: Run a command in a pod
ansible.builtin.command: echo "Hello, World!" ansible.builtin.command: echo "Hello, World!"
changed_when: false
- name: Run a command in a pod using dynamic inventory - name: Run a command in a pod using dynamic inventory
hosts: localhost hosts: localhost
gather_facts: no gather_facts: no
vars: vars:
kubeconfig: /root/.kube/config kubeconfig: /root/.kube/config
k8s_namespace: my-namespace namespace: my-namespace
my_app: my-app my_app: my-app
tasks: tasks:
- name: Get My App pod info based on label - name: Get My App pod info based on label
kubernetes.core.k8s_info: kubernetes.core.k8s_info:
kubeconfig: "{{ kubeconfig }}" kubeconfig: "{{ kubeconfig }}"
namespace: "{{ k8s_namespace }}" namespace: "{{ namespace }}"
kind: Pod kind: Pod
label_selectors: app.kubernetes.io/name = "{{ my_app }}" label_selectors: app.kubernetes.io/name = "{{ my_app }}"
register: my_app_pod register: my_app_pod
@@ -249,13 +247,12 @@ EXAMPLES = r"""
ansible_connection: kubernetes.core.kubectl ansible_connection: kubernetes.core.kubectl
ansible_kubectl_kubeconfig: "{{ kubeconfig }}" ansible_kubectl_kubeconfig: "{{ kubeconfig }}"
ansible_kubectl_pod: "{{ my_app_pod_name }}" ansible_kubectl_pod: "{{ my_app_pod_name }}"
ansible_kubectl_namespace: "{{ k8s_namespace }}" ansible_kubectl_namespace: "{{ namespace }}"
- name: Run a command in My App pod - name: Run a command in My App pod
# be aware that the command is executed as the user that started the container # be aware that the command is executed as the user that started the container
# and requires python to be installed in the image # and requires python to be installed in the image
ansible.builtin.command: echo "Hello, World!" ansible.builtin.command: echo "Hello, World!"
changed_when: false
delegate_to: "{{ my_app_pod_name }}" delegate_to: "{{ my_app_pod_name }}"
""" """
@@ -265,11 +262,11 @@ import os.path
import shutil import shutil
import subprocess import subprocess
import tempfile import tempfile
from shlex import quote as shlex_quote
from ansible.errors import AnsibleError, AnsibleFileNotFound from ansible.errors import AnsibleError, AnsibleFileNotFound
from ansible.module_utils.common.text.converters import to_bytes from ansible.module_utils._text import to_bytes
from ansible.module_utils.parsing.convert_bool import boolean 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.parsing.yaml.loader import AnsibleLoader
from ansible.plugins.connection import BUFSIZE, ConnectionBase from ansible.plugins.connection import BUFSIZE, ConnectionBase
from ansible.utils.display import Display from ansible.utils.display import Display
+3 -2
View File
@@ -16,8 +16,9 @@ options:
state: state:
description: description:
- Determines if an object should be created, patched, or deleted. When set to C(present), an object will be - Determines if an object should be created, patched, or deleted. When set to C(present), an object will be
created if it does not already exist, and an existing object will be patched if its attributes differ from created, if it does not already exist. If set to C(absent), an existing object will be deleted. If set to
those specified using I(resource_definition) or I(src). If set to C(absent), an existing object will be deleted. C(present), an existing object will be patched, if its attributes differ from those specified using
I(resource_definition) or I(src).
type: str type: str
default: present default: present
choices: [ absent, present ] choices: [ absent, present ]
+476
View File
@@ -0,0 +1,476 @@
# Copyright (c) 2018 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
DOCUMENTATION = """
name: k8s
author:
- Chris Houseknecht (@chouseknecht)
- Fabian von Feilitzsch (@fabianvf)
short_description: Kubernetes (K8s) inventory source
description:
- Fetch containers and services for one or more clusters.
- Groups by cluster name, namespace, namespace_services, namespace_pods, and labels.
- Uses the kubectl connection plugin to access the Kubernetes cluster.
- Uses k8s.(yml|yaml) YAML configuration file to set parameter values.
deprecated:
removed_in: 6.0.0
why: |
As discussed in U(https://github.com/ansible-collections/kubernetes.core/issues/31), we decided to
remove the k8s inventory plugin in release 6.0.0.
alternative: "Use M(kubernetes.core.k8s_info) and M(ansible.builtin.add_host) instead."
options:
plugin:
description: token that ensures this is a source file for the 'k8s' plugin.
required: True
choices: ['kubernetes.core.k8s', 'k8s', 'community.kubernetes.k8s']
connections:
description:
- Optional list of cluster connection settings. If no connections are provided, the default
I(~/.kube/config) and active context will be used, and objects will be returned for all namespaces
the active user is authorized to access.
suboptions:
name:
description:
- Optional name to assign to the cluster. If not provided, a name is constructed from the server
and port.
kubeconfig:
description:
- Path to an existing Kubernetes config file. If not provided, and no other connection
options are provided, the Kubernetes client will attempt to load the default
configuration file from I(~/.kube/config). Can also be specified via K8S_AUTH_KUBECONFIG
environment variable.
context:
description:
- The name of a context found in the config file. Can also be specified via K8S_AUTH_CONTEXT environment
variable.
host:
description:
- Provide a URL for accessing the API. Can also be specified via K8S_AUTH_HOST environment variable.
api_key:
description:
- Token used to authenticate with the API. Can also be specified via K8S_AUTH_API_KEY environment
variable.
username:
description:
- Provide a username for authenticating with the API. Can also be specified via K8S_AUTH_USERNAME
environment variable.
password:
description:
- Provide a password for authenticating with the API. Can also be specified via K8S_AUTH_PASSWORD
environment variable.
client_cert:
description:
- Path to a certificate used to authenticate with the API. Can also be specified via K8S_AUTH_CERT_FILE
environment variable.
aliases: [ cert_file ]
client_key:
description:
- Path to a key file used to authenticate with the API. Can also be specified via K8S_AUTH_KEY_FILE
environment variable.
aliases: [ key_file ]
ca_cert:
description:
- Path to a CA certificate used to authenticate with the API. Can also be specified via
K8S_AUTH_SSL_CA_CERT environment variable.
aliases: [ ssl_ca_cert ]
validate_certs:
description:
- "Whether or not to verify the API server's SSL certificates. Can also be specified via
K8S_AUTH_VERIFY_SSL environment variable."
type: bool
aliases: [ verify_ssl ]
namespaces:
description:
- List of namespaces. If not specified, will fetch all containers for all namespaces user is authorized
to access.
requirements:
- "python >= 3.9"
- "kubernetes >= 24.2.0"
- "PyYAML >= 3.11"
"""
EXAMPLES = r"""
# File must be named k8s.yaml or k8s.yml
- name: Authenticate with token, and return all pods and services for all namespaces
plugin: kubernetes.core.k8s
connections:
- host: https://192.168.64.4:8443
api_key: xxxxxxxxxxxxxxxx
validate_certs: false
- name: Use default config (~/.kube/config) file and active context, and return objects for a specific namespace
plugin: kubernetes.core.k8s
connections:
- namespaces:
- testing
- name: Use a custom config file, and a specific context.
plugin: kubernetes.core.k8s
connections:
- kubeconfig: /path/to/config
context: 'awx/192-168-64-4:8443/developer'
"""
import json
from ansible.errors import AnsibleError
from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable, Constructable
try:
from kubernetes.dynamic.exceptions import DynamicApiError
HAS_K8S_MODULE_HELPER = True
k8s_import_exception = None
except ImportError as e:
HAS_K8S_MODULE_HELPER = False
k8s_import_exception = e
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
get_api_client,
)
def format_dynamic_api_exc(exc):
if exc.body:
if exc.headers and exc.headers.get("Content-Type") == "application/json":
message = json.loads(exc.body).get("message")
if message:
return message
return exc.body
else:
return "%s Reason: %s" % (exc.status, exc.reason)
class K8sInventoryException(Exception):
pass
class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
NAME = "kubernetes.core.k8s"
connection_plugin = "kubernetes.core.kubectl"
transport = "kubectl"
def parse(self, inventory, loader, path, cache=True):
super(InventoryModule, self).parse(inventory, loader, path)
self.display.deprecated(
"The 'k8s' inventory plugin has been deprecated and will be removed in release 6.0.0",
version="6.0.0",
collection_name="kubernetes.core",
)
cache_key = self._get_cache_prefix(path)
config_data = self._read_config_data(path)
self.setup(config_data, cache, cache_key)
def setup(self, config_data, cache, cache_key):
connections = config_data.get("connections")
if not HAS_K8S_MODULE_HELPER:
raise K8sInventoryException(
"This module requires the Kubernetes Python client. Try `pip install kubernetes`. Detail: {0}".format(
k8s_import_exception
)
)
source_data = None
if cache and cache_key in self._cache:
try:
source_data = self._cache[cache_key]
except KeyError:
pass
if not source_data:
self.fetch_objects(connections)
def fetch_objects(self, connections):
if connections:
if not isinstance(connections, list):
raise K8sInventoryException("Expecting connections to be a list.")
for connection in connections:
if not isinstance(connection, dict):
raise K8sInventoryException(
"Expecting connection to be a dictionary."
)
client = get_api_client(**connection)
name = connection.get(
"name", self.get_default_host_name(client.configuration.host)
)
if connection.get("namespaces"):
namespaces = connection["namespaces"]
else:
namespaces = self.get_available_namespaces(client)
for namespace in namespaces:
self.get_pods_for_namespace(client, name, namespace)
self.get_services_for_namespace(client, name, namespace)
else:
client = get_api_client()
name = self.get_default_host_name(client.configuration.host)
namespaces = self.get_available_namespaces(client)
for namespace in namespaces:
self.get_pods_for_namespace(client, name, namespace)
self.get_services_for_namespace(client, name, namespace)
@staticmethod
def get_default_host_name(host):
return (
host.replace("https://", "")
.replace("http://", "")
.replace(".", "-")
.replace(":", "_")
)
def get_available_namespaces(self, client):
v1_namespace = client.resources.get(api_version="v1", kind="Namespace")
try:
obj = v1_namespace.get()
except DynamicApiError as exc:
self.display.debug(exc)
raise K8sInventoryException(
"Error fetching Namespace list: %s" % format_dynamic_api_exc(exc)
)
return [namespace.metadata.name for namespace in obj.items]
def get_pods_for_namespace(self, client, name, namespace):
v1_pod = client.resources.get(api_version="v1", kind="Pod")
try:
obj = v1_pod.get(namespace=namespace)
except DynamicApiError as exc:
self.display.debug(exc)
raise K8sInventoryException(
"Error fetching Pod list: %s" % format_dynamic_api_exc(exc)
)
namespace_group = "namespace_{0}".format(namespace)
namespace_pods_group = "{0}_pods".format(namespace_group)
self.inventory.add_group(name)
self.inventory.add_group(namespace_group)
self.inventory.add_child(name, namespace_group)
self.inventory.add_group(namespace_pods_group)
self.inventory.add_child(namespace_group, namespace_pods_group)
for pod in obj.items:
pod_name = pod.metadata.name
pod_groups = []
pod_annotations = (
{} if not pod.metadata.annotations else dict(pod.metadata.annotations)
)
if pod.metadata.labels:
# create a group for each label_value
for key, value in pod.metadata.labels:
group_name = "label_{0}_{1}".format(key, value)
if group_name not in pod_groups:
pod_groups.append(group_name)
self.inventory.add_group(group_name)
pod_labels = dict(pod.metadata.labels)
else:
pod_labels = {}
if not pod.status.containerStatuses:
continue
for container in pod.status.containerStatuses:
# add each pod_container to the namespace group, and to each label_value group
container_name = "{0}_{1}".format(pod.metadata.name, container.name)
self.inventory.add_host(container_name)
self.inventory.add_child(namespace_pods_group, container_name)
if pod_groups:
for group in pod_groups:
self.inventory.add_child(group, container_name)
# Add hostvars
self.inventory.set_variable(container_name, "object_type", "pod")
self.inventory.set_variable(container_name, "labels", pod_labels)
self.inventory.set_variable(
container_name, "annotations", pod_annotations
)
self.inventory.set_variable(
container_name, "cluster_name", pod.metadata.clusterName
)
self.inventory.set_variable(
container_name, "pod_node_name", pod.spec.nodeName
)
self.inventory.set_variable(container_name, "pod_name", pod.spec.name)
self.inventory.set_variable(
container_name, "pod_host_ip", pod.status.hostIP
)
self.inventory.set_variable(
container_name, "pod_phase", pod.status.phase
)
self.inventory.set_variable(container_name, "pod_ip", pod.status.podIP)
self.inventory.set_variable(
container_name, "pod_self_link", pod.metadata.selfLink
)
self.inventory.set_variable(
container_name, "pod_resource_version", pod.metadata.resourceVersion
)
self.inventory.set_variable(container_name, "pod_uid", pod.metadata.uid)
self.inventory.set_variable(
container_name, "container_name", container.image
)
self.inventory.set_variable(
container_name, "container_image", container.image
)
if container.state.running:
self.inventory.set_variable(
container_name, "container_state", "Running"
)
if container.state.terminated:
self.inventory.set_variable(
container_name, "container_state", "Terminated"
)
if container.state.waiting:
self.inventory.set_variable(
container_name, "container_state", "Waiting"
)
self.inventory.set_variable(
container_name, "container_ready", container.ready
)
self.inventory.set_variable(
container_name, "ansible_remote_tmp", "/tmp/"
)
self.inventory.set_variable(
container_name, "ansible_connection", self.connection_plugin
)
self.inventory.set_variable(
container_name, "ansible_{0}_pod".format(self.transport), pod_name
)
self.inventory.set_variable(
container_name,
"ansible_{0}_container".format(self.transport),
container.name,
)
self.inventory.set_variable(
container_name,
"ansible_{0}_namespace".format(self.transport),
namespace,
)
def get_services_for_namespace(self, client, name, namespace):
v1_service = client.resources.get(api_version="v1", kind="Service")
try:
obj = v1_service.get(namespace=namespace)
except DynamicApiError as exc:
self.display.debug(exc)
raise K8sInventoryException(
"Error fetching Service list: %s" % format_dynamic_api_exc(exc)
)
namespace_group = "namespace_{0}".format(namespace)
namespace_services_group = "{0}_services".format(namespace_group)
self.inventory.add_group(name)
self.inventory.add_group(namespace_group)
self.inventory.add_child(name, namespace_group)
self.inventory.add_group(namespace_services_group)
self.inventory.add_child(namespace_group, namespace_services_group)
for service in obj.items:
service_name = service.metadata.name
service_labels = (
{} if not service.metadata.labels else dict(service.metadata.labels)
)
service_annotations = (
{}
if not service.metadata.annotations
else dict(service.metadata.annotations)
)
self.inventory.add_host(service_name)
if service.metadata.labels:
# create a group for each label_value
for key, value in service.metadata.labels:
group_name = "label_{0}_{1}".format(key, value)
self.inventory.add_group(group_name)
self.inventory.add_child(group_name, service_name)
try:
self.inventory.add_child(namespace_services_group, service_name)
except AnsibleError:
raise
ports = [
{
"name": port.name,
"port": port.port,
"protocol": port.protocol,
"targetPort": port.targetPort,
"nodePort": port.nodePort,
}
for port in service.spec.ports or []
]
# add hostvars
self.inventory.set_variable(service_name, "object_type", "service")
self.inventory.set_variable(service_name, "labels", service_labels)
self.inventory.set_variable(
service_name, "annotations", service_annotations
)
self.inventory.set_variable(
service_name, "cluster_name", service.metadata.clusterName
)
self.inventory.set_variable(service_name, "ports", ports)
self.inventory.set_variable(service_name, "type", service.spec.type)
self.inventory.set_variable(
service_name, "self_link", service.metadata.selfLink
)
self.inventory.set_variable(
service_name, "resource_version", service.metadata.resourceVersion
)
self.inventory.set_variable(service_name, "uid", service.metadata.uid)
if service.spec.externalTrafficPolicy:
self.inventory.set_variable(
service_name,
"external_traffic_policy",
service.spec.externalTrafficPolicy,
)
if service.spec.externalIPs:
self.inventory.set_variable(
service_name, "external_ips", service.spec.externalIPs
)
if service.spec.externalName:
self.inventory.set_variable(
service_name, "external_name", service.spec.externalName
)
if service.spec.healthCheckNodePort:
self.inventory.set_variable(
service_name,
"health_check_node_port",
service.spec.healthCheckNodePort,
)
if service.spec.loadBalancerIP:
self.inventory.set_variable(
service_name, "load_balancer_ip", service.spec.loadBalancerIP
)
if service.spec.selector:
self.inventory.set_variable(
service_name, "selector", dict(service.spec.selector)
)
if (
hasattr(service.status.loadBalancer, "ingress")
and service.status.loadBalancer.ingress
):
load_balancer = [
{"hostname": ingress.hostname, "ip": ingress.ip}
for ingress in service.status.loadBalancer.ingress
]
self.inventory.set_variable(
service_name, "load_balancer", load_balancer
)
+1 -33
View File
@@ -209,60 +209,28 @@ RETURN = """
""" """
import os import os
from collections.abc import KeysView
from ansible.errors import AnsibleError from ansible.errors import AnsibleError
from ansible.module_utils.ansible_release import __version__ as ansible_version from ansible.module_utils.common._collections_compat import KeysView
from ansible.module_utils.common.validation import check_type_bool 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 ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
get_api_client, get_api_client,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.resource import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.resource import (
create_definitions, 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: try:
enable_turbo_mode = check_type_bool(os.environ.get("ENABLE_TURBO_MODE")) enable_turbo_mode = check_type_bool(os.environ.get("ENABLE_TURBO_MODE"))
except TypeError: except TypeError:
enable_turbo_mode = False 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: if enable_turbo_mode:
try: try:
from ansible_collections.cloud.common.plugins.plugin_utils.turbo.lookup import ( from ansible_collections.cloud.common.plugins.plugin_utils.turbo.lookup import (
TurboLookupBase as LookupBase, TurboLookupBase as LookupBase,
) )
except ImportError: 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 from ansible.plugins.lookup import LookupBase # noqa: F401
else: else:
from ansible.plugins.lookup import LookupBase # noqa: F401 from ansible.plugins.lookup import LookupBase # noqa: F401
+3 -36
View File
@@ -34,13 +34,6 @@ DOCUMENTATION = """
description: description:
- Enable the helm chart inflation generator - Enable the helm chart inflation generator
default: "False" default: "False"
environment:
description:
- The environment variables to pass to the kustomize or kubectl command.
- This can be a dictionary or a string in the format key=value, multiple pairs separated by space.
type: raw
default: {}
version_added: 6.2.0
requirements: requirements:
- "python >= 3.6" - "python >= 3.6"
@@ -62,14 +55,6 @@ EXAMPLES = """
- name: Create kubernetes resources for lookup output with `--enable-helm` set - name: Create kubernetes resources for lookup output with `--enable-helm` set
kubernetes.core.k8s: kubernetes.core.k8s:
definition: "{{ lookup('kubernetes.core.kustomize', dir='/path/to/kustomization', enable_helm=True) }}" definition: "{{ lookup('kubernetes.core.kustomize', dir='/path/to/kustomization', enable_helm=True) }}"
- name: Create kubernetes resources for lookup output with environment variables in string format
kubernetes.core.k8s:
definition: "{{ lookup('kubernetes.core.kustomize', binary_path='/path/to/kubectl', environment='HTTP_PROXY=http://proxy.example.com:3128') }}"
- name: Create kubernetes resources for lookup output with environment variables in dict format
kubernetes.core.k8s:
definition: "{{ lookup('kubernetes.core.kustomize', binary_path='/path/to/kubectl', environment={'HTTP_PROXY': 'http://proxy.example.com:3128'}) }}"
""" """
RETURN = """ RETURN = """
@@ -87,7 +72,6 @@ RETURN = """
key1: val1 key1: val1
""" """
import os
import subprocess import subprocess
from ansible.errors import AnsibleLookupError from ansible.errors import AnsibleLookupError
@@ -108,10 +92,8 @@ def get_binary_from_path(name, opt_dirs=None):
return None return None
def run_command(command, environ=None): def run_command(command):
cmd = subprocess.Popen( cmd = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environ
)
stdout, stderr = cmd.communicate() stdout, stderr = cmd.communicate()
return cmd.returncode, stdout, stderr return cmd.returncode, stdout, stderr
@@ -125,7 +107,6 @@ class LookupModule(LookupBase):
binary_path=None, binary_path=None,
opt_dirs=None, opt_dirs=None,
enable_helm=False, enable_helm=False,
environment=None,
**kwargs **kwargs
): ):
executable_path = binary_path executable_path = binary_path
@@ -160,21 +141,7 @@ class LookupModule(LookupBase):
if enable_helm: if enable_helm:
command += ["--enable-helm"] command += ["--enable-helm"]
environ = None (ret, out, err) = run_command(command)
if environment:
environ = os.environ.copy()
if isinstance(environment, str):
if not all(env.count("=") == 1 for env in environment.split(" ")):
raise AnsibleLookupError(
"environment should be dict or string in the format key=value, multiple pairs separated by space"
)
for env in environment.split(" "):
key, value = env.split("=")
environ[key] = value
if isinstance(environment, dict):
environ.update(environment)
(ret, out, err) = run_command(command, environ=environ)
if ret != 0: if ret != 0:
if err: if err:
raise AnsibleLookupError( raise AnsibleLookupError(
-30
View File
@@ -5,39 +5,13 @@ __metaclass__ = type
import os 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.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: try:
enable_turbo_mode = check_type_bool(os.environ.get("ENABLE_TURBO_MODE")) enable_turbo_mode = check_type_bool(os.environ.get("ENABLE_TURBO_MODE"))
except TypeError: except TypeError:
enable_turbo_mode = False 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: if enable_turbo_mode:
try: try:
from ansible_collections.cloud.common.plugins.module_utils.turbo.module import ( # noqa: F401 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import ( # noqa: F401
@@ -46,10 +20,6 @@ if enable_turbo_mode:
AnsibleModule.collection_name = "kubernetes.core" AnsibleModule.collection_name = "kubernetes.core"
except ImportError: 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 from ansible.module_utils.basic import AnsibleModule # noqa: F401
else: else:
from ansible.module_utils.basic import AnsibleModule # noqa: F401 from ansible.module_utils.basic import AnsibleModule # noqa: F401
-15
View File
@@ -144,18 +144,3 @@ DELETE_OPTS_ARG_SPEC = {
"options": {"resourceVersion": {"type": "str"}, "uid": {"type": "str"}}, "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"
),
}
+1 -1
View File
@@ -23,7 +23,7 @@ import base64
import os import os
from tempfile import NamedTemporaryFile from tempfile import NamedTemporaryFile
from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.module_utils.urls import Request from ansible.module_utils.urls import Request
try: try:
+54 -179
View File
@@ -18,14 +18,12 @@ from __future__ import absolute_import, division, print_function
__metaclass__ = type __metaclass__ = type
import os import os
import shlex
import tarfile import tarfile
import time
from abc import ABCMeta, abstractmethod from abc import ABCMeta, abstractmethod
from select import select from select import select
from tempfile import NamedTemporaryFile, TemporaryFile from tempfile import NamedTemporaryFile, TemporaryFile
from ansible.module_utils.common.text.converters import to_native from ansible.module_utils._text import to_native
# from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import AnsibleModule # from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import AnsibleModule
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import (
@@ -298,156 +296,14 @@ class K8SCopyToPod(K8SCopy):
Copy files/directory from local filesystem into remote Pod 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): def __init__(self, module, client):
super(K8SCopyToPod, self).__init__(module, client) super(K8SCopyToPod, self).__init__(module, client)
self.files_to_copy = list() self.files_to_copy = list()
self.named_temp_file = None
self.copy_timeout = module.params.get("copy_timeout")
def close_temp_file(self): def close_temp_file(self):
if self.named_temp_file: if self.named_temp_file:
self.named_temp_file.close() 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): def run(self):
# remove trailing slash from destination path # remove trailing slash from destination path
dest_file = self.remote_path.rstrip("/") dest_file = self.remote_path.rstrip("/")
@@ -480,46 +336,65 @@ class K8SCopyToPod(K8SCopy):
dest_file = os.path.join(dest_file, os.path.basename(src_file)) dest_file = os.path.join(dest_file, os.path.basename(src_file))
if not self.check_mode: 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: 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: with tarfile.open(fileobj=tar_buffer, mode="w") as tar:
tar.add(src_file, dest_file) tar.add(src_file, dest_file)
archive_size = tar_buffer.tell()
tar_buffer.seek(0) 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)
command, wait_for_exit = self.remote_command(dest_file, archive_size) stderr, stdout = [], []
response = stream( while response.is_open():
self.api_instance.connect_get_namespaced_pod_exec, if response.peek_stdout():
self.name, stdout.append(response.read_stdout().rstrip("\n"))
self.namespace, if response.peek_stderr():
command=command, stderr.append(response.read_stderr().rstrip("\n"))
stderr=True, if commands:
stdin=True, cmd = commands.pop(0)
stdout=True, response.write_stdin(cmd)
tty=False, else:
_preload_content=False, break
**self.container_arg, response.close()
) if stderr:
error, stdout, stderr = self._stream_tar_to_pod( self.close_temp_file()
response, tar_buffer, wait_for_exit self.module.fail_json(
) command=tar_command,
msg="Failed to copy local file/directory into Pod due to: {0}".format(
if error is not None and error.get("status") != "Success": "".join(stderr)
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() self.close_temp_file()
if self.content: if self.content:
self.module.exit_json( self.module.exit_json(
+14 -79
View File
@@ -32,53 +32,6 @@ except ImportError:
HAS_YAML = False 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): def parse_helm_plugin_list(output=None):
""" """
Parse `helm plugin list`, return list of plugins Parse `helm plugin list`, return list of plugins
@@ -87,20 +40,16 @@ def parse_helm_plugin_list(output=None):
if not output: if not output:
return ret return ret
parsing_grammar = None
for line in output: for line in output:
if line.startswith("NAME"): if line.startswith("NAME"):
parsing_grammar = [s.strip().lower() for s in line.split("\t")]
continue continue
if parsing_grammar is None: name, version, description = line.split("\t", 3)
name = name.strip()
version = version.strip()
description = description.strip()
if name == "":
continue continue
plugin = { ret.append((name, version, description))
parsing_grammar[i]: v.strip()
for i, v in enumerate(line.split("\t", len(parsing_grammar)))
}
if plugin["name"] == "":
continue
ret.append(plugin)
return ret return ret
@@ -253,35 +202,21 @@ class AnsibleHelmModule(object):
return m.group(1) return m.group(1)
return None return None
def is_helm_v4(self): def validate_helm_version(self):
helm_version = self.get_helm_version()
if helm_version is None:
return False
return LooseVersion(helm_version) >= LooseVersion("4.0.0")
def is_helm_version_compatible_with_helm_diff(self, helm_diff_version):
""" """
Return true if the helm version is compatible with the helm diff version Validate that Helm version is >=3.0.0 and <4.0.0.
Helm v4 requires helm diff v3.14.0 Helm 4 is not yet supported.
"""
if not helm_diff_version:
return False
if self.is_helm_v4():
return LooseVersion(helm_diff_version) >= LooseVersion("3.14.0")
return True
def validate_helm_version(self, version="3.0.0"):
"""
Validate that Helm version is >= version (default version=3.0.0).
""" """
helm_version = self.get_helm_version() helm_version = self.get_helm_version()
if helm_version is None: if helm_version is None:
self.fail_json(msg="Unable to determine Helm version") self.fail_json(msg="Unable to determine Helm version")
if LooseVersion(helm_version) < LooseVersion(version): if (LooseVersion(helm_version) < LooseVersion("3.0.0")) or (
LooseVersion(helm_version) >= LooseVersion("4.0.0")
):
self.fail_json( self.fail_json(
msg="Helm version must be >= {0}, current version is {1}".format( msg="Helm version must be >=3.0.0,<4.0.0, current version is {0}".format(
version, helm_version helm_version
) )
) )
-1
View File
@@ -181,7 +181,6 @@ def _create_headers(module=None, **kwargs):
header_map = { header_map = {
"impersonate_user": "Impersonate-User", "impersonate_user": "Impersonate-User",
"impersonate_groups": "Impersonate-Group", "impersonate_groups": "Impersonate-Group",
"accept": "Accept",
} }
headers = {} headers = {}
+11 -7
View File
@@ -3,7 +3,7 @@
from typing import Dict from typing import Dict
from ansible.module_utils.common.text.converters import to_native from ansible.module_utils._text import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
get_api_client, get_api_client,
) )
@@ -92,10 +92,10 @@ def run_module(module) -> None:
for definition in definitions: for definition in definitions:
result = {"changed": False, "result": {}} result = {"changed": False, "result": {}}
warnings = []
if module.params.get("validate") is not None: if module.params.get("validate") is not None:
for warning in validate(client, module, definition): warnings = validate(client, module, definition)
module.warn(warning)
try: try:
result = perform_action(svc, definition, module.params) result = perform_action(svc, definition, module.params)
@@ -109,12 +109,16 @@ def run_module(module) -> None:
except AttributeError: except AttributeError:
pass pass
error["msg"] = to_native(e) error["msg"] = to_native(e)
if warnings:
error.setdefault("warnings", []).extend(warnings)
if module.params.get("continue_on_error"): if module.params.get("continue_on_error"):
result["error"] = error result["error"] = error
else: else:
module.fail_json(**error) module.fail_json(**error)
if warnings:
result.setdefault("warnings", []).extend(warnings)
changed |= result["changed"] changed |= result["changed"]
results.append(result) results.append(result)
@@ -173,7 +177,7 @@ def perform_action(svc, definition: Dict, params: Dict) -> Dict:
result["method"] = "apply" result["method"] = "apply"
elif not existing: elif not existing:
if state == "patched": if state == "patched":
svc.module.warn( result.setdefault("warnings", []).append(
"resource 'kind={kind},name={name}' was not found but will not be " "resource 'kind={kind},name={name}' was not found but will not be "
"created as 'state' parameter has been set to '{state}'".format( "created as 'state' parameter has been set to '{state}'".format(
kind=kind, name=definition["metadata"].get("name"), state=state kind=kind, name=definition["metadata"].get("name"), state=state
@@ -190,8 +194,8 @@ def perform_action(svc, definition: Dict, params: Dict) -> Dict:
instance, warnings = svc.update(resource, definition, existing) instance, warnings = svc.update(resource, definition, existing)
result["method"] = "update" result["method"] = "update"
for warning in warnings: if warnings:
svc.module.warn(warning) result["warnings"] = warnings
# If needed, wait and/or create diff # If needed, wait and/or create diff
success = True success = True
@@ -213,7 +217,7 @@ def perform_action(svc, definition: Dict, params: Dict) -> Dict:
existing = {} existing = {}
match, diffs = diff_objects(existing, instance, hidden_fields) match, diffs = diff_objects(existing, instance, hidden_fields)
if match and diffs: if match and diffs:
svc.module.warn( result.setdefault("warnings", []).append(
"No meaningful diff was generated, but the API may not be idempotent " "No meaningful diff was generated, but the API may not be idempotent "
"(only metadata.generation or metadata.resourceVersion were changed)" "(only metadata.generation or metadata.resourceVersion were changed)"
) )
+6 -19
View File
@@ -47,18 +47,6 @@ 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: def daemonset_ready(daemonset: ResourceInstance) -> bool:
return bool( return bool(
daemonset.status daemonset.status
@@ -101,18 +89,18 @@ def custom_condition(condition: Dict, resource: ResourceInstance) -> bool:
if not matches: if not matches:
return False return False
# There should never be more than one condition of a specific type # There should never be more than one condition of a specific type
match_condition: ResourceField = matches[0] match: ResourceField = matches[0]
if match_condition.status == "Unknown": if match.status == "Unknown":
if match_condition.status == condition["status"]: if match.status == condition["status"]:
if "reason" not in condition: if "reason" not in condition:
return True return True
if condition["reason"]: if condition["reason"]:
return match_condition.reason == condition["reason"] return match.reason == condition["reason"]
return False return False
status = True if match_condition.status == "True" else False status = True if match.status == "True" else False
if status == boolean(condition["status"], strict=False): if status == boolean(condition["status"], strict=False):
if condition.get("reason"): if condition.get("reason"):
return match_condition.reason == condition["reason"] return match.reason == condition["reason"]
return True return True
return False return False
@@ -155,7 +143,6 @@ RESOURCE_PREDICATES = {
"DaemonSet": daemonset_ready, "DaemonSet": daemonset_ready,
"Deployment": deployment_ready, "Deployment": deployment_ready,
"Pod": pod_ready, "Pod": pod_ready,
"Job": job_complete,
"StatefulSet": statefulset_ready, "StatefulSet": statefulset_ready,
"ClusterOperator": cluster_operator_ready, "ClusterOperator": cluster_operator_ready,
} }
-95
View File
@@ -1,95 +0,0 @@
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import hashlib
import os
import traceback
try:
import yaml
IMP_YAML = True
IMP_YAML_ERR = None
except ImportError:
IMP_YAML = False
IMP_YAML_ERR = traceback.format_exc()
def load_yaml_file(path):
if not path or not os.path.exists(path):
return {}
with open(path, "r") as f:
return yaml.safe_load(f) or {}
def deep_merge(base, updates):
result = base.copy()
for key, value in updates.items():
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
result[key] = deep_merge(result[key], value)
else:
result[key] = value
return result
def merge_by_name(existing, new):
merged = {}
for item in existing:
if isinstance(item, dict) and "name" in item:
merged[item["name"]] = item
for item in new:
if not isinstance(item, dict) or "name" not in item:
continue
name = item["name"]
behavior = item.get("behavior", "merge")
item_copy = {k: v for k, v in item.items() if k != "behavior"}
if name in merged:
if behavior == "keep":
continue
elif behavior == "remove":
del merged[name]
elif behavior == "replace":
merged[name] = item_copy
else:
result = {"name": name}
for key in ["cluster", "user", "context"]:
if key in merged[name] or key in item_copy:
existing_config = merged[name].get(key, {})
new_config = item_copy.get(key, {})
result[key] = deep_merge(existing_config, new_config)
for key in merged[name]:
if key not in ["name", "cluster", "user", "context"]:
result[key] = merged[name][key]
for key in item_copy:
if (
key not in ["name", "cluster", "user", "context"]
and key not in result
):
result[key] = item_copy[key]
merged[name] = result
else:
if behavior == "remove":
continue
merged[name] = item_copy
return list(merged.values())
def hash_data(data):
"""Generate SHA-256 hash for idempotency checking."""
return hashlib.sha256(yaml.safe_dump(data, sort_keys=True).encode()).hexdigest()
def write_file(dest, data):
if not dest:
return False
with open(dest, "w") as f:
yaml.safe_dump(data, f, sort_keys=False)
return True
+1 -3
View File
@@ -15,6 +15,4 @@ __metaclass__ = type
# #
# from ansible.module_utils.compat.version import LooseVersion # from ansible.module_utils.compat.version import LooseVersion
from ._version import LooseVersion # noqa: F401 # pylint: disable=unused-import from ._version import LooseVersion # noqa: F401
__all__ = ["LooseVersion"]
+76 -440
View File
@@ -21,7 +21,7 @@ author:
- Matthieu Diehr (@d-matt) - Matthieu Diehr (@d-matt)
requirements: requirements:
- "helm >= 3.0.0 (https://github.com/helm/helm/releases)" - "helm (https://github.com/helm/helm/releases)"
- "yaml (https://pypi.org/project/PyYAML/)" - "yaml (https://pypi.org/project/PyYAML/)"
description: description:
@@ -132,19 +132,15 @@ options:
version_added: 2.4.0 version_added: 2.4.0
reuse_values: reuse_values:
description: description:
- When upgrading package, specifies whether to reuse the last release's values and merge in any overrides from parameters O(release_values), - When upgrading package, specifies wether to reuse the last release's values and merge in any overrides from parameters I(release_values),
O(values_files) or O(set_values). I(values_files) or I(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) - If I(reset_values) is set to C(True), this is ignored.
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 type: bool
required: false required: false
version_added: 3.0.0 version_added: 3.0.0
reset_values: reset_values:
description: description:
- When upgrading package, reset the values to the ones built into the chart. - 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 type: bool
required: false required: false
default: True default: True
@@ -153,10 +149,7 @@ options:
description: 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 - 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). parameters O(release_values), O(values_files) or O(set_values).
- 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 - If O(reset_values) or O(reuse_values) is set to V(True), this is ignored.
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. - This feature requires helm diff >= 3.9.12.
type: bool type: bool
required: false required: false
@@ -172,13 +165,6 @@ options:
force: force:
description: description:
- Helm option to force reinstall, ignore on new install. - Helm option to force reinstall, ignore on new install.
- With Helm v4 this performs a client-side replacement. Helm v4 deprecated
C(--force) (split into C(--force-replace) and C(--force-conflicts)) and
enables server-side apply by default, so for Helm v4 the module emits
C(--server-side=false --force-replace) to preserve the Helm v3 behaviour.
With Helm v3 the C(--force) flag is used. The O(force) option works the
same way regardless of the installed Helm version.
- Mutually exclusive with O(server_side) and O(force_conflicts).
default: False default: False
type: bool type: bool
purge: purge:
@@ -194,19 +180,10 @@ options:
It will wait for as long as I(wait_timeout). This feature requires helm>=3.7.0. Added in version 2.3.0. 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 default: False
type: bool 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: wait_timeout:
description: description:
- Timeout when wait option is enabled (helm2 is a number of seconds, helm3 is a duration). - 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 in version 7.0.0. Use O(timeout) instead. - The use of I(wait_timeout) to wait for kubernetes commands to complete has been deprecated and will be removed after 2022-12-01.
type: str type: str
timeout: timeout:
description: description:
@@ -218,44 +195,8 @@ options:
atomic: atomic:
description: description:
- If set, the installation process deletes the installation on failure. - If set, the installation process deletes the installation on failure.
- With Helm v4 this is translated to the C(--rollback-on-failure) flag, since
C(--atomic) was renamed; with Helm v3 the C(--atomic) flag is used. The
O(atomic) option works the same way regardless of the installed Helm version.
type: bool type: bool
default: False 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.
- Maps to the C(--server-side) flag, which accepts C(true), C(false) or C(auto).
- This option requires Helm v4 and is mutually exclusive with O(force).
type: str
choices:
- "auto"
- "true"
- "false"
version_added: 6.5.0
force_conflicts:
description:
- When server-side apply is enabled (the Helm v4 default), force changes
against conflicts instead of failing.
- Maps to the C(--force-conflicts) flag.
- This option requires Helm v4, cannot be combined with O(server_side=false),
and is mutually exclusive with O(force).
type: bool
default: False
version_added: 6.5.0
create_namespace: create_namespace:
description: description:
- Create the release namespace if not present. - Create the release namespace if not present.
@@ -296,27 +237,6 @@ options:
default: False default: False
aliases: [ skip_tls_certs_check ] aliases: [ skip_tls_certs_check ]
version_added: 5.3.0 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:
- 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
skip_schema_validation:
description:
- Disables JSON schema validation for Chart and values.
- This feature requires helm >= 3.16.0
type: bool
default: False
version_added: 6.2.0
extends_documentation_fragment: extends_documentation_fragment:
- kubernetes.core.helm_common_options - kubernetes.core.helm_common_options
""" """
@@ -399,12 +319,6 @@ EXAMPLES = r"""
chart_ref: "https://github.com/grafana/helm-charts/releases/download/grafana-5.6.0/grafana-5.6.0.tgz" chart_ref: "https://github.com/grafana/helm-charts/releases/download/grafana-5.6.0/grafana-5.6.0.tgz"
release_namespace: monitoring 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 # Using complex Values
- name: Deploy new-relic client chart - name: Deploy new-relic client chart
kubernetes.core.helm: kubernetes.core.helm:
@@ -413,7 +327,6 @@ EXAMPLES = r"""
release_namespace: default release_namespace: default
force: True force: True
wait: True wait: True
wait_for_jobs: True
replace: True replace: True
update_repo_cache: True update_repo_cache: True
disable_hook: True disable_hook: True
@@ -433,30 +346,15 @@ EXAMPLES = r"""
enabled: True enabled: True
# Deploy latest version # 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 - name: Deploy latest version of Grafana chart using reuse_values
kubernetes.core.helm: kubernetes.core.helm:
name: test name: test
chart_ref: stable/grafana chart_ref: stable/grafana
release_namespace: monitoring release_namespace: monitoring
reuse_values: true reuse_values: true
reset_values: false
values: values:
replicas: 2 replicas: 2
version: 3e8ec0b2dffa40fb97d5342e4af887de95faa8c61a62480dd7f8aa03dffcf533 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""" RETURN = r"""
@@ -498,8 +396,8 @@ status:
returned: always returned: always
description: description:
- Dict of Values used to deploy. - Dict of Values used to deploy.
- This return value has been deprecated and will be removed in version 8.0.0. - This return value has been deprecated and will be removed in a release after
Use RV(status.release_values) instead. 2027-01-08. Use RV(status.release_values) instead.
release_values: release_values:
type: dict type: dict
returned: always returned: always
@@ -545,7 +443,6 @@ from ansible.module_utils.basic import missing_required_lib
from ansible_collections.kubernetes.core.plugins.module_utils.helm import ( from ansible_collections.kubernetes.core.plugins.module_utils.helm import (
AnsibleHelmModule, AnsibleHelmModule,
parse_helm_plugin_list, parse_helm_plugin_list,
strip_registry_progress,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.helm_args_common import ( from ansible_collections.kubernetes.core.plugins.module_utils.helm_args_common import (
HELM_AUTH_ARG_SPEC, HELM_AUTH_ARG_SPEC,
@@ -576,13 +473,9 @@ def get_release_status(module, release_name, all_status=False):
"--filter", "--filter",
release_name, release_name,
] ]
if all_status and not module.is_helm_v4(): if all_status:
# --all has been removed from `helm list` command on helm v4
list_command.append("--all") list_command.append("--all")
elif not all_status:
# The default behavior to display only deployed releases has been removed from
# Helm v4
list_command.append("--deployed")
rc, out, err = module.run_helm_command(list_command) rc, out, err = module.run_helm_command(list_command)
release = get_release(yaml.safe_load(out), release_name) release = get_release(yaml.safe_load(out), release_name)
@@ -593,13 +486,6 @@ def get_release_status(module, release_name, all_status=False):
release["release_values"] = module.get_values(release_name) release["release_values"] = module.get_values(release_name)
release["values"] = release["release_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",
)
return release return release
@@ -619,9 +505,7 @@ def run_dep_update(module, chart_ref):
rc, out, err = module.run_helm_command(dep_update) rc, out, err = module.run_helm_command(dep_update)
def fetch_chart_info( def fetch_chart_info(module, command, chart_ref, insecure_skip_tls_verify=False):
module, command, chart_ref, insecure_skip_tls_verify=False, plain_http=False
):
""" """
Get chart info Get chart info
""" """
@@ -630,65 +514,9 @@ def fetch_chart_info(
if insecure_skip_tls_verify: if insecure_skip_tls_verify:
inspect_command += " --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) rc, out, err = module.run_helm_command(inspect_command)
return yaml.safe_load(strip_registry_progress(out)) return yaml.safe_load(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( def deploy(
@@ -698,14 +526,12 @@ def deploy(
release_values, release_values,
chart_name, chart_name,
wait, wait,
wait_for_jobs,
wait_timeout, wait_timeout,
disable_hook, disable_hook,
force, force,
values_files, values_files,
history_max, history_max,
atomic=False, atomic=False,
cleanup_on_fail=False,
create_namespace=False, create_namespace=False,
replace=False, replace=False,
post_renderer=None, post_renderer=None,
@@ -717,11 +543,6 @@ def deploy(
reset_values=True, reset_values=True,
reset_then_reuse_values=False, reset_then_reuse_values=False,
insecure_skip_tls_verify=False, insecure_skip_tls_verify=False,
plain_http=False,
take_ownership=False,
skip_schema_validation=False,
server_side=None,
force_conflicts=False,
): ):
""" """
Install/upgrade/rollback release chart Install/upgrade/rollback release chart
@@ -733,99 +554,36 @@ def deploy(
deploy_command += " --dependency-update" deploy_command += " --dependency-update"
else: else:
deploy_command = command + " upgrade -i" # install/upgrade deploy_command = command + " upgrade -i" # install/upgrade
if take_ownership:
deploy_command += " --take-ownership"
# '--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: if reset_values:
deploy_command += " --reset-values" deploy_command += " --reset-values"
if reuse_values is not None: if reuse_values is not None:
deploy_command += " --reuse-values=" + str(reuse_values) deploy_command += " --reuse-values=" + str(reuse_values)
if reset_then_reuse_values: if reset_then_reuse_values:
helm_version = module.get_helm_version() helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.14.0"): if LooseVersion(helm_version) < LooseVersion("3.14.0"):
module.fail_json( module.fail_json(
msg="reset_then_reuse_values requires helm >= 3.14.0, current version is {0}".format( msg="reset_then_reuse_values requires helm >= 3.14.0, current version is {0}".format(
helm_version helm_version
)
) )
else: )
deploy_command += " --reset-then-reuse-values" else:
deploy_command += " --reset-then-reuse-values"
if wait: if wait:
deploy_command += " --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: if wait_timeout is not None:
deploy_command += " --timeout " + wait_timeout deploy_command += " --timeout " + wait_timeout
if atomic: if atomic:
# Helm v4 renamed '--atomic' to '--rollback-on-failure'. The old flag is deploy_command += " --atomic"
# deprecated on 'helm upgrade' and removed from 'helm install', so always
# emit the version-appropriate flag.
if module.is_helm_v4():
deploy_command += " --rollback-on-failure"
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: if timeout:
deploy_command += " --timeout " + timeout deploy_command += " --timeout " + timeout
if server_side is not None:
if not module.is_helm_v4():
module.fail_json(
msg="server_side requires helm >= 4.0.0, current version is {0}".format(
module.get_helm_version()
)
)
deploy_command += " --server-side=" + server_side
if force_conflicts:
if not module.is_helm_v4():
module.fail_json(
msg="force_conflicts requires helm >= 4.0.0, current version is {0}".format(
module.get_helm_version()
)
)
if server_side == "false":
module.fail_json(
msg="force_conflicts requires server-side apply to be enabled and cannot be used with server_side=false"
)
deploy_command += " --force-conflicts"
if force: if force:
# Helm v4 deprecated '--force' (split into '--force-replace' and deploy_command += " --force"
# '--force-conflicts') and enables server-side apply by default, which is
# incompatible with '--force-replace'. Emit the version-appropriate flags,
# disabling server-side apply on v4 to preserve the v3 client-side
# replacement behaviour. 'force' is mutually exclusive with 'server_side'.
if module.is_helm_v4():
deploy_command += " --server-side=false --force-replace"
else:
deploy_command += " --force"
if replace: if replace:
deploy_command += " --replace" deploy_command += " --replace"
@@ -847,9 +605,6 @@ def deploy(
else: else:
deploy_command += " --insecure-skip-tls-verify" deploy_command += " --insecure-skip-tls-verify"
if plain_http:
deploy_command += " --plain-http"
if values_files: if values_files:
for value_file in values_files: for value_file in values_files:
deploy_command += " --values=" + value_file deploy_command += " --values=" + value_file
@@ -873,17 +628,6 @@ def deploy(
if set_value_args: if set_value_args:
deploy_command += " " + set_value_args deploy_command += " " + set_value_args
if skip_schema_validation:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.16.0"):
module.fail_json(
msg="skip_schema_validation requires helm >= 3.16.0, current version is {0}".format(
helm_version
)
)
else:
deploy_command += " --skip-schema-validation"
deploy_command += " " + release_name + f" '{chart_name}'" deploy_command += " " + release_name + f" '{chart_name}'"
return deploy_command return deploy_command
@@ -936,8 +680,8 @@ def get_plugin_version(plugin):
return None return None
for line in out: for line in out:
if line["name"] == plugin: if line[0] == plugin:
return line["version"] return line[1]
return None return None
@@ -956,7 +700,6 @@ def helmdiff_check(
reset_values=True, reset_values=True,
reset_then_reuse_values=False, reset_then_reuse_values=False,
insecure_skip_tls_verify=False, insecure_skip_tls_verify=False,
skip_schema_validation=False,
): ):
""" """
Use helm diff to determine if a release would change by upgrading a chart. Use helm diff to determine if a release would change by upgrading a chart.
@@ -988,10 +731,10 @@ def helmdiff_check(
if set_value_args: if set_value_args:
cmd += " " + set_value_args cmd += " " + set_value_args
if not replace and reuse_values: if reuse_values:
cmd += " --reuse-values" cmd += " --reuse-values"
if not replace and reset_then_reuse_values: if reset_then_reuse_values:
helm_diff_version = get_plugin_version("diff") helm_diff_version = get_plugin_version("diff")
helm_version = module.get_helm_version() helm_version = module.get_helm_version()
fail_msg = "" fail_msg = ""
@@ -1012,17 +755,6 @@ def helmdiff_check(
if insecure_skip_tls_verify: if insecure_skip_tls_verify:
cmd += " --insecure-skip-tls-verify" cmd += " --insecure-skip-tls-verify"
if skip_schema_validation:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.16.0"):
module.fail_json(
msg="skip_schema_validation requires helm >= 3.16.0, current version is {0}".format(
helm_version
)
)
else:
cmd += " --skip-schema-validation"
rc, out, err = module.run_helm_command(cmd) rc, out, err = module.run_helm_command(cmd)
return (len(out.strip()) > 0, out.strip()) return (len(out.strip()) > 0, out.strip())
@@ -1054,58 +786,39 @@ def default_check(release_status, chart_info, values=None, values_files=None):
def argument_spec(): def argument_spec():
arg_spec = copy.deepcopy(HELM_AUTH_ARG_SPEC) arg_spec = copy.deepcopy(HELM_AUTH_ARG_SPEC)
arg_spec.update( arg_spec.update(
{ dict(
"chart_ref": {"type": "path"}, chart_ref=dict(type="path"),
"chart_repo_url": {"type": "str"}, chart_repo_url=dict(type="str"),
"chart_version": {"type": "str"}, chart_version=dict(type="str"),
"dependency_update": { dependency_update=dict(type="bool", default=False, aliases=["dep_up"]),
"type": "bool", release_name=dict(type="str", required=True, aliases=["name"]),
"default": False, release_namespace=dict(type="str", required=True, aliases=["namespace"]),
"aliases": ["dep_up"], release_state=dict(
}, default="present", choices=["present", "absent"], aliases=["state"]
"release_name": {"type": "str", "required": True, "aliases": ["name"]}, ),
"release_namespace": { release_values=dict(type="dict", default={}, aliases=["values"]),
"type": "str", values_files=dict(type="list", default=[], elements="str"),
"required": True, update_repo_cache=dict(type="bool", default=False),
"aliases": ["namespace"], disable_hook=dict(type="bool", default=False),
}, force=dict(type="bool", default=False),
"release_state": { purge=dict(type="bool", default=True),
"default": "present", wait=dict(type="bool", default=False),
"choices": ["present", "absent"], wait_timeout=dict(type="str"),
"aliases": ["state"], timeout=dict(type="str"),
}, atomic=dict(type="bool", default=False),
"release_values": {"type": "dict", "default": {}, "aliases": ["values"]}, create_namespace=dict(type="bool", default=False),
"values_files": {"type": "list", "default": [], "elements": "str"}, post_renderer=dict(type="str"),
"update_repo_cache": {"type": "bool", "default": False}, replace=dict(type="bool", default=False),
"disable_hook": {"type": "bool", "default": False}, skip_crds=dict(type="bool", default=False),
"force": {"type": "bool", "default": False}, history_max=dict(type="int"),
"purge": {"type": "bool", "default": True}, set_values=dict(type="list", elements="dict"),
"wait": {"type": "bool", "default": False}, reuse_values=dict(type="bool"),
"wait_for_jobs": {"type": "bool", "default": False}, reset_values=dict(type="bool", default=True),
"wait_timeout": {"type": "str"}, reset_then_reuse_values=dict(type="bool", default=False),
"timeout": {"type": "str"}, insecure_skip_tls_verify=dict(
"atomic": {"type": "bool", "default": False}, type="bool", default=False, aliases=["skip_tls_certs_check"]
"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 return arg_spec
@@ -1122,24 +835,14 @@ def main():
("context", "ca_cert"), ("context", "ca_cert"),
("replace", "history_max"), ("replace", "history_max"),
("wait_timeout", "timeout"), ("wait_timeout", "timeout"),
("force", "server_side"),
("force", "force_conflicts"),
], ],
supports_check_mode=True, 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: if not IMP_YAML:
module.fail_json(msg=missing_required_lib("yaml"), exception=IMP_YAML_ERR) module.fail_json(msg=missing_required_lib("yaml"), exception=IMP_YAML_ERR)
# Validate Helm version >=3.0.0 # Validate Helm version >=3.0.0,<4.0.0
module.validate_helm_version() module.validate_helm_version()
changed = False changed = False
@@ -1159,12 +862,8 @@ def main():
force = module.params.get("force") force = module.params.get("force")
purge = module.params.get("purge") purge = module.params.get("purge")
wait = module.params.get("wait") wait = module.params.get("wait")
wait_for_jobs = module.params.get("wait_for_jobs")
wait_timeout = module.params.get("wait_timeout") wait_timeout = module.params.get("wait_timeout")
atomic = module.params.get("atomic") 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") create_namespace = module.params.get("create_namespace")
post_renderer = module.params.get("post_renderer") post_renderer = module.params.get("post_renderer")
replace = module.params.get("replace") replace = module.params.get("replace")
@@ -1176,9 +875,6 @@ def main():
reset_values = module.params.get("reset_values") reset_values = module.params.get("reset_values")
reset_then_reuse_values = module.params.get("reset_then_reuse_values") reset_then_reuse_values = module.params.get("reset_then_reuse_values")
insecure_skip_tls_verify = module.params.get("insecure_skip_tls_verify") 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")
skip_schema_validation = module.params.get("skip_schema_validation")
if update_repo_cache: if update_repo_cache:
run_repo_update(module) run_repo_update(module)
@@ -1188,33 +884,6 @@ def main():
release_status = get_release_status(module, release_name, all_status=all_status) release_status = get_release_status(module, release_name, all_status=all_status)
helm_cmd = module.get_helm_binary() 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
)
)
if skip_schema_validation:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.16.0"):
module.fail_json(
msg="skip_schema_validation requires helm >= 3.16.0, current version is {0}".format(
helm_version
)
)
opt_result = {} opt_result = {}
if release_state == "absent" and release_status is not None: if release_state == "absent" and release_status is not None:
# skip release statuses 'uninstalled' and 'uninstalling' # skip release statuses 'uninstalled' and 'uninstalling'
@@ -1225,7 +894,8 @@ def main():
if wait: if wait:
helm_version = module.get_helm_version() helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.7.0"): if LooseVersion(helm_version) < LooseVersion("3.7.0"):
module.warn( opt_result["warnings"] = []
opt_result["warnings"].append(
"helm uninstall support option --wait for helm release >= 3.7.0" "helm uninstall support option --wait for helm release >= 3.7.0"
) )
wait = False wait = False
@@ -1235,10 +905,6 @@ def main():
) )
changed = True changed = True
elif release_state == "present": elif release_state == "present":
validate_value_options(
module, replace, reuse_values, reset_values, reset_then_reuse_values
)
if chart_version is not None: if chart_version is not None:
helm_cmd += " --version=" + chart_version helm_cmd += " --version=" + chart_version
@@ -1247,7 +913,7 @@ def main():
# Fetch chart info to have real version and real name for chart_ref from archive, folder or url # Fetch chart info to have real version and real name for chart_ref from archive, folder or url
chart_info = fetch_chart_info( chart_info = fetch_chart_info(
module, helm_cmd, chart_ref, insecure_skip_tls_verify, plain_http module, helm_cmd, chart_ref, insecure_skip_tls_verify
) )
if dependency_update: if dependency_update:
@@ -1292,15 +958,11 @@ def main():
release_values, release_values,
chart_ref, chart_ref,
wait, wait,
wait_for_jobs,
wait_timeout, wait_timeout,
disable_hook, disable_hook,
False, False,
values_files=values_files, values_files=values_files,
atomic=atomic, atomic=atomic,
cleanup_on_fail=cleanup_on_fail,
server_side=server_side,
force_conflicts=force_conflicts,
create_namespace=create_namespace, create_namespace=create_namespace,
post_renderer=post_renderer, post_renderer=post_renderer,
replace=replace, replace=replace,
@@ -1313,29 +975,19 @@ def main():
reset_values=reset_values, reset_values=reset_values,
reset_then_reuse_values=reset_then_reuse_values, reset_then_reuse_values=reset_then_reuse_values,
insecure_skip_tls_verify=insecure_skip_tls_verify, insecure_skip_tls_verify=insecure_skip_tls_verify,
plain_http=plain_http,
take_ownership=take_ownership,
skip_schema_validation=skip_schema_validation,
) )
changed = True changed = True
else: else:
helm_diff_version = get_plugin_version("diff") helm_diff_version = get_plugin_version("diff")
helm_version_compatible = module.is_helm_version_compatible_with_helm_diff( if helm_diff_version and (
helm_diff_version not chart_repo_url
) or (
if ( chart_repo_url
helm_diff_version and LooseVersion(helm_diff_version) >= LooseVersion("3.4.1")
and helm_version_compatible
and (
not chart_repo_url
or (
chart_repo_url
and LooseVersion(helm_diff_version) >= LooseVersion("3.4.1")
)
) )
): ):
would_change, prepared = helmdiff_check( (would_change, prepared) = helmdiff_check(
module, module,
release_name, release_name,
chart_ref, chart_ref,
@@ -1350,23 +1002,14 @@ def main():
reset_values=reset_values, reset_values=reset_values,
reset_then_reuse_values=reset_then_reuse_values, reset_then_reuse_values=reset_then_reuse_values,
insecure_skip_tls_verify=insecure_skip_tls_verify, insecure_skip_tls_verify=insecure_skip_tls_verify,
skip_schema_validation=skip_schema_validation,
) )
if would_change and module._diff: if would_change and module._diff:
opt_result["diff"] = {"prepared": prepared} opt_result["diff"] = {"prepared": prepared}
else: else:
if helm_diff_version and not helm_version_compatible: module.warn(
module.warn( "The default idempotency check can fail to report changes in certain cases. "
"Idempotency checks are currently disabled due to a version mismatch." "Install helm diff >= 3.4.1 for better results."
f" Helm version {module.get_helm_version()} requires helm-diff >= 3.14.0," )
f" but the environment is currently running {helm_diff_version}."
" Please align the plugin versions to restore standard behavior."
)
else:
module.warn(
"The default idempotency check can fail to report changes in certain cases. "
"Install helm diff >= 3.4.1 for better results."
)
would_change = default_check( would_change = default_check(
release_status, chart_info, release_values, values_files release_status, chart_info, release_values, values_files
) )
@@ -1379,15 +1022,11 @@ def main():
release_values, release_values,
chart_ref, chart_ref,
wait, wait,
wait_for_jobs,
wait_timeout, wait_timeout,
disable_hook, disable_hook,
force, force,
values_files=values_files, values_files=values_files,
atomic=atomic, atomic=atomic,
cleanup_on_fail=cleanup_on_fail,
server_side=server_side,
force_conflicts=force_conflicts,
create_namespace=create_namespace, create_namespace=create_namespace,
post_renderer=post_renderer, post_renderer=post_renderer,
replace=replace, replace=replace,
@@ -1400,9 +1039,6 @@ def main():
reset_values=reset_values, reset_values=reset_values,
reset_then_reuse_values=reset_then_reuse_values, reset_then_reuse_values=reset_then_reuse_values,
insecure_skip_tls_verify=insecure_skip_tls_verify, insecure_skip_tls_verify=insecure_skip_tls_verify,
plain_http=plain_http,
take_ownership=take_ownership,
skip_schema_validation=skip_schema_validation,
) )
changed = True changed = True
+4 -12
View File
@@ -20,7 +20,7 @@ author:
- Lucas Boisserie (@LucasBoisserie) - Lucas Boisserie (@LucasBoisserie)
requirements: requirements:
- "helm >= 3.0.0 (https://github.com/helm/helm/releases)" - "helm (https://github.com/helm/helm/releases)"
- "yaml (https://pypi.org/project/PyYAML/)" - "yaml (https://pypi.org/project/PyYAML/)"
description: description:
@@ -119,8 +119,8 @@ status:
returned: always returned: always
description: description:
- Dict of Values used to deploy - Dict of Values used to deploy
- This return value has been deprecated and will be removed in version 8.0.0. - This return value has been deprecated and will be removed in a release after
Use RV(status.release_values) instead. 2027-01-08. Use RV(status.release_values) instead.
release_values: release_values:
type: dict type: dict
returned: always returned: always
@@ -213,14 +213,6 @@ 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["release_values"] = module.get_values(release_name, get_all_values)
release["values"] = release["release_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["manifest"] = module.get_manifest(release_name)
release["notes"] = module.get_notes(release_name) release["notes"] = module.get_notes(release_name)
release["hooks"] = module.get_hooks(release_name) release["hooks"] = module.get_hooks(release_name)
@@ -253,7 +245,7 @@ def main():
if not IMP_YAML: if not IMP_YAML:
module.fail_json(msg=missing_required_lib("yaml"), exception=IMP_YAML_ERR) module.fail_json(msg=missing_required_lib("yaml"), exception=IMP_YAML_ERR)
# Validate Helm version >=3.0.0 # Validate Helm version >=3.0.0,<4.0.0
module.validate_helm_version() module.validate_helm_version()
release_name = module.params.get("release_name") release_name = module.params.get("release_name")
+18 -67
View File
@@ -16,7 +16,7 @@ version_added: 1.0.0
author: author:
- Abhijeet Kasurde (@Akasurde) - Abhijeet Kasurde (@Akasurde)
requirements: requirements:
- "helm >= 3.0.0 (https://github.com/helm/helm/releases)" - "helm (https://github.com/helm/helm/releases)"
description: description:
- Manages Helm plugins. - Manages Helm plugins.
options: options:
@@ -48,22 +48,6 @@ options:
required: false required: false
type: str type: str
version_added: 2.3.0 version_added: 2.3.0
verify:
description:
- Verify the plugin signature before installing.
- This option requires helm version >= 4.0.0
- Used with I(state=present).
type: bool
default: true
version_added: 6.4.0
keyring:
description:
- Location of public keys used for verification.
- Only valid with C(state=present), which maps to the C(helm plugin install) subcommand.
- This option requires helm version >= 4.0.0.
type: path
required: false
version_added: 6.5.0
extends_documentation_fragment: extends_documentation_fragment:
- kubernetes.core.helm_common_options - kubernetes.core.helm_common_options
""" """
@@ -134,9 +118,6 @@ from ansible_collections.kubernetes.core.plugins.module_utils.helm_args_common i
HELM_AUTH_ARG_SPEC, HELM_AUTH_ARG_SPEC,
HELM_AUTH_MUTUALLY_EXCLUSIVE, HELM_AUTH_MUTUALLY_EXCLUSIVE,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.version import (
LooseVersion,
)
def argument_spec(): def argument_spec():
@@ -157,14 +138,6 @@ def argument_spec():
default="present", default="present",
choices=["present", "absent", "latest"], choices=["present", "absent", "latest"],
), ),
verify=dict(
type="bool",
default=True,
),
keyring=dict(
type="path",
required=False,
),
) )
) )
return arg_spec return arg_spec
@@ -188,50 +161,18 @@ def main():
mutually_exclusive=mutually_exclusive(), mutually_exclusive=mutually_exclusive(),
) )
# Validate helm version >= 3.0.0 # Validate Helm version >=3.0.0,<4.0.0
module.validate_helm_version() module.validate_helm_version()
state = module.params.get("state") state = module.params.get("state")
# The ``--keyring`` flag is only supported by the ``install``, ``verify`` and
# ``package`` plugin subcommands. Of those, this module only implements
# ``install`` (state=present); using ``keyring`` with other states emits a
# warning and the option is not passed to Helm.
if module.params.get("keyring") is not None and state != "present":
module.warn(
"The 'keyring' option is only supported with state=present "
"(the 'helm plugin install' subcommand)."
)
helm_cmd_common = module.get_helm_binary() + " plugin" helm_cmd_common = module.get_helm_binary() + " plugin"
if state == "present": if state == "present":
helm_cmd_common += " install %s" % module.params.get("plugin_path") helm_cmd_common += " install %s" % module.params.get("plugin_path")
plugin_version = module.params.get("plugin_version") plugin_version = module.params.get("plugin_version")
verify = module.params.get("verify")
keyring = module.params.get("keyring")
if plugin_version is not None: if plugin_version is not None:
helm_cmd_common += " --version=%s" % plugin_version helm_cmd_common += " --version=%s" % plugin_version
if not verify or keyring is not None:
helm_version = module.get_helm_version()
if not verify:
if LooseVersion(helm_version) < LooseVersion("4.0.0"):
module.warn(
"verify parameter requires helm >= 4.0.0, current version is {0}".format(
helm_version
)
)
else:
helm_cmd_common += " --verify=false"
if keyring is not None:
if LooseVersion(helm_version) < LooseVersion("4.0.0"):
module.warn(
"keyring parameter requires helm >= 4.0.0, current version is {0}".format(
helm_version
)
)
else:
helm_cmd_common += " --keyring=" + keyring
if not module.check_mode: if not module.check_mode:
rc, out, err = module.run_helm_command( rc, out, err = module.run_helm_command(
helm_cmd_common, fails_on_error=False helm_cmd_common, fails_on_error=False
@@ -270,9 +211,9 @@ def main():
elif state == "absent": elif state == "absent":
plugin_name = module.params.get("plugin_name") plugin_name = module.params.get("plugin_name")
rc, output, err, command = module.get_helm_plugin_list() rc, output, err, command = module.get_helm_plugin_list()
plugins = parse_helm_plugin_list(output=output.splitlines()) out = parse_helm_plugin_list(output=output.splitlines())
if not plugins: if not out:
module.exit_json( module.exit_json(
failed=False, failed=False,
changed=False, changed=False,
@@ -283,7 +224,12 @@ def main():
rc=rc, rc=rc,
) )
if all(plugin["name"] != plugin_name for plugin in plugins): found = False
for line in out:
if line[0] == plugin_name:
found = True
break
if not found:
module.exit_json( module.exit_json(
failed=False, failed=False,
changed=False, changed=False,
@@ -321,9 +267,9 @@ def main():
elif state == "latest": elif state == "latest":
plugin_name = module.params.get("plugin_name") plugin_name = module.params.get("plugin_name")
rc, output, err, command = module.get_helm_plugin_list() rc, output, err, command = module.get_helm_plugin_list()
plugins = parse_helm_plugin_list(output=output.splitlines()) out = parse_helm_plugin_list(output=output.splitlines())
if not plugins: if not out:
module.exit_json( module.exit_json(
failed=False, failed=False,
changed=False, changed=False,
@@ -334,7 +280,12 @@ def main():
rc=rc, rc=rc,
) )
if all(plugin["name"] != plugin_name for plugin in plugins): found = False
for line in out:
if line[0] == plugin_name:
found = True
break
if not found:
module.exit_json( module.exit_json(
failed=False, failed=False,
changed=False, changed=False,
+19 -6
View File
@@ -16,7 +16,7 @@ version_added: 1.0.0
author: author:
- Abhijeet Kasurde (@Akasurde) - Abhijeet Kasurde (@Akasurde)
requirements: requirements:
- "helm >= 3.0.0 (https://github.com/helm/helm/releases)" - "helm (https://github.com/helm/helm/releases)"
description: description:
- Gather information about Helm plugins installed in namespace. - Gather information about Helm plugins installed in namespace.
options: options:
@@ -98,16 +98,29 @@ def main():
supports_check_mode=True, supports_check_mode=True,
) )
# Validate helm version >= 3.0.0 # Validate Helm version >=3.0.0,<4.0.0
module.validate_helm_version() module.validate_helm_version()
plugin_name = module.params.get("plugin_name") plugin_name = module.params.get("plugin_name")
plugin_list = []
rc, output, err, command = module.get_helm_plugin_list() rc, output, err, command = module.get_helm_plugin_list()
plugins = parse_helm_plugin_list(output=output.splitlines()) out = parse_helm_plugin_list(output=output.splitlines())
if plugin_name is not None:
plugins = [plugin for plugin in plugins if plugin.get("name") == plugin_name] for line in out:
if plugin_name is None:
plugin_list.append(
{"name": line[0], "version": line[1], "description": line[2]}
)
continue
if plugin_name == line[0]:
plugin_list.append(
{"name": line[0], "version": line[1], "description": line[2]}
)
break
module.exit_json( module.exit_json(
changed=True, changed=True,
@@ -115,7 +128,7 @@ def main():
stdout=output, stdout=output,
stderr=err, stderr=err,
rc=rc, rc=rc,
plugin_list=plugins, plugin_list=plugin_list,
) )
+2 -12
View File
@@ -21,7 +21,7 @@ description:
- There are options for unpacking the chart after download. - There are options for unpacking the chart after download.
requirements: requirements:
- "helm >= 3.0.0 (https://github.com/helm/helm/releases)" - "helm >= 3.0, <4.0.0 (https://github.com/helm/helm/releases)"
options: options:
chart_ref: chart_ref:
@@ -122,13 +122,6 @@ options:
- The path of a helm binary to use. - The path of a helm binary to use.
required: false required: false
type: path 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""" EXAMPLES = r"""
@@ -360,7 +353,6 @@ def main():
chart_ssl_cert_file=dict(type="path"), chart_ssl_cert_file=dict(type="path"),
chart_ssl_key_file=dict(type="path"), chart_ssl_key_file=dict(type="path"),
binary_path=dict(type="path"), binary_path=dict(type="path"),
plain_http=dict(type="bool", default=False),
) )
module = AnsibleHelmModule( module = AnsibleHelmModule(
argument_spec=argspec, argument_spec=argspec,
@@ -372,7 +364,7 @@ def main():
mutually_exclusive=[("chart_version", "chart_devel")], mutually_exclusive=[("chart_version", "chart_devel")],
) )
# Validate Helm version >=3.0.0 # Validate Helm version >=3.0.0,<4.0.0
module.validate_helm_version() module.validate_helm_version()
helm_version = module.get_helm_version() helm_version = module.get_helm_version()
@@ -382,7 +374,6 @@ def main():
chart_ca_cert="3.1.0", chart_ca_cert="3.1.0",
chart_ssl_cert_file="3.1.0", chart_ssl_cert_file="3.1.0",
chart_ssl_key_file="3.1.0", chart_ssl_key_file="3.1.0",
plain_http="3.13.0",
) )
def test_version_requirement(opt): def test_version_requirement(opt):
@@ -422,7 +413,6 @@ def main():
skip_tls_certs_check=dict(key="insecure-skip-tls-verify"), skip_tls_certs_check=dict(key="insecure-skip-tls-verify"),
chart_devel=dict(key="devel"), chart_devel=dict(key="devel"),
untar_chart=dict(key="untar"), untar_chart=dict(key="untar"),
plain_http=dict(key="plain-http"),
) )
for k, v in helm_flag_args.items(): for k, v in helm_flag_args.items():
+10 -48
View File
@@ -20,7 +20,7 @@ author:
- Yuriy Novostavskiy (@yurnov) - Yuriy Novostavskiy (@yurnov)
requirements: requirements:
- "helm (https://github.com/helm/helm/releases) >= 3.8.0" - "helm (https://github.com/helm/helm/releases) >= 3.8.0, <4.0.0"
description: description:
- Helm registry authentication module allows you to login C(helm registry login) and logout C(helm registry logout) from a Helm registry. - Helm registry authentication module allows you to login C(helm registry login) and logout C(helm registry logout) from a Helm registry.
@@ -75,14 +75,6 @@ options:
- Path to the CA certificate SSL file for verify registry server certificate. - Path to the CA certificate SSL file for verify registry server certificate.
required: false required: false
type: path type: path
plain_http:
description:
- Use insecure HTTP connections for C(helm registry login).
- Requires Helm >= 3.18.0
required: false
type: bool
default: False
version_added: 6.4.0
binary_path: binary_path:
description: description:
- The path of a helm binary to use. - The path of a helm binary to use.
@@ -106,23 +98,17 @@ EXAMPLES = r"""
RETURN = r""" RETURN = r"""
stdout: stdout:
type: str type: str
description: description: Full C(helm) command stdout, in case you want to display it or examine the event log
- Full C(helm) command stdout, in case you want to display it or examine the event log.
- As of Helm 4.2.1 success messages such as C(Login Succeeded) are printed to stdout
(see U(https://github.com/helm/helm/pull/32056)). On earlier versions they are printed to stderr.
returned: always returned: always
sample: 'Login Succeeded\n' stout_lines:
stdout_lines:
type: list type: list
description: Full C(helm) command stdout, in case you want to display it or examine the event log description: Full C(helm) command stdout, in case you want to display it or examine the event log
returned: always returned: always
stderr: stderr:
type: str type: str
description: description: >-
- Full C(helm) command stderr, in case you want to display it or examine the event log. Full C(helm) command stderr, in case you want to display it or examine the event log.
- Please note that the helm binary may print messages to stderr even if the command is successful. Please be note that helm binnary may print messages to stderr even if the command is successful.
- On Helm versions earlier than 4.2.1, success messages such as C(Login Succeeded) are printed
here; as of Helm 4.2.1 they are printed to stdout (see U(https://github.com/helm/helm/pull/32056)).
returned: always returned: always
sample: 'Login Succeeded\n' sample: 'Login Succeeded\n'
stderr_lines: stderr_lines:
@@ -162,7 +148,6 @@ def arg_spec():
key_file=dict(type="path", required=False), key_file=dict(type="path", required=False),
cert_file=dict(type="path", required=False), cert_file=dict(type="path", required=False),
ca_file=dict(type="path", required=False), ca_file=dict(type="path", required=False),
plain_http=dict(type="bool", default=False),
) )
@@ -175,7 +160,6 @@ def login(
key_file, key_file,
cert_file, cert_file,
ca_file, ca_file,
plain_http,
): ):
login_command = command + " registry login " + host login_command = command + " registry login " + host
@@ -193,8 +177,6 @@ def login(
if ca_file is not None: if ca_file is not None:
login_command += " --ca-file=" + ca_file login_command += " --ca-file=" + ca_file
if plain_http:
login_command += " --plain-http"
return login_command return login_command
@@ -212,8 +194,8 @@ def main():
supports_check_mode=True, supports_check_mode=True,
) )
# Validate Helm version >=3.8.0 # Validate Helm version >=3.0.0,<4.0.0
module.validate_helm_version(version="3.8.0") module.validate_helm_version()
changed = False changed = False
@@ -225,19 +207,6 @@ def main():
key_file = module.params.get("key_file") key_file = module.params.get("key_file")
cert_file = module.params.get("cert_file") cert_file = module.params.get("cert_file")
ca_file = module.params.get("ca_file") ca_file = module.params.get("ca_file")
plain_http = module.params.get("plain_http")
helm_version = module.get_helm_version()
if plain_http:
if LooseVersion(helm_version) < LooseVersion("3.18.0"):
module.warn(
"plain_http option requires helm >= 3.18.0, current version is {0}".format(
helm_version
)
)
# reset option
plain_http = False
helm_cmd = module.get_helm_binary() helm_cmd = module.get_helm_binary()
@@ -246,15 +215,7 @@ def main():
changed = True changed = True
elif state == "present": elif state == "present":
helm_cmd = login( helm_cmd = login(
helm_cmd, helm_cmd, host, insecure, username, password, key_file, cert_file, ca_file
host,
insecure,
username,
password,
key_file,
cert_file,
ca_file,
plain_http,
) )
changed = True changed = True
@@ -277,6 +238,7 @@ def main():
command=helm_cmd, command=helm_cmd,
) )
helm_version = module.get_helm_version()
if LooseVersion(helm_version) >= LooseVersion("3.18.0") and state == "absent": if LooseVersion(helm_version) >= LooseVersion("3.18.0") and state == "absent":
# https://github.com/ansible-collections/kubernetes.core/issues/944 # https://github.com/ansible-collections/kubernetes.core/issues/944
module.warn( module.warn(
+3 -3
View File
@@ -20,7 +20,7 @@ author:
- Lucas Boisserie (@LucasBoisserie) - Lucas Boisserie (@LucasBoisserie)
requirements: requirements:
- "helm >= 3.0.0 (https://github.com/helm/helm/releases)" - "helm (https://github.com/helm/helm/releases)"
- "yaml (https://pypi.org/project/PyYAML/)" - "yaml (https://pypi.org/project/PyYAML/)"
description: description:
@@ -295,7 +295,7 @@ def main():
if not IMP_YAML: if not IMP_YAML:
module.fail_json(msg=missing_required_lib("yaml"), exception=IMP_YAML_ERR) module.fail_json(msg=missing_required_lib("yaml"), exception=IMP_YAML_ERR)
# Validate Helm version >= 3.0.0 # Validate Helm version >=3.0.0,<4.0.0
module.validate_helm_version() module.validate_helm_version()
changed = False changed = False
@@ -331,7 +331,7 @@ def main():
insecure_skip_tls_verify, insecure_skip_tls_verify,
) )
changed = True changed = True
elif repository_status["url"].rstrip("/") != repo_url: elif repository_status["url"] != repo_url:
module.fail_json( module.fail_json(
msg="Repository already have a repository named {0}".format(repo_name) msg="Repository already have a repository named {0}".format(repo_name)
) )
+1 -35
View File
@@ -21,10 +21,6 @@ author:
description: description:
- Render chart templates to an output directory or as text of concatenated yaml documents. - Render chart templates to an output directory or as text of concatenated yaml documents.
requirements:
- "helm >= 3.0.0 (https://github.com/helm/helm/releases)"
- "yaml (https://pypi.org/project/PyYAML/)"
options: options:
binary_path: binary_path:
description: description:
@@ -151,13 +147,6 @@ options:
- json - json
- file - file
version_added: 2.4.0 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""" EXAMPLES = r"""
@@ -228,10 +217,6 @@ except ImportError:
from ansible.module_utils.basic import missing_required_lib from ansible.module_utils.basic import missing_required_lib
from ansible_collections.kubernetes.core.plugins.module_utils.helm import ( from ansible_collections.kubernetes.core.plugins.module_utils.helm import (
AnsibleHelmModule, AnsibleHelmModule,
strip_registry_progress,
)
from ansible_collections.kubernetes.core.plugins.module_utils.version import (
LooseVersion,
) )
@@ -251,7 +236,6 @@ def template(
values_files=None, values_files=None,
include_crds=False, include_crds=False,
set_values=None, set_values=None,
plain_http=False,
): ):
cmd += " template " cmd += " template "
@@ -278,9 +262,6 @@ def template(
if insecure_registry: if insecure_registry:
cmd += " --insecure-skip-tls-verify" cmd += " --insecure-skip-tls-verify"
if plain_http:
cmd += " --plain-http"
if show_only: if show_only:
for template in show_only: for template in show_only:
cmd += " -s " + template cmd += " -s " + template
@@ -326,7 +307,6 @@ def main():
values_files=dict(type="list", default=[], elements="str"), values_files=dict(type="list", default=[], elements="str"),
update_repo_cache=dict(type="bool", default=False), update_repo_cache=dict(type="bool", default=False),
set_values=dict(type="list", elements="dict"), set_values=dict(type="list", elements="dict"),
plain_http=dict(type="bool", default=False),
), ),
supports_check_mode=True, supports_check_mode=True,
) )
@@ -347,25 +327,15 @@ def main():
values_files = module.params.get("values_files") values_files = module.params.get("values_files")
update_repo_cache = module.params.get("update_repo_cache") update_repo_cache = module.params.get("update_repo_cache")
set_values = module.params.get("set_values") set_values = module.params.get("set_values")
plain_http = module.params.get("plain_http")
if not IMP_YAML: if not IMP_YAML:
module.fail_json(msg=missing_required_lib("yaml"), exception=IMP_YAML_ERR) module.fail_json(msg=missing_required_lib("yaml"), exception=IMP_YAML_ERR)
# Validate Helm version >=3.0.0 # Validate Helm version >=3.0.0,<4.0.0
module.validate_helm_version() module.validate_helm_version()
helm_cmd = module.get_helm_binary() 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: if update_repo_cache:
update_cmd = helm_cmd + " repo update" update_cmd = helm_cmd + " repo update"
module.run_helm_command(update_cmd) module.run_helm_command(update_cmd)
@@ -390,14 +360,10 @@ def main():
values_files=values_files, values_files=values_files,
include_crds=include_crds, include_crds=include_crds,
set_values=set_values_args, set_values=set_values_args,
plain_http=plain_http,
) )
if not check_mode: if not check_mode:
rc, out, err = module.run_helm_command(tmpl_cmd) 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: else:
out = err = "" out = err = ""
rc = 0 rc = 0
+3 -2
View File
@@ -40,8 +40,9 @@ options:
state: state:
description: description:
- Determines if an object should be created, patched, or deleted. When set to C(present), an object will be - Determines if an object should be created, patched, or deleted. When set to C(present), an object will be
created if it does not already exist, and an existing object will be patched if its attributes differ from created, if it does not already exist. If set to C(absent), an existing object will be deleted. If set to
those specified using I(resource_definition) or I(src). If set to C(absent), an existing object will be deleted. C(present), an existing object will be patched, if its attributes differ from those specified using
I(resource_definition) or I(src).
- C(patched) state is an existing resource that has a given patch applied. If the resource doesn't exist, silently skip it (do not raise an error). - C(patched) state is an existing resource that has a given patch applied. If the resource doesn't exist, silently skip it (do not raise an error).
type: str type: str
default: present default: present
+1 -14
View File
@@ -76,21 +76,9 @@ options:
- This option is ignored when I(content) is set or when I(state) is set to C(from_pod). - This option is ignored when I(content) is set or when I(state) is set to C(from_pod).
type: bool type: bool
default: False 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: notes:
- the tar binary is required on the container when copying from local filesystem to pod. - 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. - the (init) container has to be started before you copy files or directories to it.
""" """
@@ -152,7 +140,7 @@ result:
import copy import copy
from ansible.module_utils.common.text.converters import to_native from ansible.module_utils._text import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import ( from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
AnsibleModule, AnsibleModule,
) )
@@ -192,7 +180,6 @@ def argspec():
"choices": ["to_pod", "from_pod"], "choices": ["to_pod", "from_pod"],
} }
argument_spec["no_preserve"] = {"type": "bool", "default": False} argument_spec["no_preserve"] = {"type": "bool", "default": False}
argument_spec["copy_timeout"] = {"type": "int", "default": 300}
return argument_spec return argument_spec
+37 -47
View File
@@ -149,7 +149,7 @@ import time
import traceback import traceback
from datetime import datetime from datetime import datetime
from ansible.module_utils.common.text.converters import to_native from ansible.module_utils._text import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import ( from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
AnsibleModule, AnsibleModule,
) )
@@ -230,7 +230,7 @@ def filter_pods(pods, force, ignore_daemonset, delete_emptydir_data):
else: else:
to_delete.append((pod.metadata.namespace, pod.metadata.name)) to_delete.append((pod.metadata.namespace, pod.metadata.name))
warnings, errors, info = [], [], [] warnings, errors = [], []
if unmanaged: if unmanaged:
pod_names = ",".join([pod[0] + "/" + pod[1] for pod in unmanaged]) pod_names = ",".join([pod[0] + "/" + pod[1] for pod in unmanaged])
if not force: if not force:
@@ -242,7 +242,7 @@ def filter_pods(pods, force, ignore_daemonset, delete_emptydir_data):
) )
else: else:
# Pod not managed will be deleted as 'force' is true # Pod not managed will be deleted as 'force' is true
info.append( warnings.append(
"Deleting Pods not managed by ReplicationController, ReplicaSet, Job, DaemonSet or StatefulSet: {0}.".format( "Deleting Pods not managed by ReplicationController, ReplicaSet, Job, DaemonSet or StatefulSet: {0}.".format(
pod_names pod_names
) )
@@ -264,7 +264,7 @@ def filter_pods(pods, force, ignore_daemonset, delete_emptydir_data):
"cannot delete Pods with local storage: {0}.".format(pod_names) "cannot delete Pods with local storage: {0}.".format(pod_names)
) )
else: else:
info.append("Deleting Pods with local storage: {0}.".format(pod_names)) warnings.append("Deleting Pods with local storage: {0}.".format(pod_names))
for pod in localStorage: for pod in localStorage:
to_delete.append((pod[0], pod[1])) to_delete.append((pod[0], pod[1]))
@@ -278,8 +278,8 @@ def filter_pods(pods, force, ignore_daemonset, delete_emptydir_data):
) )
) )
else: else:
info.append("Ignoring DaemonSet-managed Pods: {0}.".format(pod_names)) warnings.append("Ignoring DaemonSet-managed Pods: {0}.".format(pod_names))
return to_delete, warnings, errors, info return to_delete, warnings, errors
class K8sDrainAnsible(object): class K8sDrainAnsible(object):
@@ -334,19 +334,18 @@ class K8sDrainAnsible(object):
def evict_pods(self, pods): def evict_pods(self, pods):
for namespace, name in pods: for namespace, name in pods:
try: try:
if not self._module.check_mode: if self._drain_options.get("disable_eviction"):
if self._drain_options.get("disable_eviction"): self._api_instance.delete_namespaced_pod(
self._api_instance.delete_namespaced_pod( name=name, namespace=namespace, body=self._delete_options
name=name, namespace=namespace, body=self._delete_options )
) else:
else: body = v1_eviction(
body = v1_eviction( delete_options=self._delete_options,
delete_options=self._delete_options, metadata=V1ObjectMeta(name=name, namespace=namespace),
metadata=V1ObjectMeta(name=name, namespace=namespace), )
) self._api_instance.create_namespaced_pod_eviction(
self._api_instance.create_namespaced_pod_eviction( name=name, namespace=namespace, body=body
name=name, namespace=namespace, body=body )
)
self._changed = True self._changed = True
except ApiException as exc: except ApiException as exc:
if exc.reason != "Not Found": if exc.reason != "Not Found":
@@ -363,7 +362,11 @@ class K8sDrainAnsible(object):
) )
def list_pods(self): def list_pods(self):
params = {"field_selector": "spec.nodeName=" + self._module.params.get("name")} params = {
"field_selector": "spec.nodeName={name}".format(
name=self._module.params.get("name")
)
}
pod_selectors = self._module.params.get("pod_selectors") pod_selectors = self._module.params.get("pod_selectors")
if pod_selectors: if pod_selectors:
params["label_selector"] = ",".join(pod_selectors) params["label_selector"] = ",".join(pod_selectors)
@@ -373,8 +376,7 @@ class K8sDrainAnsible(object):
# Mark node as unschedulable # Mark node as unschedulable
result = [] result = []
if not node_unschedulable: if not node_unschedulable:
if not self._module.check_mode: self.patch_node(unschedulable=True)
self.patch_node(unschedulable=True)
result.append( result.append(
"node {0} marked unschedulable.".format(self._module.params.get("name")) "node {0} marked unschedulable.".format(self._module.params.get("name"))
) )
@@ -389,8 +391,7 @@ class K8sDrainAnsible(object):
def _revert_node_patch(): def _revert_node_patch():
if self._changed: if self._changed:
self._changed = False self._changed = False
if not self._module.check_mode: self.patch_node(unschedulable=False)
self.patch_node(unschedulable=False)
try: try:
pod_list = self.list_pods() pod_list = self.list_pods()
@@ -400,7 +401,7 @@ class K8sDrainAnsible(object):
delete_emptydir_data = self._drain_options.get( delete_emptydir_data = self._drain_options.get(
"delete_emptydir_data", False "delete_emptydir_data", False
) )
pods, warnings, errors, info = filter_pods( pods, warnings, errors = filter_pods(
pod_list.items, force, ignore_daemonset, delete_emptydir_data pod_list.items, force, ignore_daemonset, delete_emptydir_data
) )
if errors: if errors:
@@ -430,25 +431,18 @@ class K8sDrainAnsible(object):
if pods: if pods:
self.evict_pods(pods) self.evict_pods(pods)
number_pod = len(pods) number_pod = len(pods)
if self._module.check_mode: if self._drain_options.get("wait_timeout") is not None:
result.append( warn = self.wait_for_pod_deletion(
"Would have deleted {0} Pod(s) from node if not in check mode.".format( pods,
number_pod self._drain_options.get("wait_timeout"),
) self._drain_options.get("wait_sleep"),
) )
else: if warn:
wait_timeout = self._drain_options.get("wait_timeout") warnings.append(warn)
wait_sleep = self._drain_options.get("wait_sleep") result.append("{0} Pod(s) deleted from node.".format(number_pod))
if wait_timeout is not None:
warn = self.wait_for_pod_deletion(pods, wait_timeout, wait_sleep)
if warn:
warnings.append(warn)
result.append("{0} Pod(s) deleted from node.".format(number_pod))
if warnings: if warnings:
for warning in warnings: for warning in warnings:
self._module.warn(warning) self._module.warn(warning)
for line in info:
self._module.debug(line)
return dict(result=" ".join(result)) return dict(result=" ".join(result))
def patch_node(self, unschedulable): def patch_node(self, unschedulable):
@@ -489,8 +483,7 @@ class K8sDrainAnsible(object):
self._module.exit_json( self._module.exit_json(
result="node {0} already marked unschedulable.".format(name) result="node {0} already marked unschedulable.".format(name)
) )
if not self._module.check_mode: self.patch_node(unschedulable=True)
self.patch_node(unschedulable=True)
result["result"] = "node {0} marked unschedulable.".format(name) result["result"] = "node {0} marked unschedulable.".format(name)
self._changed = True self._changed = True
@@ -499,8 +492,7 @@ class K8sDrainAnsible(object):
self._module.exit_json( self._module.exit_json(
result="node {0} already marked schedulable.".format(name) result="node {0} already marked schedulable.".format(name)
) )
if not self._module.check_mode: self.patch_node(unschedulable=False)
self.patch_node(unschedulable=False)
result["result"] = "node {0} marked schedulable.".format(name) result["result"] = "node {0} marked schedulable.".format(name)
self._changed = True self._changed = True
@@ -543,9 +535,7 @@ def argspec():
def main(): def main():
module = AnsibleK8SModule( module = AnsibleK8SModule(module_class=AnsibleModule, argument_spec=argspec())
module_class=AnsibleModule, argument_spec=argspec(), supports_check_mode=True
)
if not HAS_EVICTION_API: if not HAS_EVICTION_API:
module.fail_json( module.fail_json(
+2 -9
View File
@@ -118,7 +118,7 @@ result:
type: int type: int
version_added: 2.2.0 version_added: 2.2.0
return_code: return_code:
description: The command status code. This attribute is deprecated and will be removed in version 7.0.0. Use RV(result.rc) instead. description: The command status code. This attribute is deprecated and will be removed in a future release. Please use rc instead.
type: int type: int
""" """
@@ -131,7 +131,7 @@ except ImportError:
# ImportError are managed by the common module already. # ImportError are managed by the common module already.
pass pass
from ansible.module_utils.common.text.converters import to_native from ansible.module_utils._text import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import ( from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
AnsibleModule, AnsibleModule,
) )
@@ -219,13 +219,6 @@ def execute_module(module, client):
else: else:
rc = int(err["details"]["causes"][0]["message"]) 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( module.exit_json(
# Some command might change environment, but ultimately failing at end # Some command might change environment, but ultimately failing at end
changed=True, changed=True,
+10 -40
View File
@@ -53,15 +53,6 @@ options:
type: list type: list
elements: str elements: str
version_added: 3.0.0 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: extends_documentation_fragment:
- kubernetes.core.k8s_auth_options - kubernetes.core.k8s_auth_options
@@ -144,12 +135,6 @@ EXAMPLES = r"""
(ocp_bootstrap_status.resources[0].data.status == 'complete') (ocp_bootstrap_status.resources[0].data.status == 'complete')
retries: 60 retries: 60
delay: 15 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""" RETURN = r"""
@@ -194,8 +179,6 @@ from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule impo
) )
from ansible_collections.kubernetes.core.plugins.module_utils.args_common import ( from ansible_collections.kubernetes.core.plugins.module_utils.args_common import (
AUTH_ARG_SPEC, AUTH_ARG_SPEC,
METADATA_ONLY_HEADER_VALUES,
METADATA_ONLY_HEADERS_SPEC,
WAIT_ARG_SPEC, WAIT_ARG_SPEC,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
@@ -233,16 +216,15 @@ def argspec():
args = copy.deepcopy(AUTH_ARG_SPEC) args = copy.deepcopy(AUTH_ARG_SPEC)
args.update(WAIT_ARG_SPEC) args.update(WAIT_ARG_SPEC)
args.update( args.update(
{ dict(
"kind": {"required": True}, kind=dict(required=True),
"api_version": {"default": "v1", "aliases": ["api", "version"]}, api_version=dict(default="v1", aliases=["api", "version"]),
"name": {}, name=dict(),
"namespace": {}, namespace=dict(),
"label_selectors": {"type": "list", "elements": "str", "default": []}, label_selectors=dict(type="list", elements="str", default=[]),
"field_selectors": {"type": "list", "elements": "str", "default": []}, field_selectors=dict(type="list", elements="str", default=[]),
"hidden_fields": {"type": "list", "elements": "str"}, hidden_fields=dict(type="list", elements="str"),
"metadata_only": {"type": "bool", "default": False}, )
}
) )
return args return args
@@ -251,20 +233,8 @@ def main():
module = AnsibleK8SModule( module = AnsibleK8SModule(
module_class=AnsibleModule, argument_spec=argspec(), supports_check_mode=True 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: try:
client = get_api_client(module, **metadata_only_headers) client = get_api_client(module)
svc = K8sService(client, module) svc = K8sService(client, module)
execute_module(module, svc) execute_module(module, svc)
except CoreException as e: except CoreException as e:
+3 -14
View File
@@ -33,14 +33,6 @@ options:
aliases: aliases:
- api - api
- version - 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: kind:
description: description:
- Use to specify an object model. - Use to specify an object model.
@@ -135,8 +127,8 @@ error:
import copy import copy
import traceback import traceback
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import missing_required_lib from ansible.module_utils.basic import missing_required_lib
from ansible.module_utils.common.text.converters import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import ( from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
AnsibleModule, AnsibleModule,
) )
@@ -155,7 +147,6 @@ from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions imp
) )
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.service import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.service import (
diff_objects, diff_objects,
hide_fields,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.waiter import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.waiter import (
get_waiter, get_waiter,
@@ -183,7 +174,6 @@ JSON_PATCH_ARGS = {
"namespace": {"type": "str"}, "namespace": {"type": "str"},
"name": {"type": "str", "required": True}, "name": {"type": "str", "required": True},
"patch": {"type": "list", "required": True, "elements": "dict"}, "patch": {"type": "list", "required": True, "elements": "dict"},
"hidden_fields": {"type": "list", "elements": "str", "default": []},
} }
@@ -213,7 +203,6 @@ def execute_module(module, client):
namespace = module.params.get("namespace") namespace = module.params.get("namespace")
patch = module.params.get("patch") patch = module.params.get("patch")
hidden_fields = module.params.get("hidden_fields")
wait = module.params.get("wait") wait = module.params.get("wait")
wait_sleep = module.params.get("wait_sleep") wait_sleep = module.params.get("wait_sleep")
wait_timeout = module.params.get("wait_timeout") wait_timeout = module.params.get("wait_timeout")
@@ -271,13 +260,13 @@ def execute_module(module, client):
module.fail_json(msg=msg, error=to_native(exc), status="", reason="") module.fail_json(msg=msg, error=to_native(exc), status="", reason="")
success = True success = True
result = {"result": hide_fields(obj, hidden_fields)} result = {"result": obj}
if wait and not module.check_mode: if wait and not module.check_mode:
waiter = get_waiter(client, resource, condition=wait_condition) waiter = get_waiter(client, resource, condition=wait_condition)
success, result["result"], result["duration"] = waiter.wait( success, result["result"], result["duration"] = waiter.wait(
wait_timeout, wait_sleep, name, namespace wait_timeout, wait_sleep, name, namespace
) )
match, diffs = diff_objects(existing.to_dict(), obj, hidden_fields) match, diffs = diff_objects(existing.to_dict(), obj)
result["changed"] = not match result["changed"] = not match
if module._diff: if module._diff:
result["diff"] = diffs result["diff"] = diffs
+1 -1
View File
@@ -149,7 +149,7 @@ except ImportError:
# Handled in module setup # Handled in module setup
pass pass
from ansible.module_utils.common.text.converters import to_native from ansible.module_utils._text import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import ( from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
AnsibleModule, AnsibleModule,
) )
-10
View File
@@ -36,7 +36,6 @@ options:
- If more than one C(merge_type) is given, the merge_types will be tried in order - 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 - 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. 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: choices:
- json - json
- merge - merge
@@ -252,15 +251,6 @@ def main():
supports_check_mode=True, 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: try:
client = get_api_client(module=module) client = get_api_client(module=module)
svc = K8sService(client, module) svc = K8sService(client, module)
+1 -1
View File
@@ -126,7 +126,7 @@ result:
import copy import copy
from ansible.module_utils.common.text.converters import to_native from ansible.module_utils._text import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import ( from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
AnsibleModule, AnsibleModule,
) )
-490
View File
@@ -1,490 +0,0 @@
#!/usr/bin/python
#
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r"""
---
module: kubeconfig
short_description: Generate, update, and optionally write Kubernetes kubeconfig files
version_added: "6.5.0"
author: "Youssef Khalid Ali (@YoussefKhalidAli)"
description:
- Build, update, and manage Kubernetes kubeconfig files using structured input.
- Supports loading an existing kubeconfig file and merging clusters, users, and contexts.
- Can optionally write the resulting kubeconfig to a destination path.
- Ensures idempotent behavior by only updating files when changes occur.
requirements:
- "PyYAML >= 5.1"
notes:
- Input data is merged by resource name (cluster, user, context).
- Updates under O(clusters), O(users), and O(contexts) are matched by C(name) against the kubeconfig loaded from O(path).
- For an existing C(name), each entry's C(behavior) suboption controls the update.
- The default is V(merge), which merges nested C(cluster), C(user), and C(context) data so unspecified keys are preserved.
- With V(replace), the previous entry for that name is dropped and only the new definition is used.
- With V(keep), the existing entry is left unchanged.
- With V(remove), the existing entry is deleted from the kubeconfig entirely. If no entry with that name exists, the operation is silently skipped.
- This can be used to move kubeconfig files to a different location with different content.
- This module does not validate cluster connectivity or authentication.
- The module supports C(check_mode) and will not write files when enabled.
- The structure follows standard Kubernetes kubeconfig format as defined in the Kubernetes documentation.
- Tokens and sensitive data should be protected using ansible-vault or environment variables.
options:
path:
description:
- Path to an existing kubeconfig file to load and merge from.
- If the file does not exist, a new kubeconfig will be created.
- This becomes the default destination if O(dest) is not specified.
type: str
required: true
dest:
description:
- Destination path where the final kubeconfig should be written.
- If not specified, the kubeconfig will be saved to O(path).
- Allows copying and modifying a kubeconfig to a new location.
type: str
required: false
clusters:
description:
- List of cluster definitions to merge into the kubeconfig.
- Each cluster is identified by its C(name).
- When C(name) matches an existing cluster, the default C(behavior) is V(merge).
- See the C(behavior) suboption for V(replace), V(keep), and V(remove).
type: list
elements: dict
required: false
default: []
suboptions:
name:
description:
- Unique name identifier for the cluster.
type: str
required: true
behavior:
description:
- How to handle merging if a cluster with this name already exists.
- C(merge) - Update only the specified fields, preserve others (default).
- C(replace) - Replace the entire cluster definition.
- C(keep) - Keep existing cluster, skip this entry.
- C(remove) - Remove the cluster entry entirely. Silently skipped if the entry does not exist.
type: str
choices: ['merge', 'replace', 'keep', 'remove']
default: merge
cluster:
description:
- Cluster configuration details.
- Not required when C(behavior) is V(remove).
type: dict
suboptions:
server:
description:
- Kubernetes API server URL (e.g., C(https://k8s.example.com:6443)).
type: str
required: true
certificate-authority:
description:
- Path to a CA certificate file for validating the API server certificate.
type: str
certificate-authority-data:
description:
- Base64 encoded CA certificate data.
- Use this instead of C(certificate-authority) for embedded certificates.
type: str
insecure-skip-tls-verify:
description:
- If true, the server's certificate will not be validated.
type: bool
proxy-url:
description:
- Optional proxy URL for cluster connections.
type: str
tls-server-name:
description:
- Server name to use for server certificate validation.
type: str
users:
description:
- List of user authentication configurations.
- Each user is identified by its C(name).
- When C(name) matches an existing user, the default C(behavior) is V(merge).
- See the C(behavior) suboption for V(replace), V(keep), and V(remove).
type: list
elements: dict
required: false
default: []
suboptions:
name:
description:
- Unique name identifier for the user.
type: str
required: true
behavior:
description:
- How to handle merging if a user with this name already exists.
- C(merge) - Update only the specified fields, preserve others (default).
- C(replace) - Replace the entire user definition.
- C(keep) - Keep existing user, skip this entry.
- C(remove) - Remove the user entry entirely. Silently skipped if the entry does not exist.
type: str
choices: ['merge', 'replace', 'keep', 'remove']
default: merge
user:
description:
- User authentication configuration.
- Not required when C(behavior) is V(remove).
type: dict
suboptions:
token:
description:
- Bearer token for authentication.
type: str
username:
description:
- Username for basic authentication.
type: str
password:
description:
- Password for basic authentication.
type: str
client-certificate:
description:
- Path to client certificate file.
- Used for certificate-based authentication.
type: str
client-key:
description:
- Path to client private key file.
- Must be provided with C(client-certificate).
type: str
client-certificate-data:
description:
- Base64 encoded client certificate.
- Use instead of C(client-certificate) for embedded certificates.
type: str
client-key-data:
description:
- Base64 encoded client private key.
- Use instead of C(client-key) for embedded keys.
type: str
auth-provider:
description:
- Authentication provider configuration (e.g., for GCP, Azure).
type: dict
exec:
description:
- Exec-based credential plugin configuration.
- Used for external authentication providers.
type: dict
contexts:
description:
- List of context definitions linking users and clusters.
- Each context is identified by its C(name).
- When C(name) matches an existing context, the default C(behavior) is V(merge).
- See the C(behavior) suboption for V(replace), V(keep), and V(remove).
type: list
elements: dict
required: false
default: []
suboptions:
name:
description:
- Unique name identifier for the context.
type: str
required: true
behavior:
description:
- How to handle merging if a context with this name already exists.
- C(merge) - Update only the specified fields, preserve others (default).
- C(replace) - Replace the entire context definition.
- C(keep) - Keep existing context, skip this entry.
- C(remove) - Remove the context entry entirely. Silently skipped if the entry does not exist.
type: str
choices: ['merge', 'replace', 'keep', 'remove']
default: merge
context:
description:
- Context configuration linking cluster and user.
- Not required when C(behavior) is V(remove).
type: dict
suboptions:
cluster:
description:
- Name of the cluster to use (must match a cluster name in O(clusters)).
type: str
required: true
user:
description:
- Name of the user to authenticate as (must match a user name in O(users)).
type: str
required: true
namespace:
description:
- Default namespace to use for this context.
- If not specified, defaults to C(default).
type: str
preferences:
description:
- Kubeconfig preferences.
- Used for client-side settings like color output, default editor, etc.
type: dict
required: false
default: {}
current_context:
description:
- Name of the context to set as current/active.
- This context will be used by default when using kubectl.
- Must match one of the context names defined in O(contexts).
type: str
required: false
seealso:
- name: Kubernetes kubeconfig documentation
description: Official Kubernetes documentation for kubeconfig files
link: https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/
- name: kubectl config documentation
description: kubectl commands for working with kubeconfig files
link: https://kubernetes.io/docs/reference/kubectl/generated/kubectl_config/
"""
EXAMPLES = r"""
# Create a new kubeconfig file with a single cluster
- name: Create basic kubeconfig
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
clusters:
- name: production-cluster
cluster:
server: https://prod.k8s.example.com:6443
certificate-authority-data: LS0tLS1CRUdJTi...
users:
- name: admin-user
user:
token: eyJhbGciOiJSUzI1NiIsImtpZCI6IiJ9...
contexts:
- name: prod-admin
context:
cluster: production-cluster
user: admin-user
namespace: production
current_context: prod-admin
- name: Add a second cluster to an existing kubeconfig without touching other entries
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
clusters:
- name: staging-cluster
cluster:
server: https://staging.k8s.example.com:6443
insecure-skip-tls-verify: true
users:
- name: staging-user
user:
client-certificate: /path/to/staging.crt
client-key: /path/to/staging.key
contexts:
- name: staging-admin
context:
cluster: staging-cluster
user: staging-user
namespace: staging
- name: Update only the token for an existing user, preserving all other user fields
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
users:
- name: admin-user
behavior: merge
user:
token: "{{ new_admin_token }}"
- name: Replace a cluster definition entirely.
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
clusters:
- name: production-cluster
behavior: replace
cluster:
server: https://new-prod.k8s.example.com:6443
certificate-authority-data: LS0tLS1CRUdJTi...
- name: Remove a decommissioned cluster, user, and context
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
clusters:
- name: old-cluster
behavior: remove
users:
- name: old-user
behavior: remove
contexts:
- name: old-context
behavior: remove
- name: Switch the active context
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
current_context: staging-admin
- name: Copy a kubeconfig to a new location with an additional cluster merged in
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
dest: /home/user/.kube/config-ci
clusters:
- name: ci-cluster
cluster:
server: https://ci.k8s.example.com:6443
insecure-skip-tls-verify: true
"""
RETURN = r"""
kubeconfig:
description: The complete kubeconfig data structure.
type: dict
returned: always
dest:
description: The path where the kubeconfig was written.
type: str
returned: always
sample: /home/user/.kube/config
"""
import os
import traceback
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.common.text.converters import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.args_common import (
extract_sensitive_values_from_kubeconfig,
)
from ansible_collections.kubernetes.core.plugins.module_utils.kubeconfig import (
hash_data,
load_yaml_file,
merge_by_name,
write_file,
)
try:
import yaml
IMP_YAML = True
IMP_YAML_ERR = None
except ImportError:
IMP_YAML = False
IMP_YAML_ERR = traceback.format_exc()
def run_module():
module_args = dict(
path=dict(type="str", required=True),
dest=dict(type="str", required=False),
clusters=dict(type="list", elements="dict", required=False, default=[]),
users=dict(type="list", elements="dict", required=False, default=[]),
contexts=dict(type="list", elements="dict", required=False, default=[]),
preferences=dict(type="dict", required=False, default={}),
current_context=dict(type="str", required=False),
)
module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)
path = module.params["path"]
dest = module.params["dest"] or path
clusters_input = module.params["clusters"]
users_input = module.params["users"]
contexts_input = module.params["contexts"]
preferences = module.params["preferences"]
current_context = module.params["current_context"]
# Load existing kubeconfig
try:
if not IMP_YAML:
module.fail_json(
msg=missing_required_lib("pyyaml"),
exception=IMP_YAML_ERR,
)
existing = load_yaml_file(path) if path else {}
except Exception as e:
module.fail_json(
msg="Failed to load existing kubeconfig: %s" % to_native(e),
exception=traceback.format_exc(),
)
clusters = merge_by_name(existing.get("clusters", []), clusters_input)
users = merge_by_name(existing.get("users", []), users_input)
contexts = merge_by_name(existing.get("contexts", []), contexts_input)
# Build final kubeconfig
kubeconfig = {
"apiVersion": "v1",
"kind": "Config",
"preferences": preferences or existing.get("preferences", {}),
"clusters": clusters,
"users": users,
"contexts": contexts,
"current-context": current_context or existing.get("current-context") or "",
}
changed = False
old_data = {}
if os.path.exists(dest):
try:
with open(dest, "r") as f:
old_data = yaml.safe_load(f) or {}
except Exception as e:
module.fail_json(
msg="Failed to read destination file: %s" % to_native(e),
exception=traceback.format_exc(),
)
old_hash = hash_data(old_data)
new_hash = hash_data(kubeconfig)
if old_hash != new_hash:
if not module.check_mode:
try:
write_file(dest, kubeconfig)
except Exception as e:
module.fail_json(
msg="Failed to write kubeconfig: %s" % to_native(e),
exception=traceback.format_exc(),
)
changed = True
if isinstance(kubeconfig, dict):
module.no_log_values.update(
extract_sensitive_values_from_kubeconfig(kubeconfig)
)
module.exit_json(
changed=changed,
kubeconfig=kubeconfig,
dest=dest,
msg=(
"Kubeconfig file has been updated."
if changed
else "Kubeconfig file is already up to date."
),
)
def main():
run_module()
if __name__ == "__main__":
main()
+2 -34
View File
@@ -9,26 +9,15 @@ sonar.python.coverage.reportPaths=coverage.xml
sonar.tests=tests/unit,tests/integration sonar.tests=tests/unit,tests/integration
sonar.python.version=3.12 sonar.python.version=3.12
sonar.newCode.referenceBranch=main sonar.newCode.referenceBranch=stable-5
sonar.exclusions=tests/**,.tox/** 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(...) # Ansible module argument_spec is conventionally defined with the dict(...)
# constructor (not {...} literals) for readability and consistency across the # constructor (not {...} literals) for readability and consistency across the
# collection. Suppress python:S7498 ("prefer literal syntax"), which conflicts # collection. Suppress python:S7498 ("prefer literal syntax"), which conflicts
# with that convention and otherwise re-fires on every new module argument. # with that convention and otherwise re-fires on every new module argument.
sonar.issue.ignore.multicriteria=e1,e2,e3,e4,e5 sonar.issue.ignore.multicriteria=e1,e2,e3
sonar.issue.ignore.multicriteria.e1.ruleKey=python:S7498 sonar.issue.ignore.multicriteria.e1.ruleKey=python:S7498
sonar.issue.ignore.multicriteria.e1.resourceKey=**/*.py sonar.issue.ignore.multicriteria.e1.resourceKey=**/*.py
@@ -45,24 +34,3 @@ sonar.issue.ignore.multicriteria.e2.resourceKey=tests/**/*.py
# to simplify maintenance. Suppress githubactions:S7637 ("use full commit SHA"). # to simplify maintenance. Suppress githubactions:S7637 ("use full commit SHA").
sonar.issue.ignore.multicriteria.e3.ruleKey=githubactions:S7637 sonar.issue.ignore.multicriteria.e3.ruleKey=githubactions:S7637
sonar.issue.ignore.multicriteria.e3.resourceKey=.github/workflows/**/*.yaml sonar.issue.ignore.multicriteria.e3.resourceKey=.github/workflows/**/*.yaml
# Workflows across this repo install ansible-core from a GitHub source
# archive (required for devel/milestone builds, which have no published
# wheel) and install this collection's shared test-requirements.txt /
# requirements.txt. Suppress githubactions:S8541 ("omitting --only-binary
# :all:") repo-wide for workflow files: forcing wheel-only installs would
# break the ansible-core source install and fails outright on the
# test-requirements.txt pin coverage==4.5.4, which has no Python 3.13 wheel.
# Scoped the same way as e3 above, since a filename-only resourceKey (as
# originally used here) does not reliably suppress issues already raised
# against this project.
sonar.issue.ignore.multicriteria.e4.ruleKey=githubactions:S8541
sonar.issue.ignore.multicriteria.e4.resourceKey=.github/workflows/**/*.yaml
# Same shared test-requirements.txt / requirements.txt as above are not
# hash-locked; that is a repo-wide dependency-management concern affecting
# every existing workflow. Suppress githubactions:S8544 ("dependencies
# without locking resolved versions") repo-wide for workflow files rather
# than diverging from established practice.
sonar.issue.ignore.multicriteria.e5.ruleKey=githubactions:S8544
sonar.issue.ignore.multicriteria.e5.resourceKey=.github/workflows/**/*.yaml
+1 -1
View File
@@ -1,2 +1,2 @@
modules: modules:
python_requires: ">=3.9" python_requires: ">=3.6"
-46
View File
@@ -1,46 +0,0 @@
# Running Helm Integration Tests Locally
This guide explains how to run the `helm*` integration test targets locally using `ansible-test`.
## Prerequisites
- `ansible-test` available in your environment (installed with `ansible-core`)
- A Kubernetes cluster accessible via `kubectl` (for targets that interact with a cluster)
## Configuration
Create an `integration_config.yml` file under `tests/integration/` with the following variables:
```yaml
setup_helm_version: vx.x.x # e.g v4.2.1
helm_install_path: /path/to/helm/directory
```
### Variables
| Variable | Description |
|---|---|
| `setup_helm_version` | The Helm version to install (e.g. `v4.2.1`). The `v` prefix is optional and will be added automatically if omitted. |
| `helm_install_path` | Path to a directory that either already contains a `helm` executable matching the version set in `setup_helm_version`, or an empty/non-existent directory where Helm will be downloaded and installed. |
If a `helm` binary already exists at `<helm_install_path>/helm`, the setup will skip the download and use the existing binary directly.
## Running Tests
Run a specific Helm test target with:
```bash
ansible-test integration --python <version> -v --no-temp-workdir <target>
```
For example, to run the `helm` target with Python 3.12:
```bash
ansible-test integration --python 3.12 -v --no-temp-workdir helm
```
You can run multiple targets in a single command:
```bash
ansible-test integration --python 3.12 -v --no-temp-workdir helm helm_diff helm_plugin
```
+2 -2
View File
@@ -1,4 +1,4 @@
helm time=100
helm_info helm_info
helm_plugin helm_repository
helm_template helm_template
@@ -1,6 +1,6 @@
--- ---
helm_binary: "helm" helm_default_archive_name: "helm-{{ helm_version }}-{{ ansible_system | lower }}-amd64.tar.gz"
setup_helm_version_binary_path: "{{ helm_binary }}" helm_binary: "/tmp/helm/{{ ansible_system | lower }}-amd64/helm"
chart_test: "ingress-nginx" chart_test: "ingress-nginx"
chart_test_oci: "oci://registry-1.docker.io/bitnamicharts/redis" chart_test_oci: "oci://registry-1.docker.io/bitnamicharts/redis"
@@ -9,26 +9,23 @@ chart_test_version: 4.2.4
chart_test_version_local_path: 1.32.0 chart_test_version_local_path: 1.32.0
chart_test_version_upgrade: 4.2.5 chart_test_version_upgrade: 4.2.5
chart_test_version_upgrade_local_path: 1.33.0 chart_test_version_upgrade_local_path: 1.33.0
chart_test_repo: "https://stenic.github.io/k8status/" chart_test_repo: "https://kubernetes.github.io/ingress-nginx"
chart_test_git_repo: "http://github.com/helm/charts.git" chart_test_git_repo: "http://github.com/helm/charts.git"
chart_test_values: chart_test_values:
revisionHistoryLimit: 0 revisionHistoryLimit: 0
myValue: "changed" myValue: "changed"
test_namespace: test_namespace:
- "helm-test-crds-{{ helm_version | replace('.', '-') }}" - "helm-test-crds"
- "helm-uninstall-{{ helm_version | replace('.', '-') }}" - "helm-uninstall"
- "helm-read-envvars-{{ helm_version | replace('.', '-') }}" - "helm-read-envvars"
- "helm-dep-update-{{ helm_version | replace('.', '-') }}" - "helm-dep-update"
- "helm-local-path-001-{{ helm_version | replace('.', '-') }}" - "helm-local-path-001"
- "helm-local-path-002-{{ helm_version | replace('.', '-') }}" - "helm-local-path-002"
- "helm-local-path-003-{{ helm_version | replace('.', '-') }}" - "helm-local-path-003"
- "helm-from-repository-{{ helm_version | replace('.', '-') }}" - "helm-from-repository"
- "helm-from-url-{{ helm_version | replace('.', '-') }}" - "helm-from-url"
- "helm-reuse-values-{{ helm_version | replace('.', '-') }}" - "helm-reuse-values"
- "helm-chart-with-space-into-name-{{ helm_version | replace('.', '-') }}" - "helm-chart-with-space-into-name"
- "helm-reset-then-reuse-values-{{ helm_version | replace('.', '-') }}" - "helm-reset-then-reuse-values"
- "helm-insecure-{{ helm_version | replace('.', '-') }}" - "helm-insecure"
- "helm-test-take-ownership-{{ helm_version | replace('.', '-') }}"
- "helm-skip-schema-validation-{{ helm_version | replace('.', '-') }}"
- "helm-wait-for-jobs-{{ helm_version | replace('.', '-') }}"
@@ -1,6 +0,0 @@
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"
@@ -1,21 +0,0 @@
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"
@@ -52,9 +52,7 @@ import json
import subprocess import subprocess
import time import time
from ansible_collections.kubernetes.core.plugins.module_utils.helm import ( from ansible.module_utils.basic import AnsibleModule
AnsibleHelmModule,
)
class HelmReleaseNotFoundError(Exception): class HelmReleaseNotFoundError(Exception):
@@ -62,9 +60,7 @@ class HelmReleaseNotFoundError(Exception):
super().__init__(message) super().__init__(message)
def create_pending_install_release( def create_pending_install_release(helm_binary, chart_ref, chart_release, namespace):
module, helm_binary, chart_ref, chart_release, namespace
):
# create pending-install release # create pending-install release
command = [ command = [
helm_binary, helm_binary,
@@ -82,14 +78,13 @@ def create_pending_install_release(
command = [ command = [
helm_binary, helm_binary,
"list", "list",
"--all",
"--output=json", "--output=json",
"--namespace", "--namespace",
namespace, namespace,
"--filter", "--filter",
chart_release, chart_release,
] ]
if not module.is_helm_v4():
command.append("--all")
cmd = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) cmd = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = cmd.communicate() out, err = cmd.communicate()
@@ -97,11 +92,11 @@ def create_pending_install_release(
if not data: if not data:
error = "Release %s not found." % chart_release error = "Release %s not found." % chart_release
raise HelmReleaseNotFoundError(message=error) raise HelmReleaseNotFoundError(message=error)
return data[0]["status"] in ("pending-install", "failed"), data[0]["status"] return data[0]["status"] == "pending-install", data[0]["status"]
def main(): def main():
module = AnsibleHelmModule( module = AnsibleModule(
argument_spec=dict( argument_spec=dict(
binary_path=dict(type="path", required=True), binary_path=dict(type="path", required=True),
chart_ref=dict(type="str", required=True), chart_ref=dict(type="str", required=True),
@@ -111,7 +106,6 @@ def main():
) )
params = dict( params = dict(
module=module,
helm_binary=module.params.get("binary_path"), helm_binary=module.params.get("binary_path"),
chart_release=module.params.get("chart_release"), chart_release=module.params.get("chart_release"),
chart_ref=module.params.get("chart_ref"), chart_ref=module.params.get("chart_ref"),
@@ -122,7 +116,7 @@ def main():
result, status = create_pending_install_release(**params) result, status = create_pending_install_release(**params)
if not result: if not result:
module.fail_json( module.fail_json(
msg="unable to create pending-install/failed release, current status is %s" msg="unable to create pending-install release, current status is %s"
% status % status
) )
module.exit_json(changed=True, msg="Release created with status '%s'" % status) module.exit_json(changed=True, msg="Release created with status '%s'" % status)
@@ -0,0 +1,96 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2021, 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
DOCUMENTATION = r"""
---
module: helm_test_version
short_description: check helm executable version
author:
- Aubin Bikouo (@abikouo)
requirements:
- "helm (https://github.com/helm/helm/releases)"
description:
- validate version of helm binary is lower than the specified version.
options:
binary_path:
description:
- The path of a helm binary to use.
required: false
type: path
version:
description:
- version to test against helm binary.
type: str
default: 3.7.0
"""
EXAMPLES = r"""
- name: validate helm binary version is lower than 3.5.0
helm_test_version:
binary_path: path/to/helm
version: "3.5.0"
"""
RETURN = r"""
message:
type: str
description: Text message describing the test result.
returned: always
sample: 'version installed: 3.4.5 is lower than version 3.5.0'
result:
type: bool
description: Test result.
returned: always
sample: 1
"""
import re
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.kubernetes.core.plugins.module_utils.version import (
LooseVersion,
)
def main():
module = AnsibleModule(
argument_spec=dict(
binary_path=dict(type="path"),
version=dict(type="str", default="3.7.0"),
),
)
bin_path = module.params.get("binary_path")
version = module.params.get("version")
if bin_path is not None:
helm_cmd_common = bin_path
else:
helm_cmd_common = "helm"
helm_cmd_common = module.get_bin_path(helm_cmd_common, required=True)
rc, out, err = module.run_command([helm_cmd_common, "version"])
if rc != 0:
module.fail_json(msg="helm version failed.", err=err, out=out, rc=rc)
m = re.match(r'version.BuildInfo{Version:"v([0-9\.]*)",', out)
installed_version = m.group(1)
message = "version installed: %s" % installed_version
if LooseVersion(installed_version) < LooseVersion(version):
message += " is lower than version %s" % version
module.exit_json(changed=False, result=True, message=message)
else:
message += " is greater than version %s" % version
module.exit_json(changed=False, result=False, message=message)
if __name__ == "__main__":
main()
+2 -2
View File
@@ -1,5 +1,5 @@
--- ---
dependencies:
- setup_helm_version
collections: collections:
- kubernetes.core - kubernetes.core
dependencies:
- remove_namespace
@@ -0,0 +1,7 @@
---
- connection: local
gather_facts: true
hosts: localhost
roles:
- helm
+5
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 "$@"
@@ -0,0 +1,15 @@
---
- name: Init Helm folders
file:
path: /tmp/helm/
state: directory
- name: Unarchive Helm binary
unarchive:
src: 'https://get.helm.sh/{{ helm_archive_name | default(helm_default_archive_name) }}'
dest: /tmp/helm/
remote_src: yes
retries: 10
delay: 5
register: result
until: result is not failed
@@ -1,11 +1,10 @@
--- ---
- name: Ensure helm is not installed
ansible.builtin.file:
path: "/tmp/helm"
state: absent
- name: Check failed if helm is not installed
ansible.builtin.include_tasks: test_helm_not_installed.yml
- name: Run tests - name: Run tests
ansible.builtin.include_tasks: run_test.yml include_tasks: run_test.yml
loop_control:
loop_var: helm_version
with_items:
- "v3.15.4"
- "v3.16.0"
- "v3.17.0"
- "v4.0.0"
@@ -1,18 +1,28 @@
--- ---
- name: Main helm tests - name: Ensure helm is not installed
file:
path: "{{ item }}"
state: absent
with_items:
- "/tmp/helm"
- name: Check failed if helm is not installed
include_tasks: test_helm_not_installed.yml
- name: "Install {{ helm_version }}"
include_role:
name: install_helm
- name: Main helm tests with Helm v3
when: helm_version != "v4.0.0"
block: block:
- name: Install helm-diff plugin
helm_plugin:
binary_path: "{{ helm_binary }}"
plugin_path: https://github.com/databus23/helm-diff
plugin_version: "{{ helm_version | string is ansible.builtin.version('4.0.0', '>=') | ternary('v3.14.0', 'v3.10.0') }}"
verify: false
- name: "Ensure we honor the environment variables" - name: "Ensure we honor the environment variables"
ansible.builtin.include_tasks: test_read_envvars.yml include_tasks: test_read_envvars.yml
when: helm_version != "v4.0.0"
- name: Deploy charts - name: Deploy charts
ansible.builtin.include_tasks: "tests_chart/{{ test_chart_type }}.yml" include_tasks: "tests_chart/{{ test_chart_type }}.yml"
loop_control: loop_control:
loop_var: test_chart_type loop_var: test_chart_type
with_items: with_items:
@@ -20,44 +30,34 @@
- from_repository - from_repository
- from_url - from_url
- name: Test helm upgrade with reuse_values - name: test helm upgrade with reuse_values
ansible.builtin.include_tasks: test_helm_reuse_values.yml include_tasks: test_helm_reuse_values.yml
- name: Test helm upgrade with reset_then_reuse_values - name: test helm upgrade with reset_then_reuse_values
ansible.builtin.include_tasks: test_helm_reset_then_reuse_values.yml include_tasks: test_helm_reset_then_reuse_values.yml
when: helm_version | string is ansible.builtin.version('3.14.0', '>=')
- name: Test helm dependency update - name: test helm dependency update
ansible.builtin.include_tasks: test_up_dep.yml include_tasks: test_up_dep.yml
- name: Test helm uninstall
include_tasks: test_helm_uninstall.yml
- name: Test helm install with chart name containing space - name: Test helm install with chart name containing space
ansible.builtin.include_tasks: test_helm_with_space_into_chart_name.yml include_tasks: test_helm_with_space_into_chart_name.yml
# https://github.com/ansible-collections/community.kubernetes/issues/296 # https://github.com/ansible-collections/community.kubernetes/issues/296
- name: Test Skip CRDS feature in helm chart install - name: Test Skip CRDS feature in helm chart install
ansible.builtin.include_tasks: test_crds.yml include_tasks: test_crds.yml
- name: Test insecure registry flag feature - name: Test insecure registry flag feature
ansible.builtin.include_tasks: test_helm_insecure.yml include_tasks: test_helm_insecure.yml
- name: Test take ownership flag feature - name: Test helm version
ansible.builtin.include_tasks: test_helm_take_ownership.yml include_tasks: test_helm_version.yml
- name: Test helm skip_schema_validation - name: Clean helm install
ansible.builtin.include_tasks: test_skip_schema_validation.yml file:
path: "{{ item }}"
- name: Test helm wait_for_jobs state: absent
ansible.builtin.include_tasks: test_helm_wait_for_jobs.yml with_items:
- "/tmp/helm/"
always:
- name: Remove helm-diff plugin
helm_plugin:
binary_path: "{{ helm_binary }}"
plugin_name: diff
state: absent
ignore_errors: true
- name: Clean helm install
ansible.builtin.file:
path: "/tmp/helm/"
state: absent
@@ -14,7 +14,7 @@
register: install register: install
- name: Validate that insecure flag is not set - name: Validate that insecure flag is not set
ansible.builtin.assert: assert:
that: that:
- install is changed - install is changed
- '"--insecure-skip-tls-verify" not in install.command' - '"--insecure-skip-tls-verify" not in install.command'
@@ -30,18 +30,18 @@
ignore_errors: true ignore_errors: true
- name: Validate that insecure flag IS set if helm version is >= 3.16.0 - name: Validate that insecure flag IS set if helm version is >= 3.16.0
ansible.builtin.assert: assert:
that: that:
- install is changed - install is changed
- '"--insecure-skip-tls-verify" in install.command' - '"--insecure-skip-tls-verify" in install.command'
when: helm_version | string is ansible.builtin.version("3.16.0", ">=") when: '"v3.16.0" <= helm_version'
- name: Validate that feature fails for helm < 3.16.0 - name: Validate that feature fails for helm < 3.16.0
ansible.builtin.assert: assert:
that: that:
- install is failed - install is failed
- '"insecure_skip_tls_verify requires helm >= 3.16.0" in install.msg' - '"insecure_skip_tls_verify requires helm >= 3.16.0" in install.msg'
when: helm_version | string is ansible.builtin.version("3.16.0", "<") when: 'helm_version < "v3.16.0"'
always: always:
- name: Remove helm namespace - name: Remove helm namespace
@@ -1,15 +1,23 @@
--- ---
- name: Failed test when helm is not installed - name: Failed test when helm is not installed
helm: helm:
binary_path: "{{ helm_binary }}_fake" binary_path: "{{ helm_binary}}_fake"
name: test name: test
chart_ref: "{{ chart_test }}" chart_ref: "{{ chart_test }}"
namespace: "helm-test" namespace: "helm-test"
ignore_errors: true ignore_errors: yes
register: helm_missing_binary register: helm_missing_binary
- name: Assert that helm is not installed - name: Assert that helm is not installed
ansible.builtin.assert: assert:
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: that:
- helm_missing_binary is failed - helm_missing_binary is failed
- "'Error executing command' in helm_missing_binary.msg" - "'Error executing command' in helm_missing_binary.msg"
when: ansible_version.full is version('2.20', '>=')
@@ -32,34 +32,12 @@
register: release_value register: release_value
- name: Validate that chart values are as expected - name: Validate that chart values are as expected
ansible.builtin.assert: assert:
that: that:
- install is changed - install is changed
- '"--reset-then-reuse-values" not in install.command' - '"--reset-then-reuse-values" not in install.command'
- release_value["status"]["release_values"] == chart_release_values - release_value["status"]["release_values"] == chart_release_values
# We need to provide the actual redis password otherwise the update command
# will fail with the following:
# Error: execution error at (redis/templates/replicas/application.yaml:55:35):
# PASSWORDS ERROR: You must provide your current passwords when upgrading the release.
# Note that even after reinstallation, old credentials may be needed as they may be kept in persistent volume claims.
# Further information can be obtained at https://docs.bitnami.com/general/how-to/troubleshoot-helm-chart-issues/#credential-errors-while-upgrading-chart-releases
# 'global.redis.password' must not be empty, please add '--set global.redis.password=$REDIS_PASSWORD' to the command. To get the current value:
- name: Retrieve release password
kubernetes.core.k8s_info:
namespace: "{{ helm_namespace }}"
kind: Secret
name: test-redis
register: redis_secret
- ansible.builtin.set_fact:
chart_reset_then_reuse_values: "{{ chart_reset_then_reuse_values | combine(redis_global_password) }}"
vars:
redis_global_password:
global:
redis:
password: "{{ redis_secret.resources.0.data['redis-password'] | b64decode }}"
- name: Upgrade chart using reset_then_reuse_values=true - name: Upgrade chart using reset_then_reuse_values=true
helm: helm:
binary_path: "{{ helm_binary }}" binary_path: "{{ helm_binary }}"
@@ -80,7 +58,7 @@
register: release_value register: release_value
- name: Validate that chart values are as expected - name: Validate that chart values are as expected
ansible.builtin.assert: assert:
that: that:
- upgrade is changed - upgrade is changed
- '"--reset-then-reuse-values" in upgrade.command' - '"--reset-then-reuse-values" in upgrade.command'
@@ -95,4 +73,3 @@
kind: Namespace kind: Namespace
name: "{{ helm_namespace }}" name: "{{ helm_namespace }}"
state: absent state: absent
wait: false

Some files were not shown because too many files have changed in this diff Show More