Compare commits

..
142 Commits
Author SHA1 Message Date
2e5f3198fc fix: add default to k8s_copy init-pod until conditional (#1233) (#1271)
(cherry picked from commit b7e1ed5661)

Co-authored-by: Don Naro <dnaro@redhat.com>
2026-09-22 16:29:41 +01:00
819adf3e4b fix(sanity): resolve ansible-test devel validation errors (#1268) (#1269)
(cherry picked from commit 177297fdae)

Co-authored-by: Don Naro <dnaro@redhat.com>
2026-09-22 09:59:33 +01:00
e91b3171ea Release v6.6.0 (#1261)
* Release v6.6.0

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* bump Makefile and README example VERSION to 6.6.0

* docs: regenerate for 6.6.0 and fix stable-6 links

- Regenerate module documentation with collection_prep
- Update helm module docs for reuse_values/reset_values changes
- Add wait_for_jobs, copy_timeout, metadata_only parameters
- Restore ansible_turbo_mode.rst (not auto-generated)
- Fix README.md links to point to stable-6 branch

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
Co-authored-by: Mandar Kulkarni <mandkulk@redhat.com>
2026-09-16 12:28:23 +01:00
693e80389b fix(helm): validate reuse_values against reset_values and replace (#1230) (#1262)
* fix(helm): validate reuse_values against reset_values and replace

reset_values defaults to true and helm ignores --reuse-values whenever
--reset-values is passed, so the documented reuse_values example was a
no-op. Warn rather than flip the default, which would silently change
what existing playbooks deploy.

helm install accepts neither --reuse-values nor --reset-then-reuse-values,
so pairing either with replace could only ever make helm report an unknown
flag. Fail up front instead, and keep both flags inside the upgrade branch.

Fixes #1229

* fix(docstring): neither nor replacing



* fix(helm): warn instead of failing on replace + reuse_values

reuse_values has been accepted since 3.0.0, and a converged release never
reaches deploy(), so these combinations pass in playbooks today. Failing
in main() would turn them red on upgrade. The flags are already dropped
from the install path, so warning leaves a valid command behind.

Splits the changelog fragment per user-visible change, and covers the
helm diff path, whose 'not replace' guards the hard failure had made
unreachable.

Changes based on the @abikouo's feedback

---------


(cherry picked from commit 10584acdbb)

Co-authored-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
Co-authored-by: Don Naro <dnaro@redhat.com>
2026-09-16 11:47:18 +01:00
53cb65a740 :fix(helm_repository): normalize both sides of the repo URL comparison (#1236) (#1258)
helm stores repository URLs verbatim, so a repository registered with a
trailing slash keeps it in repositories.yaml. Only the URL coming from the
task was normalized, so a repository that already matched was reported as a
name conflict.

Fixes #1235

(cherry picked from commit 094240ab77)

Co-authored-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
2026-09-15 11:03:49 -07:00
a2803df8e8 Add deprecation warnings for the status.values return value (#1241) (#1256)
* chore: add deprecation warning for status.values

* docs: add changelog entries for status.values deprecation

(cherry picked from commit f42c78ce83)

Co-authored-by: Don Naro <dnaro@redhat.com>
2026-09-15 16:44:53 +01:00
1016f80aee Add ansible-core version check to k8s lookup turbo mode (#1253) (#1254)
* feat(lookup): add ansible-core version check for turbo mode in k8s lookup

Add ansible-core version checking to the k8s lookup plugin to match the
behavior already implemented in module_utils/ansiblemodule.py.

When ENABLE_TURBO_MODE is set and ansible-core >= 2.19.0:
- Emit deprecation warning for ENABLE_TURBO_MODE
- Emit version warning explaining turbo mode is unsupported
- Disable turbo mode and fall back to standard LookupBase

This prevents confusing tracebacks when cloud.common (which declares
requires_ansible '>=2.15.0,<2.19') is used on newer ansible-core versions
where it is not fully compatible.

Changes:
- Import ansible_version and LooseVersion
- Add TURBO_UNSUPPORTED_CORE = "2.19.0" constant
- Check version before enabling turbo mode
- Disable turbo mode and warn if version >= 2.19.0

Addresses reviewer feedback on PR #1251 to add version testing to the
lookup plugin matching the module implementation.



* test(lookup): add unit tests for k8s turbo mode version check

Add comprehensive unit tests for the ansible-core version checking logic
in the k8s lookup plugin's turbo mode handling.

Tests validate that when ENABLE_TURBO_MODE is set:
- Turbo mode is disabled on ansible-core >= 2.19.0 (tests 2.19.0 and 2.21.4)
- Turbo mode is enabled on ansible-core < 2.19.0 (tests 2.18.0)
- Appropriate deprecation and version warnings are shown
- Standard LookupBase is used when turbo mode is disabled

Tests also verify that when ENABLE_TURBO_MODE is not set:
- No deprecation or warning messages are shown
- Turbo mode remains disabled
- Standard LookupBase is used

Implementation follows pytest best practices:
- Autouse fixture for module cleanup between tests
- Parametrized tests to avoid duplication (2.19.0 and 2.21.4 share logic)
- Mock assertion methods (assert_called, assert_not_called)
- Module-level import of StandardLookupBase to avoid repetition

Simplified and maintainable: 71 lines vs initial 139-line implementation
(49% reduction through deduplication and better abstractions).



* style: format with black

* fixup! test(lookup): add unit tests for k8s turbo mode version check

* docs: add changelog fragment for k8s lookup turbo version check

Add changelog entry documenting that the k8s lookup plugin now ignores
ENABLE_TURBO_MODE on ansible-core >= 2.19.0 and falls back to standard
LookupBase instead of failing with a traceback.

This complements the existing deprecate-enable-turbo-mode.yml fragment
which covers the module implementation, by documenting the lookup plugin
fix specifically.



* fixup! fixup! test(lookup): add unit tests for k8s turbo mode version check

* fixup! fixup! fixup! test(lookup): add unit tests for k8s turbo mode version check

---------


(cherry picked from commit c46180bb6f)

Co-authored-by: Don Naro <dnaro@redhat.com>
Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-09-15 16:42:50 +01:00
90e868aa37 ci: add the PE certification checker workflow (#1231) (#1249)
* ci: add the PE certification checker workflow

* ci: add stable branches to certification workflow

(cherry picked from commit 732925b986)

Co-authored-by: Don Naro <dnaro@redhat.com>
2026-09-15 14:25:49 +01:00
864c7addd1 k8s_cp - wait for remote tar to finish before closing the stream (#1217) (#1252)
* fix(k8s_cp): wait for remote tar to finish before closing the stream

The module closed the exec connection right after writing the last chunk,
killing tar mid-extract, and never checked its exit status, so a partial
or failed copy was reported as success (#776).

The v4 exec protocol cannot half-close stdin, and busybox tar blocks for
EOF rather than stopping at the end-of-archive marker, so bound the stream
with `head -c N | tar ...`. tar then gets a clean EOF, exits on its own,
and its status is read from the error channel. Containers without /bin/sh
and head keep the previous behaviour and get a warning.

Also add copy_timeout (default 300s, #621) and stream the archive from the
temp file instead of buffering every chunk in memory.

* test(k8s_cp): split combined assert into separate statements

Addresses review feedback on #1217.

* chore(changelog): link the PR and use single-line fragment entries

* fix(linter): reformat with black

* fix(linter): sort imports in test_copy.py

isort --profile black puts ansible_collections in the same third-party
section as pytest, so the blank line between them is a failure.

* fix(k8s_cp): report what tar said when the copy fails early

An early close or a stall is the symptom; tar has usually already
written the cause (a read-only mount, a missing directory) to stderr,
and drain() has it. Discarding it left only the generic truncation or
timeout message.

* refactor(k8s_cp): move the stderr suffix into _fail

The nested fail() helper added a branch inside a closure, which counts
double for nesting and took _stream_tar_to_pod over Sonar's cognitive
complexity limit (14 -> 16). _fail already had the response; give it
the stderr too.

* test(k8s_cp): tempfile for the repeated-copy test directory



---------


(cherry picked from commit 8a9dd54fe7)

Co-authored-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>
2026-09-15 10:53:45 +01:00
021ffbfec2 Add a deprecation notice for ENABLE_TURBO_MODE (#1242) (#1250)
* Add a deprecation notice for ENABLE_TURBO_MODE

* minor fix

* fix(turbo): ensure deprecation warning reaches user and skip turbo on unsupported ansible-core

Move the ENABLE_TURBO_MODE deprecation warning to module import time,
since AnsibleTurboModule.__init__() exits the process before returning,
making the previous per-instance deprecate() call unreachable. Also
skip turbo mode on ansible-core >= 2.19.0, where cloud.common is not
supported and the import succeeding could otherwise fail later with
an unrelated traceback, and warn instead of silently falling back
when cloud.common is not installed.

Assisted-by: Claude Sonnet 5

* docs(turbo): clarify that turbo mode is ignored on ansible-core 2.19+

Turbo mode is now bypassed with a warning rather than failing on
unsupported ansible-core, so drop the "may lead to fails" wording from
the README note and the matching statement in the turbo mode guide.

Assisted-by: Claude Opus 5


---------


(cherry picked from commit 031bc475fa)

Co-authored-by: Mandar Kulkarni <mandkulk@redhat.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-15 09:19:32 +01:00
b40a401ec2 fix(helm): skip Helm's OCI registry progress messages on stdout (#1223) (#1247)
* fix(helm): skip OCI registry progress messages on stdout

Helm 4.2.1 moved the registry client's progress messages from stderr to
stdout (helm/helm#32056), so on an OCI reference they now precede the real
output. helm parses the stdout of `helm show chart` and helm_template
returns the stdout of `helm template`, and neither can detect this from the
return code because both commands exit 0.

Helm rewrites '+' to '_' in OCI tags, which makes it also print a free-text
explanation. That is not valid YAML, so a chart version carrying semver
build metadata failed outright. Without the '+' the messages parse as a
mapping instead, silently adding Pulled/Digest keys to the chart info.

Match helm's message verbatim rather than seeking the start of the real
output: the payload has three shapes and can be empty, whereas the messages
are always at the front and byte-identical. A reworded message then fails
loudly instead of consuming a line of real output.

Fixes: #1222

* test(helm): cover OCI charts whose version has build metadata

Pushes a chart versioned 1.0.0+build.1 to the local registry and asserts
that helm installs it idempotently with the version reported verbatim, and
that helm_template returns only rendered manifests. A second version without
build metadata covers the case where the registry messages parse as YAML.

Pinned to Helm 4.2.4: the target is only meaningful on >= 4.2.1, which is
where the messages moved to stdout. The rest of the helm matrix tops out at
v4.0.0, which is why this went unnoticed.

Verified to fail on the parent commit and pass on the fix.

* test(helm): drop Go template from chart fixture

The yamllint sanity test parses chart templates with libyaml, where
`{{ default "test" .Values.myValue }}` is an unhashable mapping key. The
existing chart fixtures carry a yamllint!skip entry in every
tests/sanity/ignore-*.txt for exactly this, but the target never renders
the chart with values, so the template served no purpose. Making the
fixture plain YAML keeps the ignore lists from growing.

* test(ci): empty commit to re-trigger CI

(cherry picked from commit c098ecc8c8)

Co-authored-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
2026-09-14 14:33:17 +01:00
e620b92b49 [PR #1240/cb00cf3c backport][stable-6] Address stale deprecations (#1245)
* Address stale deprecations (#1240)

* chore: update deprecation for wait_timeout

* chore: update deprecation for return_code

* docs(changelogs): add stale deprecations to changelogs

* docs: ignore pylint deprecation warnings

* chore: update deprecation for merge_type

* docs: update changelogs for merge_type

* docs: ignore more pylint deprecation warnings

(cherry picked from commit cb00cf3c9e)

* fix: remove unnecessary ignore statements

---------

Co-authored-by: Don Naro <dnaro@redhat.com>
2026-09-14 13:49:58 +01:00
40123060c1 chore(test): add ansible 2.21 to integration tests matrix (#1234) (#1243)
* chore(test): add ansible 2.21 to integration tests matrix

current version of Ansible (as the time of this commit) is
2.21 that is included in the Ansible 14 release.

To ensure testing coverage for actual version if ansible,
version 2.21 should be included in the integration tests matrix.

Updated matrix includes:
- stable-2.18 as the latest version support turbo mode
- stable-2.21 as the actual version
- milestone as the development version

* chore(test): exclude 2.18/turbo off from integration tests matrix

stable-2.18 is used mostly as the last version with turbo mode,
so no reason to test it with turbo mode disabled as it tested with
the later version of ansible.

Excluding to decrease CI time/cost

(cherry picked from commit 7df5e01974)

Co-authored-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
2026-09-14 13:21:20 +01:00
d44a8501e6 test(sanity): align python_requires with documented 3.9+ support (#1226) (#1227)
tests/config.yml declared ">=3.6", so ansible-test ran the module import
test on target Python versions this collection never supported, while
README states 3.9+. Narrow the declaration and add ignore entries for the
supported target versions that were missing.

(cherry picked from commit d9e0218dba)

Co-authored-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
2026-09-10 17:27:53 +01:00
c3f7a453fd fix(meta): add missing modules to helm and k8s action groups, document them (#1216) (#1221)
* fix(meta): add missing modules to helm and k8s action groups

`helm_plugin` and `helm_plugin_info` both build their argument spec from
`HELM_AUTH_ARG_SPEC`, and `k8s_taint` builds its own from `AUTH_ARG_SPEC`,
but none of the three were listed in the action groups. Anyone setting
`module_defaults` on `group/kubernetes.core.helm` or
`group/kubernetes.core.k8s` silently got no defaults for them.

Deliberately left out of the groups, since they do not accept the shared
authentication options and would make `module_defaults` fail for every
user of the group:

  - `helm_pull` and `helm_template` take only `binary_path`
  - `helm_registry_auth` takes `binary_path` plus its own required `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

Also documents both action groups in the scenario guide, including the
exclusions above and the distinction from the legacy `k8s` group that
ansible-core defines, which is a different group and does not cover this
collection's modules.

Closes #577

* test(meta): guard action group membership against argspec drift

The action groups in `meta/runtime.yml` were maintained by hand, so
`helm_plugin`, `helm_plugin_info` and `k8s_taint` were able to inherit the
shared authentication arg specs without anyone adding them to a group.
Nothing failed, users just silently got no `module_defaults`.

Asserts the invariant in both directions: a module belongs to a group if
and only if it builds its argument spec from that group's shared constant.
The reverse direction matters too, since a member that does not accept the
shared options makes `module_defaults` fail with "Unsupported parameters"
for every user of the group.

Membership is read statically with `ast`, so the test needs no imports and
runs without a cluster or the `kubernetes` package.

The four modules that are deliberately excluded are listed with their
reasons, so restoring one has to be a decision rather than an oversight.

* fix(tests): satisfy pylint disallowed-name and set an explicit license

ansible-test's pylint profile rejects `_` as a name, which the sanity job
flagged three times. Rather than renaming the throwaways, give the entries
in SHARED_ARG_SPECS named keys so there is nothing to discard when reading
them back.

The header was copied from a sibling test that carries Apache-2.0 because
it derives from kubernetes/kubernetes, so it named the wrong copyright
holder. It now names the author, and keeps Apache-2.0 deliberately: the
collection requirements allow code outside plugins/ that imports no
GPL-3.0-or-later code to use any GPL-3.0-compatible license, and this file
imports only ast, os, pytest and yaml, since it reads group membership
statically rather than importing the modules. A comment records that
reasoning so the constraint is visible if an import is ever added.

* fix(doc): update changelog fragment with the manintainer suggestion

* fix(doc): show helm group defaults in the action group example

abikouo asked for the module_defaults example to cover the helm action
group as well, with tasks that actually consume those defaults. Set
binary_path, kubeconfig and context on group/kubernetes.core.helm and
add helm_repository, helm and helm_info tasks that rely on them; the
namespace in the k8s tasks now matches the release namespace so the
playbook reads as one flow.



---------


(cherry picked from commit 0bc99117af)

Co-authored-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>
2026-09-10 17:24:42 +01:00
5c06a554a8 Use collections.abc (#1057) (#1220)
* use collections.abc

ansible.module_utils.common._collections_compat shall be deprecated in
ansible-core 2.24

Use collections.abc

Link: https://forum.ansible.com/t/deprecation-warnings-in-ansible-core-2-20/44741


* Apply suggestion from @abikouo

* Fix linter errors

---------




(cherry picked from commit c643719085)

Signed-off-by: Plamerdi Makela <plamerdi447@gmail.com>
Co-authored-by: Plamerdi Makela <plamerdi447@gmail.com>
Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>
Co-authored-by: Bianca Henderson <bianca@redhat.com>
2026-09-10 17:23:52 +01:00
20b9c3fb7f Fix ansible-lint no-changed-when and execution-environment schema warnings (#1196) (#1237)
* Fix ansible-lint no-changed-when and execution-environment schema warnings

Add `changed_when: false` to example command tasks in the kubectl
connection plugin to resolve no-changed-when warnings from ansible-lint.

Add `version: 3` to meta/execution-environment.yml to satisfy the
schema[execution-environment] rule requiring the version property.



* Add changelog fragment for ansible-lint warning fixes



* Fix changelog fragment YAML formatting

Quote strings to avoid YAML parsing ambiguity in the trivial section.



---------


(cherry picked from commit a7922e498c)

Co-authored-by: Daniel Brennand <52419383+dbrennand@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-09-10 15:26:41 +01:00
7b17313ace Support wait_for_jobs flag for helm release upgrade/install (#1140) (#1214)
* Support wait_for_jobs flag for helm release upgrade/install

* Update plugins/modules/helm.py



* Apply suggestion from @abikouo

* fix(helm): correct wait_for_jobs implementation and add changelog

- Fix double-append of --wait-for-jobs flag
- Fix version check to run before appending the flag
- Fetch helm_version before use to avoid undefined variable
- Fix YAML indentation for version_added in docs
- Add changelog fragment



* test: add integration tests for wait_for_jobs

- Test that --wait-for-jobs is appended when wait=true and wait_for_jobs=true
- Test that wait_for_jobs fails with appropriate message on helm < 3.5.0
- Test that wait_for_jobs is ignored when wait is not set
- Add test-chart-job helm chart containing a simple Job resource



* fix: harden test Job pod spec

Disable service account token automounting and add memory limit to
the test Job container.



* fix: add resource requests and pin image version in test Job

Add CPU, memory, and ephemeral-storage requests. Pin busybox image
to version 1.37.



* style: apply linter formatting to helm argument_spec



* Update sanity ignore file

* fix: quote Helm template expression to pass yamllint sanity



* Fix linters errors

---------





(cherry picked from commit e475d06403)

Co-authored-by: Daniel Simko <danosimko1@gmail.com>
Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>
Co-authored-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
Co-authored-by: aubin bikouo <abikouo@redhat.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-08-11 12:11:51 -04:00
569bae6593 Remove remaining ansible.module_utils.six import from kubectl connection plugin (#1197) (#1200)
* Replace ansible.module_utils.six with Python stdlib equivalents

ansible.module_utils.six is deprecated in ansible-core 2.21 and is
scheduled for removal in 2.24. Every use of it in this collection has a
direct Python 3 standard library equivalent, so switch to those.

* Update changelogs/fragments/20260723-remove-module-utils-six.yaml



---------


(cherry picked from commit dd4ca7a8b0)

Co-authored-by: Zhiwei Liang <zhiwei.liang@zliang.me>
Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>
2026-08-11 12:54:54 +02:00
da42348358 ci: exclude test code from SonarCloud duplication detection (#1207) (#1213)
Duplication is scored on new code only, so a PR adding cases to an already
repetitive test module inherits debt accrued across earlier PRs rather than
introducing it; tests/unit/modules/test_module_helm.py sits at 47.9% on main
before any change.

sonar.exclusions filters the source set, not the copy/paste detector, so test
code needs its own exclusion. Production code stays covered.

(cherry picked from commit f31ecce59c)

Co-authored-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
2026-08-10 12:01:19 -04:00
79e98c3d6e feat(waiter): add native wait support for Job resources (#1202) (#1211)
Add a `job_complete` predicate that waits for Job resources to reach
either `Complete` or `Failed` condition, removing the need for custom
wait_condition workarounds.

Also rename shadowed `match` variable to `match_condition` in
`custom_condition` to avoid masking the Python built-in.

Fixes ansible-collections/kubernetes.core#1201


(cherry picked from commit 3e58e3a9ad)

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-08-10 16:49:59 +02:00
477bb79305 feat(helm): add cleanup_on_fail option (#1206) (#1210)
* feat(helm): add cleanup_on_fail option

atomic rolls back to the last successful revision but can leave behind
resources the failed upgrade created; helm accepts both flags together so
the rollback also drops those orphans.

Rejected with replace=true, since that deploys via helm install, which has
no --cleanup-on-fail. No version gate: the flag exists in helm 3.0.0, the
module's minimum, and was not renamed in v4.

* refactor(tests): share helm command-building test helpers

The new cleanup_on_fail tests copied setUp and _run_with_version verbatim
from the atomic tests, which SonarQube flagged as duplication on new code.
Extract both to module level so the two classes share them.

Scoped to the classes involved in that duplication; the other test classes
in this file keep their own fixtures.

* test(helm): align cleanup_on_fail assertions with review feedback

Adjust the Helm unit tests to assert the expected flags for
cleanup_on_fail on Helm v3 and v4, matching the behavior clarified
in review feedback.



---------


(cherry picked from commit d4ef10fc80)

Co-authored-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
Co-authored-by: abikouo <abikouo@users.noreply.github.com>
2026-08-10 16:41:33 +02:00
fd65a4f09e Handle empty template output gracefully (#1044) (#1205)
* Handle empty template output gracefully

* Add changelog fragment for empty template output fix

* refactor: reduce cognitive complexity of ActionModule.run

Extract compound boolean condition to a variable to reduce the
cognitive complexity from 16 to the allowed maximum of 15.



* refactor: extract duplicated error handling into _fail_with_error

Replace two identical error-handling blocks in ActionModule.run() with
a shared _fail_with_error static method to address SonarQube code
duplication finding.



* refactor: reduce code duplication in action plugin and tests

Revert _fail_with_error extraction that increased duplication on new
code. Consolidate duplicate integration test tasks for conditional
template into a single looped task.



---------



(cherry picked from commit ec8942dd90)

Co-authored-by: W. H. Wang <mattwang44@gmail.com>
Co-authored-by: aubin bikouo <abikouo@redhat.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-08-10 16:29:44 +02:00
b9749c94f9 Support for metadata-only fetches in k8s_info module (#1030) (#1203)
* Support for metadata-only fetches in k8s_info module

* Fix integration test assert

* Add missing changelog fragment

* Fix linters and sanity checks

* Fix linters

* Apply suggestion from @abikouo

* fix: resolve linter errors after rebase

Fix import sorting and apply black formatting to k8s_info.py and
args_common.py to pass tox -e linters.



---------




(cherry picked from commit 08a761fc17)

Co-authored-by: Federico Chiacchiaretta <federico.chia@gmail.com>
Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>
Co-authored-by: aubin bikouo <abikouo@redhat.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-08-07 11:03:57 +02:00
0f472b53e2 Prepare release 6.5.0 (#1188)
* Prepare k8s collection release 6.5.0

* update release date for the version 6.5.0

* Update changelog.yaml and changelog.rst mismatch

---------

Co-authored-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
2026-07-08 11:06:30 -04:00
a1cd39a71f Update RST documentation files (#1189) (#1190)
(cherry picked from commit 470c042690)

Co-authored-by: Bianca Henderson <bianca@redhat.com>
2026-07-07 17:17:19 -04:00
6742eaa725 Add meta/execution-environment.yml to fix EE builds on UBI images (#1142) (#1183)
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:53:59 -04:00
5c98d5696e Add lint ignore entry (#1184) (#1186)
(cherry picked from commit 75a5560aec)

Co-authored-by: Bianca Henderson <bianca@redhat.com>
2026-07-07 09:43:06 -04:00
78b82c74f7 feat(ci): add security check to block .claude/ and .vscode/ directories (#1173) (#1181)
* 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:50 -04:00
42963f0536 feat: add plugin --keyring option (#1150) (#1179)
* feat: add plugin --keyring option

* docs: add changelog fragment

* Update changelogs/fragments/20260620-add-plugin-keyring-option.yaml



* feat: restrict helm_plugin keyring to install subcommand (#1)

Restrict the keyring option to state=present (helm plugin install),
the only implemented subcommand that supports --keyring, and fail
explicitly when it is used with other states.



* refactor(helm_plugin): warn instead of fail

* Resolve linter error

* Update plugins/modules/helm_plugin.py

---------




(cherry picked from commit 4b3e24bf02)

Co-authored-by: Kenji Gaillac <48765390+Nhqml@users.noreply.github.com>
Co-authored-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
Co-authored-by: Bianca Henderson <bianca@redhat.com>
Co-authored-by: Bianca Henderson <beeankha@gmail.com>
2026-07-02 13:24:50 -04:00
9c3988689f helm: use --rollback-on-failure for atomic on Helm v4 (#1144) (#1178)
* helm: use --rollback-on-failure for atomic on Helm v4

Helm v4 renamed the `--atomic` flag to `--rollback-on-failure`. The old
flag is deprecated on `helm upgrade` and removed entirely from `helm
install`, so `atomic: true` failed against Helm v4 (issue #1143).

Emit the version-appropriate flag from deploy() using the existing
is_helm_v4() helper, covering both the upgrade and the replace/install
code paths. The public `atomic` option is unchanged.

Fixes: https://github.com/ansible-collections/kubernetes.core/issues/1143

Co-Authored-By: Claude Opus 4.8

* fix wrong link in the changelog fragment



---------


(cherry picked from commit bc17b33d44)

Signed-off-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
Co-authored-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
2026-07-01 17:27:39 -04:00
08143fc16f fix(helm): support Helm v4 force/server-side apply flags (#1164) (#1177)
* fix(helm): support Helm v4 force/server-side apply flags

Helm v4 deprecated --force and enables server-side apply by default, so
playbooks relying on force=true broke with "Flag --force has been
deprecated" and "cannot use server-side apply and force replace together".
Because force always meant a client-side delete/recreate replacement, the
module now reproduces that behaviour on v4 (--server-side=false
--force-replace) so existing playbooks keep working unchanged across both
Helm versions.

To let users opt into Helm v4's server-side world explicitly, add
server_side and force_conflicts options. These are mutually exclusive with
force (a client-side replacement cannot coexist with a server-side mode),
keeping the surface unambiguous and surfacing bad combinations up front
instead of as cryptic Helm errors.

AI-assisted commit with Claude Opus

* fix(linter) reformat tests/unit/modules/test_module_helm.py with black

(cherry picked from commit 3634105366)

Co-authored-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
2026-07-01 14:12:24 -04:00
457a7dc534 Point to Python 3.13 for ansible-core devel (#1174) (#1176)
(cherry picked from commit ceeafa8c6d)

Co-authored-by: Bianca Henderson <bianca@redhat.com>
2026-07-01 12:19:06 -04:00
Bianca HendersonandGitHub edee5c994d [manual backport stable-6] Fix CI Test Collision (#1162) (#1167)
* 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:51 -04:00
a523a195cb ci: suppress SonarCloud python:S5443 for test code (#1165) (#1169)
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:49 -04:00
7f5c2183c0 CI - configure precommit hook to block commit when files from .claude… (#1149) (#1171)
* 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:58:06 +02:00
294c2fce4a Fix workflow concurrency issue (#1159) (#1161)
(cherry picked from commit bb80dde66d)

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

Co-authored-by: Bianca Henderson <bianca@redhat.com>
2026-06-26 10:53:17 -04:00
57f4bf76cd helm_registry_auth: document/test stdout for registry success messages (Helm 4.2.1) (#1147) (#1156)
* helm: document/test stdout for registry success messages (Helm 4.2.1)

Helm < 4.2.1 prints registry success messages (Login Succeeded, Pushed,
Pulled, Digest) to stderr (helm/helm#13464); Helm >= 4.2.1 moves them to
stdout (helm/helm#32056). The modules key on the return code, so logic is
unaffected, but the RETURN docs and integration assertions assumed stderr.

- helm_registry_auth: note the version-dependent output stream in
  the RETURN documentation.
- helm_registry_auth integration tests: assert success messages against the
  stdout+stderr union so they pass on both old and new Helm.

Fixes: #1146

Co-Authored-By: Claude Opus 4.8

* ci: empty commit to re-trigger ci

(cherry picked from commit ae90b60fd6)

Co-authored-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
2026-06-25 16:07:10 -04:00
63f490d123 ci: suppress SonarCloud python:S7498 for argument_spec dict() convention (#1152) (#1155)
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:07 -04:00
1d49a942d9 Manual backport of SonarQube configuration to stable-6 branch (#1136)
* Manual backport of SonarQube configuration to stable-6 branch

* Add CI.md and align README with collection standards (#1124)

Include CI.md from #1124 and update README.md to match the Red Hat
Ansible Certified Collection layout from main, with stable-6 branch
references for repository links.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Revert changes to some README links

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-29 17:31:59 -04:00
d8ae230bcf docs: clarify ansible turbo mode with version compatibility notice (#1120) (#1132)
The docs/ansible_turbo_mode.rst file was accidentally removed in PR#988,
breaking the link referenced in README.md. Restore it so users following
that link get the full Turbo mode documentation rather than a 404.

Additionally, document the ansible-core version compatibility issue for
cloud.common (see ansible-collections/cloud.common@5e3430d and
kubernetes.core PR #1109): Turbo mode is incompatible with ansible-core
>= 2.19 because cloud.common no longer supports it. Without this
clarification users on newer ansible-core versions encounter silent or
confusing failures when ENABLE_TURBO_MODE=1 is set.

Update README.md with the same warning so the incompatibility is visible
before users follow the link to the full docs.

Addresses: #927
(cherry picked from commit 248e0d7db9)

Co-authored-by: Yuriy Novostavskiy <yuriy@novostavskiy.kiev.ua>
2026-05-26 09:58:23 -04:00
71e9aba89c Fix unit test failures in CI (#1133) (#1135)
(cherry picked from commit f69761f37c)

Co-authored-by: Bianca Henderson <bianca@redhat.com>
2026-05-25 15:53:21 -04:00
fdebba58bc Kubeconfig module improvement (#1123) (#1131)
* Add kubeconfig module for managing Kubernetes config files

* Remove unnecessary requirement & Change version

* Move functions to module_utils

* Add unit tests

* Add kubeconfig module for managing Kubernetes config files

* Remove unnecessary requirement & Change version

* Move functions to module_utils

* Add unit tests

* Avoid linter errors

* Improve documentation clarity

* Redact sensitive kubeconfig information

* Imprvoe verbosity

* Move import statement for to_native to avoid linters check failure

* Fix linting error

* Add remove behavior

* Add tests for remove behavior

* Imporve documentation

* Add changelog

---------


(cherry picked from commit 53c6c0ee80)

Co-authored-by: Youssef Ali <154611350+YoussefKhalidAli@users.noreply.github.com>
Co-authored-by: Bianca Henderson <bianca@redhat.com>
2026-05-19 14:38:15 -04:00
e87fe77453 Update pod deletion conditions for local storage used in a daemon set pod (#1095) (#1128)
* 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:01 -04:00
714c2f6711 fix(helm_repository): strip trailing slashes from repo_url (#1121) (#1126)
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:28 -04:00
2fb6546b03 docs: add until example to k8s_info (#885) (#1119)
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:32 -04:00
ef9fb67688 Add kubeconfig module for managing Kubernetes config files (#1104) (#1122)
* Add kubeconfig module for managing Kubernetes config files

* Remove unnecessary requirement & Change version

* Move functions to module_utils

* Add unit tests

* Add kubeconfig module for managing Kubernetes config files

* Remove unnecessary requirement & Change version

* Move functions to module_utils

* Add unit tests

* Avoid linter errors

* Improve documentation clarity

* Redact sensitive kubeconfig information

* Imprvoe verbosity

* Move import statement for to_native to avoid linters check failure

* Fix linting error

---------


(cherry picked from commit e79ed52a4d)

Co-authored-by: Youssef Ali <154611350+YoussefKhalidAli@users.noreply.github.com>
Co-authored-by: Bianca Henderson <bianca@redhat.com>
2026-05-06 10:15:42 -04:00
Bianca HendersonandGitHub 90bc4c4b3b Release prep for 6.4.0 (#1101)
SUMMARY

Prep kubernetes.core 6.4.0 release

COMPONENT NAME

Multiple

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
Reviewed-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
Reviewed-by: Bikouo Aubin
Reviewed-by: Hannah DeFazio <h2defazio@gmail.com>
2026-04-22 21:04:10 +00:00
1590c6a4cc Update URL reference in integration-test CI file (#1112) (#1114)
(cherry picked from commit 210467b26d)

Co-authored-by: Bianca Henderson <bianca@redhat.com>
2026-04-22 14:14:06 -04:00
76eccacab6 ci: conditionally test turbo mode and cloud.common (#1109) (#1111)
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:37:48 -04:00
620abbac26 trivial(doc): post #1090 cosmetic update (#1097) (#1107)
SUMMARY
Name of the Helm plays in the integration test framework test updated to reflect the actual version of Helm (addressed comments #1090 (review))
Updated documentation for the modules updated in the PR with the https://github.com/ansible-network/collection_prep, as per CONTRIBUTING.md
ISSUE TYPE

Docs Pull Request

COMPONENT NAME

tests/integration/targets/helm_v3_*/play.yaml
docs/kubernetes.core.helm*.rst

ADDITIONAL INFORMATION
Only cosmetic changes in this PR, so the label skip-changelog is suggested

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
(cherry picked from commit 16e92a20e8)

Co-authored-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
2026-04-21 11:31:11 +02:00
66a820e03a Add sanity test ignores for ansible-core 2.22 (#1102) (#1106)
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:35 -04:00
patchback[bot]andGitHub a3f2438e9d Ensure compatibility with Helm v4 for the collection (#1090) (#1096)
This is a backport of PR #1090 as merged into main (e6076e5).
SUMMARY

Ensure compatibility with Helm v4 for modules helm_plugin and helm_plugin_info
Partially addresses #1038

ISSUE TYPE


Feature Pull Request

COMPONENT NAME

helm_plugin
helm_plugin_info
helm_info
helm_pull
helm_registry_auth
helm
helm_template

Reviewed-by: Bikouo Aubin
Reviewed-by: Matthew Johnson
2026-03-17 15:03:02 +00:00
patchback[bot]andGitHub 0709ea31c9 Support take_ownership parameter in helm installation (#1034) (#1092)
This is a backport of PR #1034 as merged into main (42acb4f).
SUMMARY
Adds support for the take_ownership for initial release installation operations.
ISSUE TYPE

Bugfix Pull Request

COMPONENT NAME
plugins/modules/helm.py
ADDITIONAL INFORMATION
I recently had to migrate a namespace k8s from flat manifest installation into helm a release.
I was so glad to see the take_ownership feature but realized that it work only after first installation of the release.
Seeing no reason to denied this use case i suggest this very simple changes.
To reproduce it:

Create a new namespace in any cluster.
Create a secret
Install any helm chart that deploy the same secret using take_ownership: true.
2026-02-19 16:40:12 +00:00
patchback[bot]andGitHub 44ab1fc478 Add check_mode support for k8s_drain module (#1086) (#1091)
This is a backport of PR #1086 as merged into main (d239adb).
SUMMARY

Closes #1037

added support for check_mode
Converted warnings into informational display when user has explicitly requested to delete daemontset-managed pods, unmanaged pods or pods with local storage


ISSUE TYPE


Feature Pull Request

COMPONENT NAME

k8s_drain

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2026-02-16 20:35:22 +00:00
Bianca HendersonandGitHub 80c33c5573 Prep 6.3.0 release (#1084)
SUMMARY

Prep kubernetes.core 6.3.0 release

COMPONENT NAME

Multiple

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
Reviewed-by: Bikouo Aubin
Reviewed-by: Mike Graves <mgraves@redhat.com>
Reviewed-by: Alina Buzachis
Reviewed-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
Reviewed-by: Rahmanim Benny <brahmani@redhat.com>
2026-02-03 17:03:41 +00:00
patchback[bot]andGitHub 73dc94be68 Add idempotency to helm_pull module (#1055) (#1080)
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:22:52 +00:00
patchback[bot]andGitHub 1bc65230bb Fix incorrect assertion in helm_pull integration test (#1077) (#1079)
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:44:05 +00:00
patchback[bot]andGitHub 91427a5b6a chore(CI): prevent patchback bot from labeling new PRs (#1062) (#1064)
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-29 16:00:40 +00:00
patchback[bot]andGitHub 1d1a23b1ab Replace passing `warnings to exit_json with AnsibleModule.warn` for the few modules (#1033) (#1073)
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 21:14:44 +00:00
patchback[bot]andGitHub 6edc84678d Limit compatibility to Helm =>v3.0.0,<4.0.0 (#1039) (#1071)
This is a backport of PR #1039 as merged into main (13791ec).
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: Bianca Henderson <beeankha@gmail.com>
Reviewed-by: Mike Graves <mgraves@redhat.com>
2026-01-26 19:47:46 +00:00
patchback[bot]andGitHub 66bd8620e4 Replace deprecated ansible.module_utils._text imports (#1053) (#1070)
This is a backport of PR #1053 as merged into main (452fb3d).
SUMMARY
Importing from ansible.module_utils._text is deprecated in ansible-core 2.20 and removed in 2.24. All imports of to_bytes, to_native, and to_text now use ansible.module_utils.common.text.converters.
Before:
from ansible.module_utils._text import to_bytes, to_native, to_text

After:
from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text

ISSUE TYPE

Bugfix Pull Request

COMPONENT NAME
plugins/module_utils/common.py
plugins/action/k8s_info.py
plugins/connection/kubectl.py
plugins/module_utils/{copy.py, k8s/runner.py}
plugins/modules/{k8s_cp.py, k8s_drain.py, k8s_exec.py, k8s_json_patch.py, k8s_scale.py, k8s_taint.py}
ADDITIONAL INFORMATION
It's not an actual Bugfix, more a lifecycle management to ensure compatibility with future Ansible versions.
Tested with ansible-core 2.20 to ensure no deprecation warnings are raised and with ansible-core 2.16 to ensure backward compatibility.
Patrially coauthored-by: GitHub Copilot with Claude Code 4.5 model.
Addresses issue #1052.

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2026-01-26 15:22:45 +00:00
patchback[bot]andGitHub 94b43dc582 Fix K8S_AUTH_VERIFY_SSL environment value handling in kubectl connection plugin (#1049) (#1069)
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:44 +00:00
patchback[bot]andGitHub 3c4f9cee60 chore(doc): update typos (#1059) (#1061)
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-15 21:30:22 +00:00
patchback[bot]andGitHub a54b4a13b6 address sanity issues (#1056) (#1058)
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: Bikouo Aubin
Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2026-01-14 17:08:35 +00:00
patchback[bot]andGitHub e16b3c46b0 Add new workflow to label prs with needs_triage (#1045) (#1048)
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:29:05 +00:00
bc60523372 Add 2.21 ignore file for sanity tests (#1032) (#1036)
SUMMARY

Resolves #1027

Reviewed-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
Reviewed-by: GomathiselviS <gomathiselvi@gmail.com>
(cherry picked from commit 1c16a2d2b5)

Co-authored-by: Bianca Henderson <bianca@redhat.com>
2025-10-24 09:28:46 -04:00
patchback[bot]andGitHub 64f3f07c5a Extend k8s action group (#992) (#1026)
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:47:03 +00:00
patchback[bot]andGitHub d6492b66d9 Selectively redact sensitive kubeconfig data from logs (#1014) (#1024)
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:05 +00:00
patchback[bot]andGitHub 4d5388ddf8 775 document proxy configurations (#1018) (#1020)
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:10 +00:00
Bianca HendersonandGitHub 6dadd06252 Add missing changelog fragments from 5.4.0 and 5.4.1 releases (#1015)
Reviewed-by: Mandar Kulkarni <mandar242@gmail.com>
Reviewed-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
2025-10-07 20:38:26 +00:00
Bianca HendersonandGitHub 69dc7d5c5d Prep 6.2.0 release (#1011)
SUMMARY

Prep kubernetes.core 6.2.0 release

COMPONENT NAME
Multiple

Reviewed-by: Bikouo Aubin
Reviewed-by: Yuriy Novostavskiy <yuriy@novostavskiy.kyiv.ua>
Reviewed-by: Alina Buzachis
Reviewed-by: Bianca Henderson <beeankha@gmail.com>
Reviewed-by: Mandar Kulkarni <mandar242@gmail.com>
2025-10-07 18:18:54 +00:00
patchback[bot]andGitHub 2fa1c2c6e5 Add support of local environment variables in kustomize lookup plugin (#786) (#1010)
This is a backport of PR #786 as merged into main (87344b9).
SUMMARY
kustomize doesn't support an environment that makes it impossible to use HTTP_PROXY or provide some templatized parameters.
This PR is the result of the issue #783
ISSUE TYPE

Feature Pull Request

COMPONENT NAME
kubernetes.core.kustomize lookup plugin

Reviewed-by: Bikouo Aubin
Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2025-10-03 14:34:41 +00:00
patchback[bot]andGitHub f2623dd3cf update doc following #971 (#1006) (#1008)
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:11:20 +00:00
patchback[bot]andGitHub 8772d8c997 Add the PR head as reference to the checkout action of the splitter job. (#981) (#1005)
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:12:05 +00:00
patchback[bot]andGitHub a32108f64f Added support for copying files to init Containers. (#971) (#1003)
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:07:52 +00:00
patchback[bot]andGitHub 365e5e9159 Add support for skip-schema-validation in helm module (#995) (#1001)
This is a backport of PR #995 as merged into main (da93cce).
SUMMARY
This pull request adds support for a new skip_schema_validation option to the helm module, allowing users to disable JSON schema validation for Helm charts and values (requires helm >= 3.16.0).
ISSUE TYPE

Feature Pull Request

COMPONENT NAME
helm
ADDITIONAL INFORMATION
Added the skip_schema_validation boolean parameter to the helm module, allowing users to disable JSON schema validation for charts and values. This option is only available with Helm versions >= 3.16.0, and an appropriate error is raised for older versions.
Added integration tests to verify the behavior of the skip_schema_validation option, including cases for both supported and unsupported Helm versions.
Closes #994

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2025-09-24 20:29:07 +00:00
patchback[bot]andGitHub 448a68da3d Changelog fixes (#989) (#990)
This is a backport of PR #989 as merged into main (6158300).
SUMMARY

Changelog fixes

ISSUE TYPE


Docs Pull Request

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
Reviewed-by: Chyna Sanders
2025-09-22 20:14:29 +00:00
patchback[bot]andGitHub 46acab9c4c [CI Fix] Remove ansible.module_utils.six imports (#998) (#1000)
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:49:02 +00:00
Bianca HendersonandGitHub fdb77182c8 Update/correct stable-6 changelog (#987)
SUMMARY
A part of the changelog referring to reverted changes was left in; this PR updates the changelog files to accurately reflect the state of stable-6/6.1.0 release.

Reviewed-by: Yuriy Novostavskiy
Reviewed-by: Alina Buzachis
2025-08-13 08:34:52 +00:00
Alina BuzachisandGitHub fa3d94f793 Prep kubernetes.core 6.1.0 (#977)
SUMMARY


ISSUE TYPE


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

COMPONENT NAME

ADDITIONAL INFORMATION

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

Bugfix Pull Request

COMPONENT NAME
CI
ADDITIONAL INFORMATION

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

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

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

kubevirt/kubevirt.core#145
ISSUE TYPE


Bugfix Pull Request

COMPONENT NAME

kubernetes.core.module_utils.k8s.service
ADDITIONAL INFORMATION


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

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

ISSUE TYPE

Feature Pull Request

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

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

Feature Pull Request

COMPONENT NAME

kubernetes.core.helm

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

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

ISSUE TYPE


Bugfix Pull Request

COMPONENT NAME

kubeconfig

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

Bugfix Pull Request

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

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

Resolves #344

This revision adds the following test coverage:

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

COMPONENT NAME

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

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

Bugfix Pull Request

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

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

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

ISSUE TYPE


Feature Pull Request

COMPONENT NAME

helm, helm_pull and helm_template
ADDITIONAL INFORMATION


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

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

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

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

ISSUE TYPE


Feature Pull Request

COMPONENT NAME
Multiple

Reviewed-by: Bikouo Aubin
2025-06-03 16:56:33 +00:00
Bikouo AubinandGitHub 94c1f57f36 Push 5.x.x changes into main branch (#932)
Release 5.3.0 is out, update the main branch to reflect these changes.

Reviewed-by: Yuriy Novostavskiy
Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2025-05-16 16:06:45 +00:00
Bianca HendersonandGitHub d0b97319a5 Update README to remove information about backports. (#930)
Per this comment, I am removing information about backports that were added in #926; per the Cloud Content Handbook page on backports, we will only be backporting to the two latest versions, and since mentioning specific branches and versions in this collection's README in this manner will add to future maintenance/upkeep burden, I opted to remove this line entirely.
I will be creating a separate PR to manually backport the new README information to stable-5.

Reviewed-by: Mike Graves <mgraves@redhat.com>
Reviewed-by: Alina Buzachis
2025-05-15 13:45:09 +00:00
Bianca HendersonandGitHub 38d5c81051 Add information in README stating stable-4 is no longer supported (#926)
SUMMARY

Resolves ACA-2383.

ISSUE TYPE


Docs Pull Request

COMPONENT NAME

README.md
ADDITIONAL INFORMATION
Also added information about backporting only bugfixes to stable-3 and made some minor capitalization edits.

Reviewed-by: Bikouo Aubin
Reviewed-by: Yuriy Novostavskiy
Reviewed-by: Mike Graves <mgraves@redhat.com>
Reviewed-by: Alina Buzachis
2025-05-14 17:13:52 +00:00
Noah LehmannandGitHub 914a16ec5c Add helm insecure skip tls verify (#901)
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: Yuriy Novostavskiy
Reviewed-by: Noah Lehmann
Reviewed-by: Bikouo Aubin
Reviewed-by: Bianca Henderson <beeankha@gmail.com>
Reviewed-by: Mike Graves <mgraves@redhat.com>
2025-05-02 16:24:26 +00:00
Yuriy NovostavskiyandGitHub cb2070c93f Initial update to 6.0.0-dev0: remove support of ansible-core<2.16.0 and k8s inventory plugin (#867)
SUMMARY
This is initial to prepare the main branch to version 6.0.0 (6.0.0-dev0 in galaxy.yml) and includes following braking changes:

removed support of ansible-core<2.16.0 as 2.15 reach EOL in Nov 2024;
removed the k8s inventory plugin that was deprecated in release 3.0.0.

ISSUE TYPE

Feature Pull Request

COMPONENT NAME

Documentation
galaxy.yml
inventory/k8s.py

ADDITIONAL INFORMATION
The initial version of this PR doesn't remove tests/sanity/ignore-2.14.txt and tests/sanity/ignore-2.15.txt, and CI part will require removing version 2.15 from the matrix in https://github.com/ansible-network/github_actions, so, we have external dependency here.

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
Reviewed-by: Yuriy Novostavskiy
Reviewed-by: Mike Graves <mgraves@redhat.com>
2025-04-29 18:23:11 +00:00
Bianca HendersonandGitHub b594d35931 Update ansible-lint version to 25.1.2 (#919)
* Update ansible-lint version to 25.1.2

* Add changelog file
2025-04-29 11:54:09 -04:00
b0z02003andGitHub 00699ac3e5 add reset_then_reuse_values support to helm module (#802)
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: Bikouo Aubin
Reviewed-by: Yuriy Novostavskiy
Reviewed-by: b0z02003
Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2025-04-28 15:11:58 +00:00
Bikouo AubinandGitHub d329e7ee42 Rebase PR #898 (#905)
This PR is a rebase of #898 for CI to pass
Thanks @efussi for your collaboration.
Closes #892

Reviewed-by: Yuriy Novostavskiy
Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2025-04-25 05:31:03 +00:00
Yuriy NovostavskiyandGitHub d4fc22c74e Bugfix: fix unit-source for pre-release of ansible-core 2.20 (devel and milestone branch) (#903)
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>
2025-04-24 14:56:24 +00:00
Mike GravesandGitHub b648f45e90 Prep 5.2.0 release (#891) (#896)
SUMMARY
Prep 5.2.0 release
ISSUE TYPE
COMPONENT NAME
ADDITIONAL INFORMATION
Reviewed-by: Yuriy Novostavskiy
Reviewed-by: Bikouo Aubin
Reviewed-by: Alina Buzachis
(cherry picked from commit 0eff03d)
SUMMARY


ISSUE TYPE


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

COMPONENT NAME

ADDITIONAL INFORMATION

Reviewed-by: Yuriy Novostavskiy
Reviewed-by: GomathiselviS <gomathiselvi@gmail.com>
2025-04-02 13:39:41 +00:00
Bikouo AubinandGitHub 2cb5d6c316 Run integration tests using ansible-core 2.19 (#888)
* 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
2025-04-01 11:15:30 +02:00
Bikouo AubinandGitHub 0e7229cf8d Push changes from 3.3.1 into main branch (#893)
Release 3.3.1 is out; push changes to main branch

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2025-03-31 09:06:26 +00:00
Will ThamesandGitHub 9ec6912325 Extend hidden_fields to allow more complicated field definitions (#872)
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
Reviewed-by: Helen Bailey <hebailey@redhat.com>
Reviewed-by: GomathiselviS <gomathiselvi@gmail.com>
Reviewed-by: Alina Buzachis
2025-03-20 10:35:51 +00:00
Steve OvensandGitHub 7cdf0d03f5 waiter.py Add ClusterOperator Test (#879)
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: Mandar Kulkarni <mandar242@gmail.com>
Reviewed-by: Bikouo Aubin
2025-02-26 17:53:12 +00:00
Yuriy NovostavskiyandGitHub 91df2f10bc Fix linters in CI (#873)
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>
Reviewed-by: Yuriy Novostavskiy
2025-02-06 15:16:55 +00:00
Yuriy NovostavskiyandGitHub 1943dfc3d9 Post release 5.1.0 update (#866)
SUMMARY
This is a post-5.1.0 documentation update of the main branch that includes a cherry-pic of the changelog and an update version to 5.2.0-dev0.
ISSUE TYPE

Docs Pull Request

COMPONENT NAME

changelog
galaxy.yml

ADDITIONAL INFORMATION
The reason for this version bump is to understand of version when the collection is installed as ansible-galaxy collection install git+https://github.com/ansible-collections/kubernetes.core.git and don't mess up the main (that may contain some PRs that is not included to any released version) with the released version 5.1.0.

Reviewed-by: Mike Graves <mgraves@redhat.com>
Reviewed-by: Yuriy Novostavskiy
2025-01-21 15:53:54 +00:00
Yuriy NovostavskiyandGitHub eb731cd3a5 Remove deprecated .github/stale.yml to address #837 (#838)
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>
2025-01-17 16:26:28 +00:00
Irum MalikandGitHub ecc64cace1 helm_pull: Silence false no_log warning (#796)
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

Reviewed-by: Yuriy Novostavskiy
Reviewed-by: Mike Graves <mgraves@redhat.com>
Reviewed-by: Irum Malik
2025-01-17 15:52:58 +00:00
Yuriy NovostavskiyandGitHub bc0de24cba trivial doc: replace 2.5.0 with 3.0.0 (#831)
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

Reviewed-by: Mike Graves <mgraves@redhat.com>
2025-01-17 15:43:51 +00:00
Mike GravesandGitHub 9f60b151ba Clean up test namespace (#852)
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

Reviewed-by: Alina Buzachis
Reviewed-by: Yuriy Novostavskiy
2025-01-17 14:53:21 +00:00
Yuriy NovostavskiyandGitHub 159a63af97 fix linters in github actions (#848)
Fix bug #846
within this commit ansible/ansible-lint updated to 24.12.2 and config moved to .config folder
2025-01-16 14:45:27 -05:00
Bikouo AubinandGitHub 6efabd3418 Remove kubeconfig value from module invocation log (#826) 2024-12-17 17:50:22 +01:00
aee847431a helm_registry_auth module to authenticate in OCI registry (#800)
* 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>
2024-12-17 15:39:42 +01:00
Yuriy NovostavskiyandGitHub 6609abdd5a Parameter insecure_registry added to helm_template (#805)
* Parameter insecure_registry added to helm_template as equivalent of insecure-skip-tls-verify
2024-12-17 11:59:14 +01:00
219c747a24 fix: typo (#804)
* 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>
2024-12-17 11:58:33 +01:00
Bikouo AubinandGitHub 7559b65946 Fix helm integration tests (#830)
SUMMARY
Fix charts ref on integration tests targets
ISSUE TYPE


Bugfix Pull Request

Reviewed-by: Yuriy Novostavskiy
Reviewed-by: Alina Buzachis
2024-12-17 10:18:17 +00:00
Mike GravesandGitHub c8a33c7180 Fix helm tests (#827)
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: Helen Bailey <hebailey@redhat.com>
Reviewed-by: Yuriy Novostavskiy
2024-12-13 21:50:37 +00:00
Ottavia BalducciandGitHub 52f2cb5587 Improve error message for pod disruption budget when draining a node (#798)
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

Reviewed-by: Mike Graves <mgraves@redhat.com>
2024-12-11 14:45:47 +00:00
Mike GravesandGitHub 513ff66fcf Remove kubevirt integration test workflow (#806)
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: Bikouo Aubin
Reviewed-by: Helen Bailey <hebailey@redhat.com>
Reviewed-by: Mike Graves <mgraves@redhat.com>
2024-12-10 16:18:14 +00:00
Ottavia BalducciandGitHub fca0dc0485 Fix k8s_drain runs into timeout with pods from stateful sets. (#793)
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

Reviewed-by: Mike Graves <mgraves@redhat.com>
2024-12-10 15:35:07 +00:00
Yuriy NovostavskiyandGitHub cd686316e9 [ci] fix github actions post 2.18 (#789)
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: Andrew Klychkov <aklychko@redhat.com>
Reviewed-by: Mike Graves <mgraves@redhat.com>
2024-11-04 17:12:45 +00:00
Yuriy NovostavskiyandGitHub b8e9873f64 Update README.md with removing outdated communication channels (#790)
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](https://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
2024-11-04 14:31:08 +01:00
Ottavia BalducciandGitHub 4c305e73f0 Make k8s_drain work when only one pod is present (#770)
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

Reviewed-by: Mike Graves <mgraves@redhat.com>
2024-11-01 14:22:27 +00:00
Andrew KlychkovandGitHub c8a9326306 CONTRIBUTING.md remove IRC (#778) 2024-09-05 09:07:17 +02:00
Andrew KlychkovandGitHub 445d367059 README: Add Communication section with Forum information (#774) 2024-08-19 10:57:24 +02:00
GomathiselviSandGitHub fdb8af7ca9 Update Readme to match the template (#767)
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

Reviewed-by: Alina Buzachis
2024-07-31 13:37:02 +00:00
Mandar KulkarniandGitHub a89f19b4e5 Bump the ansible-lint version to 24.7.0 (#765)
* add minimum version for  ansible-lint to 24.7.0

* added changelog fragment

* add newline at eof
2024-07-26 13:48:56 -04:00
QCUandGitHub 5bc53dba7c fix: kustomize plugin fails with deprecation warnings (#728)
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>
Reviewed-by: QCU
2024-07-15 13:29:23 +00:00
Artur ZałęskiandGitHub b07fbd6271 Fix waiting for daemonset when desired number of pods is 0 (#756)
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 13:58:37 +00:00
Mike GravesandGitHub 44a2fc392a Merge pull request #757 from gravesm/gha-python-version
Remove ansible install step from kubevirt GHA
2024-07-09 11:52:07 -04:00
Mike Graves 6265a3e7ce Remove ansible install step from kubevirt GHA
Ansible 2.17 is already included in the ubuntu-latest runner image, so
there's no need for a separate install step. It was broken in any case
because the python version being used was too low for ansible 2.18.
2024-07-09 09:51:36 -04:00
Yuriy NovostavskiyandGitHub 0afd257dd0 fix shields.io badges in README.md (#749)
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:

Reviewed-by: Mike Graves <mgraves@redhat.com>
Reviewed-by: Yuriy Novostavskiy
2024-06-18 13:55:25 +00:00
Yuriy NovostavskiyandGitHub d192157ed8 update changelog with release 3.2.0 (#750)
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.

Reviewed-by: Mike Graves <mgraves@redhat.com>
2024-06-17 18:58:44 +00:00
Eric GandGitHub 6a04f42d0b helm: Accept release candidate versions for compatibility checks (#745)
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: Yuriy Novostavskiy
Reviewed-by: Eric G.
Reviewed-by: Mike Graves <mgraves@redhat.com>
2024-06-17 18:58:42 +00:00
Bikouo AubinandGitHub 5064d722c3 Update changelog after release 5.0.0 (#747)
Push change from stable-5 after release 5.0.0

Reviewed-by: Mike Graves <mgraves@redhat.com>
Reviewed-by: Yuriy Novostavskiy
2024-06-13 10:02:28 +00:00
Yuriy NovostavskiyandGitHub fb80d973c4 Doc: add example of using kubectl connection plugin (#741)
Doc: add example of using kubectl connection plugin

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: Bikouo Aubin
Reviewed-by: Sandra McCann <samccann@redhat.com>
Reviewed-by: Mike Graves <mgraves@redhat.com>
Reviewed-by: Yuriy Novostavskiy
Reviewed-by: purdzan
2024-06-06 13:48:15 +00:00
Bikouo AubinandGitHub 8363a4debf Remove support for ansible-core<2.15 (#737)
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>
2024-05-31 07:41:07 +00:00
Bikouo AubinandGitHub 0c5233a650 Defer removal of inventory/k8s to 6.0.0 (#734)
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>
2024-05-31 07:41:04 +00:00
Bikouo AubinandGitHub c0666a5137 kubevirt.core collection cross testing (#731)
* Initial

* update python version

* update python version

* checkout local version of collection

* add integration job

* indent

* Set workflow as non blocking
2024-05-30 15:34:29 +02:00
178 changed files with 7556 additions and 2876 deletions
+1
View File
@@ -17,6 +17,7 @@ tests/integration/cloud-config-*
# Helm charts
tests/integration/*-chart-*.tgz
tests/integration/targets/*/*.tgz
# ansible-test generated file
tests/integration/inventory
+134 -43
View File
@@ -4,19 +4,24 @@ Kubernetes Collection Release Notes
.. contents:: Topics
v5.5.0
v6.6.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).
- 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
-------------------
@@ -32,51 +37,85 @@ 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).
v5.4.4
v6.5.0
======
Release Summary
---------------
This release corrects the documented and enforced minimum ``ansible-core`` version to ``>=2.16.0``.
Bugfixes
--------
- 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).
v5.4.3
======
Release Summary
---------------
This release contains bugfixes such as improved idempotency for helm repository URLs with trailing slashes.
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).
- 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).
v5.4.2
======
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 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 ``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).
- 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
-------------------
@@ -93,12 +132,64 @@ 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).
- 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
======
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.4.1
======
@@ -111,7 +202,7 @@ 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).
- 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).
v5.4.0
@@ -138,15 +229,15 @@ This release includes minor changes, bug fixes and also bumps ``ansible-lint`` v
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 2.19`` (https://github.com/ansible-collections/kubernetes.core/pull/888).
- helm - add ``reset_then_reuse_values`` support to helm module (https://github.com/ansible-collections/kubernetes.core/issues/803).
- helm - add support for ``insecure_skip_tls_verify`` option to helm and ``helm_repository`` (https://github.com/ansible-collections/kubernetes.core/issues/694).
- kubernetes.core - Bump version of ``ansible-lint`` to ``25.1.2`` (https://github.com/ansible-collections/kubernetes.core/pull/919).
- helm - add support for ``insecure_skip_tls_verify`` option to helm and helm_repository(https://github.com/ansible-collections/kubernetes.core/issues/694).
Bugfixes
--------
- module_utils/k8s/service - fix issue when trying to delete resource using `delete_options` and `check_mode=true` (https://github.com/ansible-collections/kubernetes.core/issues/892).
- module_utils/k8s/service - fix issue when trying to delete resource using ``delete_options`` and ``check_mode=true`` (https://github.com/ansible-collections/kubernetes.core/issues/892).
v5.2.0
======
+1 -1
View File
@@ -1,5 +1,5 @@
# Also needs to be updated in galaxy.yml
VERSION = 5.5.0
VERSION = 6.6.0
TEST_ARGS ?= ""
PYTHON_VERSION ?= `python -c 'import platform; print(".".join(platform.python_version_tuple()[0:2]))'`
+33 -37
View File
@@ -22,47 +22,43 @@ Click on the name of a plugin or module to view that content's documentation:
### Connection plugins
Name | Description
--- | ---
[kubernetes.core.kubectl](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/docs/kubernetes.core.kubectl_connection.rst)|Execute tasks in pods running on Kubernetes.
[kubernetes.core.kubectl](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.kubectl_connection.rst)|Execute tasks in pods running on Kubernetes.
### K8s filter plugins
Name | Description
--- | ---
kubernetes.core.k8s_config_resource_name|Generate resource name for the given resource of type ConfigMap, Secret
### Inventory plugins
Name | Description
--- | ---
[kubernetes.core.k8s](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/docs/kubernetes.core.k8s_inventory.rst)|Kubernetes (K8s) inventory source
### Lookup plugins
Name | Description
--- | ---
[kubernetes.core.k8s](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/docs/kubernetes.core.k8s_lookup.rst)|Query the K8s API
[kubernetes.core.kustomize](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/docs/kubernetes.core.kustomize_lookup.rst)|Build a set of kubernetes resources using a 'kustomization.yaml' file.
[kubernetes.core.k8s](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_lookup.rst)|Query the K8s API
[kubernetes.core.kustomize](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.kustomize_lookup.rst)|Build a set of kubernetes resources using a 'kustomization.yaml' file.
### Modules
Name | Description
--- | ---
[kubernetes.core.helm](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/docs/kubernetes.core.helm_module.rst)|Manages Kubernetes packages with the Helm package manager
[kubernetes.core.helm_info](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/docs/kubernetes.core.helm_info_module.rst)|Get information from Helm package deployed inside the cluster
[kubernetes.core.helm_plugin](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/docs/kubernetes.core.helm_plugin_module.rst)|Manage Helm plugins
[kubernetes.core.helm_plugin_info](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/docs/kubernetes.core.helm_plugin_info_module.rst)|Gather information about Helm plugins
[kubernetes.core.helm_pull](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/docs/kubernetes.core.helm_pull_module.rst)|download a chart from a repository and (optionally) unpack it in local directory.
[kubernetes.core.helm_registry_auth](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/docs/kubernetes.core.helm_registry_auth_module.rst)|Helm registry authentication module
[kubernetes.core.helm_repository](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/docs/kubernetes.core.helm_repository_module.rst)|Manage Helm repositories.
[kubernetes.core.helm_template](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/docs/kubernetes.core.helm_template_module.rst)|Render chart templates
[kubernetes.core.k8s](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/docs/kubernetes.core.k8s_module.rst)|Manage Kubernetes (K8s) objects
[kubernetes.core.k8s_cluster_info](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/docs/kubernetes.core.k8s_cluster_info_module.rst)|Describe Kubernetes (K8s) cluster, APIs available and their respective versions
[kubernetes.core.k8s_cp](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/docs/kubernetes.core.k8s_cp_module.rst)|Copy files and directories to and from pod.
[kubernetes.core.k8s_drain](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/docs/kubernetes.core.k8s_drain_module.rst)|Drain, Cordon, or Uncordon node in k8s cluster
[kubernetes.core.k8s_exec](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/docs/kubernetes.core.k8s_exec_module.rst)|Execute command in Pod
[kubernetes.core.k8s_info](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/docs/kubernetes.core.k8s_info_module.rst)|Describe Kubernetes (K8s) objects
[kubernetes.core.k8s_json_patch](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/docs/kubernetes.core.k8s_json_patch_module.rst)|Apply JSON patch operations to existing objects
[kubernetes.core.k8s_log](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/docs/kubernetes.core.k8s_log_module.rst)|Fetch logs from Kubernetes resources
[kubernetes.core.k8s_rollback](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/docs/kubernetes.core.k8s_rollback_module.rst)|Rollback Kubernetes (K8S) Deployments and DaemonSets
[kubernetes.core.k8s_scale](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/docs/kubernetes.core.k8s_scale_module.rst)|Set a new size for a Deployment, ReplicaSet, Replication Controller, or Job.
[kubernetes.core.k8s_service](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/docs/kubernetes.core.k8s_service_module.rst)|Manage Services on Kubernetes
[kubernetes.core.k8s_taint](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/docs/kubernetes.core.k8s_taint_module.rst)|Taint a node in a Kubernetes/OpenShift cluster
[kubernetes.core.helm](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.helm_module.rst)|Manages Kubernetes packages with the Helm package manager
[kubernetes.core.helm_info](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.helm_info_module.rst)|Get information from Helm package deployed inside the cluster
[kubernetes.core.helm_plugin](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.helm_plugin_module.rst)|Manage Helm plugins
[kubernetes.core.helm_plugin_info](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.helm_plugin_info_module.rst)|Gather information about Helm plugins
[kubernetes.core.helm_pull](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.helm_pull_module.rst)|download a chart from a repository and (optionally) unpack it in local directory.
[kubernetes.core.helm_registry_auth](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.helm_registry_auth_module.rst)|Helm registry authentication module
[kubernetes.core.helm_repository](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.helm_repository_module.rst)|Manage Helm repositories.
[kubernetes.core.helm_template](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.helm_template_module.rst)|Render chart templates
[kubernetes.core.k8s](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_module.rst)|Manage Kubernetes (K8s) objects
[kubernetes.core.k8s_cluster_info](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_cluster_info_module.rst)|Describe Kubernetes (K8s) cluster, APIs available and their respective versions
[kubernetes.core.k8s_cp](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_cp_module.rst)|Copy files and directories to and from pod.
[kubernetes.core.k8s_drain](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_drain_module.rst)|Drain, Cordon, or Uncordon node in k8s cluster
[kubernetes.core.k8s_exec](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_exec_module.rst)|Execute command in Pod
[kubernetes.core.k8s_info](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_info_module.rst)|Describe Kubernetes (K8s) objects
[kubernetes.core.k8s_json_patch](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_json_patch_module.rst)|Apply JSON patch operations to existing objects
[kubernetes.core.k8s_log](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_log_module.rst)|Fetch logs from Kubernetes resources
[kubernetes.core.k8s_rollback](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_rollback_module.rst)|Rollback Kubernetes (K8S) Deployments and DaemonSets
[kubernetes.core.k8s_scale](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_scale_module.rst)|Set a new size for a Deployment, ReplicaSet, Replication Controller, or Job.
[kubernetes.core.k8s_service](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_service_module.rst)|Manage Services on Kubernetes
[kubernetes.core.k8s_taint](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_taint_module.rst)|Taint a node in a Kubernetes/OpenShift cluster
[kubernetes.core.kubeconfig](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.kubeconfig_module.rst)|Generate, update, and optionally write Kubernetes kubeconfig files
<!--end collection content-->
@@ -80,7 +76,7 @@ PEP440 is the schema used to describe the versions of Ansible.
### Helm Version Compatibility
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.
This collection supports Helm v3.x and newer. Please note that specific modules or certain parameters may have additional version requirements.
### Python Support
@@ -104,7 +100,7 @@ You can also include it in a `requirements.yml` file and install it via `ansible
---
collections:
- name: kubernetes.core
version: 5.5.0
version: 6.6.0
```
### Installing the Kubernetes Python Library
@@ -203,7 +199,7 @@ The ``kubernetes.core`` collection supports Ansible Turbo mode as a tech preview
To enable Turbo mode for k8s lookup plugin, set the environment variable `ENABLE_TURBO_MODE=1` on the managed node. This is not working when
defined in the playbook using `environment` keyword as above, you must set it using `export ENABLE_TURBO_MODE=1`.
Please read more about Ansible Turbo mode - [here](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/docs/ansible_turbo_mode.rst).
Please read more about Ansible Turbo mode - [here](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/ansible_turbo_mode.rst).
## Testing
@@ -230,7 +226,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.
See [Contributing to kubernetes.core](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/CONTRIBUTING.md).
See [Contributing to kubernetes.core](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/CONTRIBUTING.md).
Join the Ansible community:
@@ -255,7 +251,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.
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).
For the latest supported versions, see [Release Notes and Roadmap](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/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/).
@@ -282,9 +278,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)
* [Ansible communication guide](https://docs.ansible.com/ansible/devel/community/communication.html)
* [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/stable-5/SONARCLOUD.md)
* [Ansible Turbo mode (tech preview)](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/docs/ansible_turbo_mode.rst)
* [Continuous integration (CI) overview](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/CI.md)
* [SonarCloud integration](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/SONARCLOUD.md)
* [Ansible Turbo mode (tech preview)](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/ansible_turbo_mode.rst)
### Code of conduct
@@ -296,4 +292,4 @@ If you encounter abusive behavior, please refer to the [policy violations](https
GNU General Public License v3.0 or later
See [LICENSE](https://github.com/ansible-collections/kubernetes.core/blob/stable-5/LICENSE) to see the full text.
See [LICENSE](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/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).
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.
The **coverage** job (in **`all_green`**) uses **`ansible-test`** (`units --coverage`, then **`coverage combine`** / **`coverage xml`**) with **ansible-core `stable-2.18`** on **`stable-6`**, 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`**.
+198 -38
View File
@@ -1027,14 +1027,13 @@ releases:
changes:
bugfixes:
- module_utils/k8s/service - fix issue when trying to delete resource using
`delete_options` and `check_mode=true` (https://github.com/ansible-collections/kubernetes.core/issues/892).
``delete_options`` and ``check_mode=true`` (https://github.com/ansible-collections/kubernetes.core/issues/892).
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
2.19`` (https://github.com/ansible-collections/kubernetes.core/pull/888).
- helm - add ``reset_then_reuse_values`` support to helm module (https://github.com/ansible-collections/kubernetes.core/issues/803).
- helm - add support for ``insecure_skip_tls_verify`` option to helm and ``helm_repository``
(https://github.com/ansible-collections/kubernetes.core/issues/694).
- kubernetes.core - Bump version of ``ansible-lint`` to ``25.1.2`` (https://github.com/ansible-collections/kubernetes.core/pull/919).
- helm - add support for ``insecure_skip_tls_verify`` option to helm and helm_repository(https://github.com/ansible-collections/kubernetes.core/issues/694).
release_summary: This release includes minor changes, bug fixes and also bumps
``ansible-lint`` version to ``25.1.2``.
fragments:
@@ -1063,7 +1062,7 @@ releases:
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).
- 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).
release_summary: This release includes bugfixes for k8s service field handling,
k8s_cp init containers support, and removes deprecated ansible.module_utils.six
@@ -1074,12 +1073,67 @@ releases:
- 20250922-remove-ansible-six-imports.yaml
- 5.4.1.yml
release_date: '2025-10-07'
5.4.2:
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
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``
@@ -1097,14 +1151,14 @@ releases:
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:
- helm - Add ``release_values`` key to ``status`` return value that can be accessed
- 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
- 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 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.
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).
@@ -1114,52 +1168,125 @@ releases:
- 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
- 5-4-2.yaml
- 6-3-0.yaml
release_date: '2026-02-03'
5.4.3:
6.4.0:
changes:
bugfixes:
- ee - Add ``meta/execution-environment.yml`` to decouple ansible-builder EE
builds from the ``openshift-clients`` system dependency declared in ``bindep.txt``,
- 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_repository - Correct handling of repository URLs with trailing slashes
- 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).
release_summary: This release contains bugfixes such as improved idempotency
for helm repository URLs with trailing slashes.
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
- 5-4-3.yml
- 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'
5.4.4:
changes:
bugfixes:
- 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).
release_summary: This release corrects the documented and enforced minimum ``ansible-core``
version to ``>=2.16.0``.
release_date: '2026-07-09'
5.5.0:
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:
@@ -1180,23 +1307,56 @@ releases:
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).
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``.
- 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
- 5.5.0.yml
- deprecate-enable-turbo-mode.yml
- fix-ansible-lint-warnings.yaml
release_date: '2026-09-15'
release_date: '2026-09-16'
+3 -2
View File
@@ -34,8 +34,9 @@ Synopsis
Requirements
------------
The following requirement is needed on the host that executes this module.
The following requirements are 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)
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::
@@ -158,4 +159,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
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:
- Ansible 2.9.17 or latest installed
- Ansible 2.16.0 or latest installed
- `Kubernetes Python client <https://pypi.org/project/kubernetes/>`_ installed on the host that will execute the modules.
@@ -42,6 +42,92 @@ Basic authentication is also supported using the ``username`` and ``password`` o
To disable SSL certificate verification, set ``verify_ssl`` to false.
Sharing options across tasks with action groups
===============================================
Repeating the same authentication options on every task gets verbose quickly. The collection
defines two `action groups <https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_module_defaults.html#module-defaults-groups>`_
so you can set them once with ``module_defaults``:
``kubernetes.core.k8s``
Modules that talk to the Kubernetes API and accept the standard authentication options
(``kubeconfig``, ``context``, ``host``, ``api_key``, ``validate_certs``, and so on):
``k8s``, ``k8s_cluster_info``, ``k8s_cp``, ``k8s_drain``, ``k8s_exec``, ``k8s_info``,
``k8s_json_patch``, ``k8s_log``, ``k8s_rollback``, ``k8s_scale``, ``k8s_service``, and
``k8s_taint``.
``kubernetes.core.helm``
Modules that shell out to the ``helm`` binary and accept its shared authentication
options (``binary_path``, ``kubeconfig``, ``context``, ``host``, ``api_key``,
``ca_cert``, ``validate_certs``): ``helm``, ``helm_info``, ``helm_plugin``,
``helm_plugin_info``, and ``helm_repository``.
Prefix the group name with ``group/`` to use it:
.. code-block:: yaml
- hosts: localhost
module_defaults:
group/kubernetes.core.k8s:
kubeconfig: /path/to/kubeconfig
context: staging
group/kubernetes.core.helm:
binary_path: /path/to/helm
kubeconfig: /path/to/kubeconfig
context: staging
tasks:
- name: Create a namespace
kubernetes.core.k8s:
definition:
apiVersion: v1
kind: Namespace
metadata:
name: monitoring
- name: Read it back
kubernetes.core.k8s_info:
kind: Namespace
name: monitoring
- name: Add the prometheus chart repository
kubernetes.core.helm_repository:
name: prometheus-community
repo_url: https://prometheus-community.github.io/helm-charts
- name: Deploy the kube-prometheus-stack chart
kubernetes.core.helm:
name: kube-prometheus-stack
chart_ref: prometheus-community/kube-prometheus-stack
release_namespace: monitoring
- name: Collect the releases in that namespace
kubernetes.core.helm_info:
name: kube-prometheus-stack
release_namespace: monitoring
Every task picks up ``kubeconfig`` and ``context`` from its group without repeating them, the
``helm`` modules additionally pick up ``binary_path``, and an option set on an individual task
still wins over the group default.
.. note::
Always write the group name fully qualified as ``group/kubernetes.core.k8s``. A bare
``group/k8s`` refers to the legacy ``k8s`` group that ansible-core defined back when the
Kubernetes modules shipped in core itself. The two are not the same group, and the legacy
one does not cover the modules in this collection.
Some modules are deliberately **not** in these groups because they do not accept the shared
authentication options, and including them would make ``module_defaults`` fail for everyone
using the group:
- ``helm_pull`` and ``helm_template`` accept only ``binary_path``.
- ``helm_registry_auth`` accepts ``binary_path`` and its own ``host``, which is an OCI
registry URL rather than a Kubernetes API server.
- ``kubeconfig`` writes a kubeconfig file locally and takes no cluster connection options.
Pass options to those modules directly, or give them their own per-module ``module_defaults``
entry.
Reporting an issue
==================
@@ -1,88 +0,0 @@
.. _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,6 +13,5 @@ To get started, please select one of the following topics.
:maxdepth: 1
kubernetes_scenarios/k8s_intro
kubernetes_scenarios/k8s_inventory
kubernetes_scenarios/k8s_scenarios
+1 -1
View File
@@ -25,7 +25,7 @@ Requirements
------------
The below requirements are needed on the host that executes this module.
- helm (https://github.com/helm/helm/releases)
- helm >= 3.0.0 (https://github.com/helm/helm/releases)
- yaml (https://pypi.org/project/PyYAML/)
+187 -4
View File
@@ -25,7 +25,7 @@ Requirements
------------
The below requirements are needed on the host that executes this module.
- helm (https://github.com/helm/helm/releases)
- helm >= 3.0.0 (https://github.com/helm/helm/releases)
- yaml (https://pypi.org/project/PyYAML/)
@@ -73,6 +73,7 @@ Parameters
</td>
<td>
<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>
</tr>
<tr>
@@ -156,6 +157,29 @@ Parameters
<div>Chart version to install. If this is not specified, the latest version is installed.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>cleanup_on_fail</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.6.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&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>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -254,6 +278,30 @@ Parameters
</td>
<td>
<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>
</tr>
<tr>
@@ -330,6 +378,27 @@ Parameters
<div style="font-size: small; color: darkgreen"><br/>aliases: kubeconfig_path</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>plain_http</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.1.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&nbsp;&larr;</div></li>
<li>yes</li>
</ul>
</td>
<td>
<div>Use HTTP instead of HTTPS when working with OCI registries</div>
<div>Requires Helm &gt;= 3.13.0</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -476,7 +545,9 @@ Parameters
</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>If O(reset_values) or O(reuse_values) is set to V(True), this is ignored.</div>
<div>Helm ignores this when <code>--reset-values</code> or <code>--reuse-values</code> is passed. Since O(reset_values) defaults to V(true), it has to be set to V(false), and O(reuse_values) left unset or V(false), for this option to take any effect.</div>
<div><code>helm install</code> does not accept <code>--reset-then-reuse-values</code>, so this option is ignored when O(replace) is set.</div>
<div>The module warns whenever one of those combinations makes this option a no-op.</div>
<div>This feature requires helm diff &gt;= 3.9.12.</div>
</td>
</tr>
@@ -498,6 +569,7 @@ Parameters
</td>
<td>
<div>When upgrading package, reset the values to the ones built into the chart.</div>
<div>Defaults to V(true), which makes helm ignore O(reuse_values) and O(reset_then_reuse_values). Set it to V(false) to use either of them.</div>
</td>
</tr>
<tr>
@@ -517,8 +589,33 @@ Parameters
</ul>
</td>
<td>
<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>If <em>reset_values</em> is set to <code>True</code>, this is ignored.</div>
<div>When upgrading package, specifies whether to reuse the last release&#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> is passed. Since O(reset_values) defaults to V(true), it has to be set to V(false) for this option to take any effect.</div>
<div><code>helm install</code> does not accept <code>--reuse-values</code>, so this option is ignored when O(replace) is set.</div>
<div>The module warns whenever one of those combinations makes this option a no-op.</div>
</td>
</tr>
<tr>
<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>
</tr>
<tr>
@@ -601,6 +698,48 @@ Parameters
<div>Skip custom resource definitions when installing or upgrading.</div>
</td>
</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>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -700,6 +839,28 @@ Parameters
<div>When <em>release_state</em> is set to <code>absent</code>, will wait until all the resources are deleted before returning. It will wait for as long as <em>wait_timeout</em>. This feature requires helm&gt;=3.7.0. Added in version 2.3.0.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>wait_for_jobs</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.6.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&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>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -810,6 +971,12 @@ Examples
chart_ref: "https://github.com/grafana/helm-charts/releases/download/grafana-5.6.0/grafana-5.6.0.tgz"
release_namespace: monitoring
- name: Deploy Bitnami's MongoDB latest chart from OCI registry
kubernetes.core.helm:
name: test
chart_ref: "oci://registry-1.docker.io/bitnamicharts/mongodb"
release_namespace: database
# Using complex Values
- name: Deploy new-relic client chart
kubernetes.core.helm:
@@ -818,6 +985,7 @@ Examples
release_namespace: default
force: True
wait: True
wait_for_jobs: True
replace: True
update_repo_cache: True
disable_hook: True
@@ -837,16 +1005,31 @@ Examples
enabled: True
# Deploy latest version
# 'reset_values' defaults to true and helm ignores '--reuse-values' when it is set,
# so it has to be turned off explicitly.
- name: Deploy latest version of Grafana chart using reuse_values
kubernetes.core.helm:
name: test
chart_ref: stable/grafana
release_namespace: monitoring
reuse_values: true
reset_values: false
values:
replicas: 2
version: 3e8ec0b2dffa40fb97d5342e4af887de95faa8c61a62480dd7f8aa03dffcf533
# Same for 'reset_then_reuse_values', which helm ignores when either
# '--reset-values' or '--reuse-values' is set.
- name: Deploy latest version of Grafana chart using reset_then_reuse_values
kubernetes.core.helm:
name: test
chart_ref: stable/grafana
release_namespace: monitoring
reset_then_reuse_values: true
reset_values: false
values:
replicas: 2
Return Values
@@ -25,7 +25,7 @@ Requirements
------------
The below requirements are needed on the host that executes this module.
- helm (https://github.com/helm/helm/releases)
- helm >= 3.0.0 (https://github.com/helm/helm/releases)
Parameters
+41 -1
View File
@@ -25,7 +25,7 @@ Requirements
------------
The below requirements are needed on the host that executes this module.
- helm (https://github.com/helm/helm/releases)
- helm >= 3.0.0 (https://github.com/helm/helm/releases)
Parameters
@@ -120,6 +120,24 @@ Parameters
<div>Provide a URL for accessing the API. Can also be specified via <code>K8S_AUTH_HOST</code> environment variable.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>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>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -231,6 +249,28 @@ Parameters
<div style="font-size: small; color: darkgreen"><br/>aliases: verify_ssl</div>
</td>
</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>
<br/>
+22 -1
View File
@@ -27,7 +27,7 @@ Requirements
------------
The below requirements are needed on the host that executes this module.
- helm >= 3.0, <4.0.0 (https://github.com/helm/helm/releases)
- helm >= 3.0.0 (https://github.com/helm/helm/releases)
Parameters
@@ -215,6 +215,27 @@ Parameters
<div>Pass credentials to all domains.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>plain_http</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.1.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&nbsp;&larr;</div></li>
<li>yes</li>
</ul>
</td>
<td>
<div>Use HTTP instead of HTTPS when working with OCI registries</div>
<div>Requires Helm &gt;= 3.13.0</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -25,7 +25,7 @@ Requirements
------------
The below requirements are needed on the host that executes this module.
- helm (https://github.com/helm/helm/releases) >= 3.8.0, <4.0.0
- helm (https://github.com/helm/helm/releases) >= 3.8.0
Parameters
@@ -151,6 +151,27 @@ Parameters
<div style="font-size: small; color: darkgreen"><br/>aliases: repo_password</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>plain_http</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.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>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -268,7 +289,9 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
</td>
<td>always</td>
<td>
<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>Full <code>helm</code> command stderr, in case you want to display it or examine the event log.</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/>
<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>
@@ -300,14 +323,17 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
</td>
<td>always</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/>
<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>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>stout_lines</b>
<b>stdout_lines</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
@@ -25,7 +25,7 @@ Requirements
------------
The below requirements are needed on the host that executes this module.
- helm (https://github.com/helm/helm/releases)
- helm >= 3.0.0 (https://github.com/helm/helm/releases)
- yaml (https://pypi.org/project/PyYAML/)
@@ -20,6 +20,13 @@ 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
----------
@@ -194,6 +201,27 @@ Parameters
<div>If the directory already exists, it will be overwritten.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>plain_http</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.1.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&nbsp;&larr;</div></li>
<li>yes</li>
</ul>
</td>
<td>
<div>Use HTTP instead of HTTPS when working with OCI registries</div>
<div>Requires Helm &gt;= 3.13.0</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
+20
View File
@@ -152,6 +152,25 @@ Parameters
<div>The name of a context found in the config file. Can also be specified via K8S_AUTH_CONTEXT environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>copy_timeout</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">integer</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.6.0</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">300</div>
</td>
<td>
<div>Maximum time in seconds to spend streaming the archive to the pod and waiting for the remote <code>tar</code> process to finish extracting it.</div>
<div>Raise this when copying large files over a slow connection.</div>
<div>This option is ignored when <em>state</em> is set to <code>from_pod</code>.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -512,6 +531,7 @@ Notes
.. note::
- the tar binary is required on the container when copying from local filesystem to pod.
- a POSIX shell at ``/bin/sh`` and ``head`` are also used, when present, to bound the archive sent to the container so that the module can confirm the copy finished. Without them the copy still runs but completion cannot be verified, and a warning is emitted.
- the (init) container has to be started before you copy files or directories to it.
- To avoid SSL certificate validation errors when ``validate_certs`` is *True*, the full certificate chain for the API server must be provided via ``ca_cert`` or in the kubeconfig file.
+29
View File
@@ -280,6 +280,29 @@ Parameters
<div>List of label selectors to use to filter results</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>metadata_only</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.6.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&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>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -716,6 +739,12 @@ Examples
retries: 60
delay: 15
- name: Get a list of all pods metadata only
kubernetes.core.k8s_info:
kind: Pod
metadata_only: true
register: pod_metadata_list
Return Values
-372
View File
@@ -1,372 +0,0 @@
.. _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.
@@ -140,6 +140,25 @@ Parameters
<div>The name of a context found in the config file. Can also be specified via K8S_AUTH_CONTEXT environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>hidden_fields</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
/ <span style="color: purple">elements=string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.1.0</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">[]</div>
</td>
<td>
<div>List of fields to hide from the diff output.</div>
<div>This is useful for fields that are not relevant to the patch operation, such as `metadata.managedFields`.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
+863
View File
@@ -0,0 +1,863 @@
.. _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)
+28
View File
@@ -95,6 +95,26 @@ Parameters
<div>Enable the helm chart inflation generator</div>
</td>
</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>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -145,6 +165,14 @@ Examples
kubernetes.core.k8s:
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
+1 -1
View File
@@ -25,7 +25,7 @@ tags:
- openshift
- okd
- cluster
version: 5.5.0
version: 6.6.0
build_ignore:
- .DS_Store
- "*.tar.gz"
+10 -3
View File
@@ -1,10 +1,17 @@
---
requires_ansible: '>=2.16.0'
# Only modules that accept the shared authentication options belong in these
# groups: HELM_AUTH_ARG_SPEC for helm, AUTH_ARG_SPEC for k8s. Adding a module
# that does not accept them makes module_defaults fail for every user of the
# group. This excludes helm_pull, helm_registry_auth, helm_template and
# kubeconfig, which only take a subset (or none) of those options.
action_groups:
helm:
- helm
- helm_info
- helm_plugin
- helm_plugin_info
- helm_repository
k8s:
- k8s
@@ -18,17 +25,17 @@ action_groups:
- k8s_rollback
- k8s_scale
- k8s_service
- k8s_taint
plugin_routing:
inventory:
openshift:
redirect: community.okd.openshift
k8s:
deprecation:
tombstone:
removal_version: 6.0.0
warning_text: >-
The k8s inventory plugin has been deprecated and
will be removed in release 6.0.0.
The k8s inventory plugin was slated for deprecation in 3.3.0 and has been removed in release 6.0.0. Use kubernetes.core.k8s_info and ansible.builtin.add_host instead.
modules:
k8s_auth:
redirect: community.okd.k8s_auth
+1 -1
View File
@@ -20,7 +20,7 @@ from ansible.errors import (
AnsibleError,
AnsibleFileNotFound,
)
from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
from ansible.module_utils.parsing.convert_bool import boolean
from ansible.plugins.action import ActionBase
+1 -1
View File
@@ -268,7 +268,7 @@ import tempfile
from shlex import quote as shlex_quote
from ansible.errors import AnsibleError, AnsibleFileNotFound
from ansible.module_utils._text import to_bytes
from ansible.module_utils.common.text.converters import to_bytes
from ansible.module_utils.parsing.convert_bool import boolean
from ansible.parsing.yaml.loader import AnsibleLoader
from ansible.plugins.connection import BUFSIZE, ConnectionBase
-476
View File
@@ -1,476 +0,0 @@
# 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 -1
View File
@@ -209,10 +209,10 @@ RETURN = """
"""
import os
from collections.abc import KeysView
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.utils.display import Display
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
+36 -3
View File
@@ -34,6 +34,13 @@ DOCUMENTATION = """
description:
- Enable the helm chart inflation generator
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:
- "python >= 3.6"
@@ -55,6 +62,14 @@ EXAMPLES = """
- name: Create kubernetes resources for lookup output with `--enable-helm` set
kubernetes.core.k8s:
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 = """
@@ -72,6 +87,7 @@ RETURN = """
key1: val1
"""
import os
import subprocess
from ansible.errors import AnsibleLookupError
@@ -92,8 +108,10 @@ def get_binary_from_path(name, opt_dirs=None):
return None
def run_command(command):
cmd = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
def run_command(command, environ=None):
cmd = subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environ
)
stdout, stderr = cmd.communicate()
return cmd.returncode, stdout, stderr
@@ -107,6 +125,7 @@ class LookupModule(LookupBase):
binary_path=None,
opt_dirs=None,
enable_helm=False,
environment=None,
**kwargs
):
executable_path = binary_path
@@ -141,7 +160,21 @@ class LookupModule(LookupBase):
if enable_helm:
command += ["--enable-helm"]
(ret, out, err) = run_command(command)
environ = None
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 err:
raise AnsibleLookupError(
+15
View File
@@ -144,3 +144,18 @@ DELETE_OPTS_ARG_SPEC = {
"options": {"resourceVersion": {"type": "str"}, "uid": {"type": "str"}},
},
}
METADATA_ONLY_HEADERS_SPEC = {
"accept": {"type": "str"},
}
METADATA_ONLY_HEADER_VALUES = {
"partial_object": (
"application/json;as=PartialObjectMetadata;g=meta.k8s.io;v=v1,"
"application/json;q=0.9"
),
"partial_object_list": (
"application/json;as=PartialObjectMetadataList;g=meta.k8s.io;v=v1,"
"application/json;q=0.9"
),
}
+1 -1
View File
@@ -23,7 +23,7 @@ import base64
import os
from tempfile import NamedTemporaryFile
from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
from ansible.module_utils.urls import Request
try:
+179 -54
View File
@@ -18,12 +18,14 @@ from __future__ import absolute_import, division, print_function
__metaclass__ = type
import os
import shlex
import tarfile
import time
from abc import ABCMeta, abstractmethod
from select import select
from tempfile import NamedTemporaryFile, TemporaryFile
from ansible.module_utils._text import to_native
from ansible.module_utils.common.text.converters import to_native
# from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import AnsibleModule
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import (
@@ -296,14 +298,156 @@ class K8SCopyToPod(K8SCopy):
Copy files/directory from local filesystem into remote Pod
"""
# Size of the chunks the tar archive is written to stdin with.
CHUNK_SIZE = 1024 * 1024
SHELL = "/bin/sh"
def __init__(self, module, client):
super(K8SCopyToPod, self).__init__(module, client)
self.files_to_copy = list()
self.named_temp_file = None
self.copy_timeout = module.params.get("copy_timeout")
def close_temp_file(self):
if self.named_temp_file:
self.named_temp_file.close()
def _fail(self, response, msg, stderr=(), **kwargs):
"""Fail, keeping whatever the remote already wrote to stderr.
An early close or a stall is usually the symptom, not the cause: tar
has typically said why on stderr first.
"""
if stderr:
msg = "{0}: {1}".format(msg, "".join(stderr))
response.close()
self.close_temp_file()
self.module.fail_json(
msg="Failed to copy local file/directory into Pod: {0}".format(msg),
**kwargs,
)
def tar_command(self, dest_file):
if self.no_preserve:
command = [
"tar",
"--no-same-permissions",
"--no-same-owner",
"-xmf",
"-",
]
else:
command = ["tar", "-xmf", "-"]
if dest_file.startswith("/"):
command.extend(["-C", "/"])
return command
def can_bound_stream(self):
"""Whether the container can run ``sh -c 'head -c ...'``."""
error, _out, _err = self._run_from_pod(
cmd=[self.SHELL, "-c", "command -v head"]
)
return (error or {}).get("status") == "Success"
def remote_command(self, dest_file, archive_size):
"""Build the command that extracts the archive inside the container.
The websocket exec protocol the kubernetes client speaks (v4) cannot
half-close stdin, so the only EOF the remote process can get is the
connection going away. Relying on that races with tar finishing and
truncates the file (issue #776), and tar cannot be relied on to stop at
the end-of-archive marker either -- busybox tar blocks for EOF.
Piping through ``head -c`` bounds the stream at the exact archive size,
so tar sees a clean EOF, exits on its own, and the API server reports
its exit status on the error channel. Only where the container has no
shell do we fall back to feeding tar directly, which cannot confirm
that the copy completed.
"""
command = self.tar_command(dest_file)
if not self.can_bound_stream():
self.module.warn(
"Container has no '{0}' with 'head', falling back to writing the"
" archive straight to tar. The module cannot confirm the copy"
" completed; verify the file after copying.".format(self.SHELL)
)
return command, False
return [
self.SHELL,
"-c",
"head -c {0} | {1}".format(
archive_size, " ".join(shlex.quote(arg) for arg in command)
),
], True
def _stream_tar_to_pod(self, response, tar_buffer, wait_for_exit):
"""Feed the archive to the remote extractor and wait for it to finish.
Writing the last chunk only hands the bytes to the local socket; they
still have to cross the API server and reach the container. Closing the
connection at that point kills the extractor mid-write and silently
truncates the file, which is what issue #776 reports.
"""
stdout, stderr = [], []
def drain(timeout):
response.update(timeout=timeout)
if response.peek_stdout():
stdout.append(response.read_stdout().rstrip("\n"))
if response.peek_stderr():
stderr.append(response.read_stderr().rstrip("\n"))
deadline = time.monotonic() + self.copy_timeout
chunk = tar_buffer.read(self.CHUNK_SIZE)
while chunk:
if not response.is_open():
self._fail(
response,
"connection to Pod {0}/{1} closed before the whole archive was"
" sent, the remote file is incomplete".format(
self.namespace, self.name
),
stderr,
)
if time.monotonic() > deadline:
self._fail(
response,
"timed out after {0}s sending the archive to Pod {1}/{2}".format(
self.copy_timeout, self.namespace, self.name
),
stderr,
)
# Non-blocking, keeps the receive buffer clear while we write.
drain(0)
response.write_stdin(chunk)
chunk = tar_buffer.read(self.CHUNK_SIZE)
if not wait_for_exit:
# No way to make the extractor exit, so no status to collect: read
# whatever it has already said and close, as the module always did.
drain(0)
response.close()
return None, stdout, stderr
# The archive is on the wire; wait for the extractor to consume it,
# exit, and have its status reported on the error channel.
while response.is_open():
if time.monotonic() > deadline:
self._fail(
response,
"timed out after {0}s waiting for tar to finish extracting on Pod"
" {1}/{2}".format(self.copy_timeout, self.namespace, self.name),
stderr,
)
drain(1)
error = yaml.safe_load(response.read_channel(ERROR_CHANNEL)) or {}
response.close()
return error, stdout, stderr
def run(self):
# remove trailing slash from destination path
dest_file = self.remote_path.rstrip("/")
@@ -336,65 +480,46 @@ class K8SCopyToPod(K8SCopy):
dest_file = os.path.join(dest_file, os.path.basename(src_file))
if not self.check_mode:
if self.no_preserve:
tar_command = [
"tar",
"--no-same-permissions",
"--no-same-owner",
"-xmf",
"-",
]
else:
tar_command = ["tar", "-xmf", "-"]
if dest_file.startswith("/"):
tar_command.extend(["-C", "/"])
response = stream(
self.api_instance.connect_get_namespaced_pod_exec,
self.name,
self.namespace,
command=tar_command,
stderr=True,
stdin=True,
stdout=True,
tty=False,
_preload_content=False,
**self.container_arg,
)
with TemporaryFile() as tar_buffer:
# Build the archive first: bounding the remote read needs its
# exact size.
with tarfile.open(fileobj=tar_buffer, mode="w") as tar:
tar.add(src_file, dest_file)
archive_size = tar_buffer.tell()
tar_buffer.seek(0)
commands = []
# push command in chunk mode
size = 1024 * 1024
while True:
data = tar_buffer.read(size)
if not data:
break
commands.append(data)
stderr, stdout = [], []
while response.is_open():
if response.peek_stdout():
stdout.append(response.read_stdout().rstrip("\n"))
if response.peek_stderr():
stderr.append(response.read_stderr().rstrip("\n"))
if commands:
cmd = commands.pop(0)
response.write_stdin(cmd)
else:
break
response.close()
if stderr:
self.close_temp_file()
self.module.fail_json(
command=tar_command,
msg="Failed to copy local file/directory into Pod due to: {0}".format(
"".join(stderr)
),
command, wait_for_exit = self.remote_command(dest_file, archive_size)
response = stream(
self.api_instance.connect_get_namespaced_pod_exec,
self.name,
self.namespace,
command=command,
stderr=True,
stdin=True,
stdout=True,
tty=False,
_preload_content=False,
**self.container_arg,
)
error, stdout, stderr = self._stream_tar_to_pod(
response, tar_buffer, wait_for_exit
)
if error is not None and error.get("status") != "Success":
self._fail(
response,
"".join(stderr) or error.get("message", "unknown error"),
command=command,
)
if error is None and stderr:
# Legacy path: no exit status to go on, so any output is fatal.
self._fail(response, "".join(stderr), command=command)
if stderr:
self.module.warn(
"tar wrote to stderr while extracting into Pod {0}/{1}: {2}".format(
self.namespace, self.name, "".join(stderr)
)
)
self.close_temp_file()
if self.content:
self.module.exit_json(
+79 -14
View File
@@ -32,6 +32,53 @@ except ImportError:
HAS_YAML = False
# Helm's registry client writes these progress messages to stdout as of helm 4.2.1
# (helm/helm#32056); earlier versions sent them to stderr. Anything that parses the
# stdout of a helm command which may pull from an OCI registry has to skip them.
# Kept verbatim from helm's pkg/registry/client.go so that a reworded message fails
# to match, and therefore fails loudly, rather than silently eating real output.
REGISTRY_PROGRESS_RE = re.compile(r"^(?:Pulled|Pushed|Digest): \S")
REGISTRY_UNDERSCORE_SUFFIX = " contains an underscore.\n"
REGISTRY_UNDERSCORE_MESSAGE = """
OCI artifact references (e.g. tags) do not support the plus sign (+). To support
storing semantic versions, Helm adopts the convention of changing plus (+) to
an underscore (_) in chart version tags when pushing to a registry and back to
a plus (+) when pulling from a registry.
"""
REGISTRY_UNDERSCORE_MESSAGE_LINES = len(REGISTRY_UNDERSCORE_MESSAGE.splitlines())
def strip_registry_progress(out):
"""
Drop OCI registry progress messages from the front of a helm command's stdout.
Helm emits 'Pulled:'/'Pushed:' and 'Digest:' lines, followed - when the
reference contains an underscore - by a free-text explanation that is not
valid YAML. Since helm 4.2.1 these land on stdout ahead of the real output,
so 'helm show chart' can no longer be parsed and 'helm template' no longer
returns only rendered manifests.
"""
lines = out.splitlines(keepends=True)
index = 0
while index < len(lines):
if REGISTRY_PROGRESS_RE.match(lines[index]):
index += 1
elif lines[index].endswith(REGISTRY_UNDERSCORE_SUFFIX):
# helm prints its registryUnderscoreMessage right after this line, led
# by a blank line. Anything else is not a message we know about.
start = index + 1
end = start + REGISTRY_UNDERSCORE_MESSAGE_LINES
if "".join(lines[start:end]) != REGISTRY_UNDERSCORE_MESSAGE:
break
index = end
else:
break
return "".join(lines[index:])
def parse_helm_plugin_list(output=None):
"""
Parse `helm plugin list`, return list of plugins
@@ -40,16 +87,20 @@ def parse_helm_plugin_list(output=None):
if not output:
return ret
parsing_grammar = None
for line in output:
if line.startswith("NAME"):
parsing_grammar = [s.strip().lower() for s in line.split("\t")]
continue
name, version, description = line.split("\t", 3)
name = name.strip()
version = version.strip()
description = description.strip()
if name == "":
if parsing_grammar is None:
continue
ret.append((name, version, description))
plugin = {
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
@@ -202,21 +253,35 @@ class AnsibleHelmModule(object):
return m.group(1)
return None
def validate_helm_version(self):
def is_helm_v4(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):
"""
Validate that Helm version is >=3.0.0 and <4.0.0.
Helm 4 is not yet supported.
Return true if the helm version is compatible with the helm diff version
Helm v4 requires helm diff v3.14.0
"""
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()
if helm_version is None:
self.fail_json(msg="Unable to determine Helm version")
if (LooseVersion(helm_version) < LooseVersion("3.0.0")) or (
LooseVersion(helm_version) >= LooseVersion("4.0.0")
):
if LooseVersion(helm_version) < LooseVersion(version):
self.fail_json(
msg="Helm version must be >=3.0.0,<4.0.0, current version is {0}".format(
helm_version
msg="Helm version must be >= {0}, current version is {1}".format(
version, helm_version
)
)
+1
View File
@@ -181,6 +181,7 @@ def _create_headers(module=None, **kwargs):
header_map = {
"impersonate_user": "Impersonate-User",
"impersonate_groups": "Impersonate-Group",
"accept": "Accept",
}
headers = {}
+1 -1
View File
@@ -3,7 +3,7 @@
from typing import Dict
from ansible.module_utils._text import to_native
from ansible.module_utils.common.text.converters import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
get_api_client,
)
+19 -6
View File
@@ -47,6 +47,18 @@ def pod_ready(pod: ResourceInstance) -> bool:
)
def job_complete(job: ResourceInstance) -> bool:
return bool(
job.status
and job.status.conditions
and any(
condition["type"] in ("Complete", "Failed")
and boolean(condition["status"], strict=False)
for condition in job.status.conditions
)
)
def daemonset_ready(daemonset: ResourceInstance) -> bool:
return bool(
daemonset.status
@@ -89,18 +101,18 @@ def custom_condition(condition: Dict, resource: ResourceInstance) -> bool:
if not matches:
return False
# There should never be more than one condition of a specific type
match: ResourceField = matches[0]
if match.status == "Unknown":
if match.status == condition["status"]:
match_condition: ResourceField = matches[0]
if match_condition.status == "Unknown":
if match_condition.status == condition["status"]:
if "reason" not in condition:
return True
if condition["reason"]:
return match.reason == condition["reason"]
return match_condition.reason == condition["reason"]
return False
status = True if match.status == "True" else False
status = True if match_condition.status == "True" else False
if status == boolean(condition["status"], strict=False):
if condition.get("reason"):
return match.reason == condition["reason"]
return match_condition.reason == condition["reason"]
return True
return False
@@ -143,6 +155,7 @@ RESOURCE_PREDICATES = {
"DaemonSet": daemonset_ready,
"Deployment": deployment_ready,
"Pod": pod_ready,
"Job": job_complete,
"StatefulSet": statefulset_ready,
"ClusterOperator": cluster_operator_ready,
}
+95
View File
@@ -0,0 +1,95 @@
# 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
+435 -73
View File
@@ -21,7 +21,7 @@ author:
- Matthieu Diehr (@d-matt)
requirements:
- "helm (https://github.com/helm/helm/releases)"
- "helm >= 3.0.0 (https://github.com/helm/helm/releases)"
- "yaml (https://pypi.org/project/PyYAML/)"
description:
@@ -132,15 +132,19 @@ options:
version_added: 2.4.0
reuse_values:
description:
- When upgrading package, specifies wether to reuse the last release's values and merge in any overrides from parameters I(release_values),
I(values_files) or I(set_values).
- If I(reset_values) is set to C(True), this is ignored.
- When upgrading package, specifies whether to reuse the last release's values and merge in any overrides from parameters O(release_values),
O(values_files) or O(set_values).
- Helm ignores this when C(--reset-values) is passed. Since O(reset_values) defaults to V(true), it has to be set to V(false)
for this option to take any effect.
- C(helm install) does not accept C(--reuse-values), so this option is ignored when O(replace) is set.
- The module warns whenever one of those combinations makes this option a no-op.
type: bool
required: false
version_added: 3.0.0
reset_values:
description:
- When upgrading package, reset the values to the ones built into the chart.
- Defaults to V(true), which makes helm ignore O(reuse_values) and O(reset_then_reuse_values). Set it to V(false) to use either of them.
type: bool
required: false
default: True
@@ -149,7 +153,10 @@ options:
description:
- When upgrading package, reset the values to the ones built into the chart, apply the last release's values and merge in any overrides from
parameters O(release_values), O(values_files) or O(set_values).
- If O(reset_values) or O(reuse_values) is set to V(True), this is ignored.
- Helm ignores this when C(--reset-values) or C(--reuse-values) is passed. Since O(reset_values) defaults to V(true), it has to be
set to V(false), and O(reuse_values) left unset or V(false), for this option to take any effect.
- C(helm install) does not accept C(--reset-then-reuse-values), so this option is ignored when O(replace) is set.
- The module warns whenever one of those combinations makes this option a no-op.
- This feature requires helm diff >= 3.9.12.
type: bool
required: false
@@ -165,6 +172,13 @@ options:
force:
description:
- 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
type: bool
purge:
@@ -180,6 +194,15 @@ options:
It will wait for as long as I(wait_timeout). This feature requires helm>=3.7.0. Added in version 2.3.0.
default: False
type: bool
wait_for_jobs:
description:
- When I(release_state) is set to C(present), and I(wait) is set to C(True), wait until all jobs are in a
completed state before marking the release as successful.
- Ignored when used without O(wait).
- Requires Helm >= 3.5.0
version_added: 6.6.0
default: False
type: bool
wait_timeout:
description:
- Timeout when wait option is enabled (helm2 is a number of seconds, helm3 is a duration).
@@ -195,8 +218,44 @@ options:
atomic:
description:
- 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
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:
description:
- Create the release namespace if not present.
@@ -237,6 +296,27 @@ options:
default: False
aliases: [ skip_tls_certs_check ]
version_added: 5.3.0
plain_http:
description:
- Use HTTP instead of HTTPS when working with OCI registries
- Requires Helm >= 3.13.0
type: bool
default: False
version_added: 6.1.0
take_ownership:
description:
- 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:
- kubernetes.core.helm_common_options
"""
@@ -319,6 +399,12 @@ EXAMPLES = r"""
chart_ref: "https://github.com/grafana/helm-charts/releases/download/grafana-5.6.0/grafana-5.6.0.tgz"
release_namespace: monitoring
- name: Deploy Bitnami's MongoDB latest chart from OCI registry
kubernetes.core.helm:
name: test
chart_ref: "oci://registry-1.docker.io/bitnamicharts/mongodb"
release_namespace: database
# Using complex Values
- name: Deploy new-relic client chart
kubernetes.core.helm:
@@ -327,6 +413,7 @@ EXAMPLES = r"""
release_namespace: default
force: True
wait: True
wait_for_jobs: True
replace: True
update_repo_cache: True
disable_hook: True
@@ -346,15 +433,30 @@ EXAMPLES = r"""
enabled: True
# Deploy latest version
# 'reset_values' defaults to true and helm ignores '--reuse-values' when it is set,
# so it has to be turned off explicitly.
- name: Deploy latest version of Grafana chart using reuse_values
kubernetes.core.helm:
name: test
chart_ref: stable/grafana
release_namespace: monitoring
reuse_values: true
reset_values: false
values:
replicas: 2
version: 3e8ec0b2dffa40fb97d5342e4af887de95faa8c61a62480dd7f8aa03dffcf533
# Same for 'reset_then_reuse_values', which helm ignores when either
# '--reset-values' or '--reuse-values' is set.
- name: Deploy latest version of Grafana chart using reset_then_reuse_values
kubernetes.core.helm:
name: test
chart_ref: stable/grafana
release_namespace: monitoring
reset_then_reuse_values: true
reset_values: false
values:
replicas: 2
"""
RETURN = r"""
@@ -443,6 +545,7 @@ from ansible.module_utils.basic import missing_required_lib
from ansible_collections.kubernetes.core.plugins.module_utils.helm import (
AnsibleHelmModule,
parse_helm_plugin_list,
strip_registry_progress,
)
from ansible_collections.kubernetes.core.plugins.module_utils.helm_args_common import (
HELM_AUTH_ARG_SPEC,
@@ -473,9 +576,13 @@ def get_release_status(module, release_name, all_status=False):
"--filter",
release_name,
]
if all_status:
if all_status and not module.is_helm_v4():
# --all has been removed from `helm list` command on helm v4
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)
release = get_release(yaml.safe_load(out), release_name)
@@ -512,7 +619,9 @@ def run_dep_update(module, chart_ref):
rc, out, err = module.run_helm_command(dep_update)
def fetch_chart_info(module, command, chart_ref, insecure_skip_tls_verify=False):
def fetch_chart_info(
module, command, chart_ref, insecure_skip_tls_verify=False, plain_http=False
):
"""
Get chart info
"""
@@ -521,9 +630,65 @@ def fetch_chart_info(module, command, chart_ref, insecure_skip_tls_verify=False)
if insecure_skip_tls_verify:
inspect_command += " --insecure-skip-tls-verify"
if plain_http:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.13.0"):
module.fail_json(
msg="plain_http requires helm >= 3.13.0, current version is {0}".format(
helm_version
)
)
else:
inspect_command += " --plain-http"
rc, out, err = module.run_helm_command(inspect_command)
return yaml.safe_load(out)
return yaml.safe_load(strip_registry_progress(out))
def validate_value_options(
module, replace, reuse_values, reset_values, reset_then_reuse_values
):
"""
Check the value-reuse options against each other and against 'replace'.
'helm install' accepts none of these flags, so 'replace' drops all three. The rest
are precedence rules helm applies silently: '--reset-values' wins over
'--reuse-values', and both win over '--reset-then-reuse-values'. Since 'reset_values'
defaults to true, requesting either of the other two on its own is a no-op.
Warn rather than fail throughout. Every one of these combinations is accepted by
playbooks today: 'reuse_values' has existed since 3.0.0, and a release that is
already converged never reaches deploy(), so the invalid command was never built.
Failing here would turn tasks that pass today into tasks that fail.
"""
if replace:
for name, requested in (
("reuse_values", reuse_values is not None),
("reset_then_reuse_values", reset_then_reuse_values),
):
if requested:
module.warn(
"{0} is ignored because replace=true deploys through 'helm install',"
" which does not accept the flag.".format(name)
)
return
if reset_values:
for name, requested in (
("reuse_values", reuse_values),
("reset_then_reuse_values", reset_then_reuse_values),
):
if requested:
module.warn(
"{0} is ignored because reset_values is true. "
"Set reset_values=false to make it take effect.".format(name)
)
elif reuse_values and reset_then_reuse_values:
module.warn(
"reset_then_reuse_values is ignored because reuse_values is true. "
"Set reuse_values=false to make it take effect."
)
def deploy(
@@ -533,12 +698,14 @@ def deploy(
release_values,
chart_name,
wait,
wait_for_jobs,
wait_timeout,
disable_hook,
force,
values_files,
history_max,
atomic=False,
cleanup_on_fail=False,
create_namespace=False,
replace=False,
post_renderer=None,
@@ -550,6 +717,11 @@ def deploy(
reset_values=True,
reset_then_reuse_values=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
@@ -561,36 +733,99 @@ def deploy(
deploy_command += " --dependency-update"
else:
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:
deploy_command += " --reset-values"
if reuse_values is not None:
deploy_command += " --reuse-values=" + str(reuse_values)
if reuse_values is not None:
deploy_command += " --reuse-values=" + str(reuse_values)
if reset_then_reuse_values:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.14.0"):
module.fail_json(
msg="reset_then_reuse_values requires helm >= 3.14.0, current version is {0}".format(
helm_version
if reset_then_reuse_values:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.14.0"):
module.fail_json(
msg="reset_then_reuse_values requires helm >= 3.14.0, current version is {0}".format(
helm_version
)
)
)
else:
deploy_command += " --reset-then-reuse-values"
else:
deploy_command += " --reset-then-reuse-values"
if wait:
deploy_command += " --wait"
if wait_for_jobs:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.5.0"):
module.fail_json(
msg="wait_for_jobs requires helm >= 3.5.0, current version is {0}".format(
helm_version
)
)
else:
deploy_command += " --wait-for-jobs"
if wait_timeout is not None:
deploy_command += " --timeout " + wait_timeout
if atomic:
deploy_command += " --atomic"
# Helm v4 renamed '--atomic' to '--rollback-on-failure'. The old flag is
# 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:
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:
deploy_command += " --force"
# Helm v4 deprecated '--force' (split into '--force-replace' and
# '--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:
deploy_command += " --replace"
@@ -612,6 +847,9 @@ def deploy(
else:
deploy_command += " --insecure-skip-tls-verify"
if plain_http:
deploy_command += " --plain-http"
if values_files:
for value_file in values_files:
deploy_command += " --values=" + value_file
@@ -635,6 +873,17 @@ def deploy(
if 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}'"
return deploy_command
@@ -687,8 +936,8 @@ def get_plugin_version(plugin):
return None
for line in out:
if line[0] == plugin:
return line[1]
if line["name"] == plugin:
return line["version"]
return None
@@ -707,6 +956,8 @@ def helmdiff_check(
reset_values=True,
reset_then_reuse_values=False,
insecure_skip_tls_verify=False,
plain_http=False,
skip_schema_validation=False,
):
"""
Use helm diff to determine if a release would change by upgrading a chart.
@@ -738,10 +989,10 @@ def helmdiff_check(
if set_value_args:
cmd += " " + set_value_args
if reuse_values:
if not replace and reuse_values:
cmd += " --reuse-values"
if reset_then_reuse_values:
if not replace and reset_then_reuse_values:
helm_diff_version = get_plugin_version("diff")
helm_version = module.get_helm_version()
fail_msg = ""
@@ -762,6 +1013,28 @@ def helmdiff_check(
if 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"
if plain_http:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.13.0"):
module.fail_json(
msg="plain_http requires helm >= 3.13.0, current version is {0}".format(
helm_version
)
)
else:
cmd += " --plain-http"
rc, out, err = module.run_helm_command(cmd)
return (len(out.strip()) > 0, out.strip())
@@ -793,39 +1066,58 @@ def default_check(release_status, chart_info, values=None, values_files=None):
def argument_spec():
arg_spec = copy.deepcopy(HELM_AUTH_ARG_SPEC)
arg_spec.update(
dict(
chart_ref=dict(type="path"),
chart_repo_url=dict(type="str"),
chart_version=dict(type="str"),
dependency_update=dict(type="bool", default=False, aliases=["dep_up"]),
release_name=dict(type="str", required=True, aliases=["name"]),
release_namespace=dict(type="str", required=True, aliases=["namespace"]),
release_state=dict(
default="present", choices=["present", "absent"], aliases=["state"]
),
release_values=dict(type="dict", default={}, aliases=["values"]),
values_files=dict(type="list", default=[], elements="str"),
update_repo_cache=dict(type="bool", default=False),
disable_hook=dict(type="bool", default=False),
force=dict(type="bool", default=False),
purge=dict(type="bool", default=True),
wait=dict(type="bool", default=False),
wait_timeout=dict(type="str"),
timeout=dict(type="str"),
atomic=dict(type="bool", default=False),
create_namespace=dict(type="bool", default=False),
post_renderer=dict(type="str"),
replace=dict(type="bool", default=False),
skip_crds=dict(type="bool", default=False),
history_max=dict(type="int"),
set_values=dict(type="list", elements="dict"),
reuse_values=dict(type="bool"),
reset_values=dict(type="bool", default=True),
reset_then_reuse_values=dict(type="bool", default=False),
insecure_skip_tls_verify=dict(
type="bool", default=False, aliases=["skip_tls_certs_check"]
),
)
{
"chart_ref": {"type": "path"},
"chart_repo_url": {"type": "str"},
"chart_version": {"type": "str"},
"dependency_update": {
"type": "bool",
"default": False,
"aliases": ["dep_up"],
},
"release_name": {"type": "str", "required": True, "aliases": ["name"]},
"release_namespace": {
"type": "str",
"required": True,
"aliases": ["namespace"],
},
"release_state": {
"default": "present",
"choices": ["present", "absent"],
"aliases": ["state"],
},
"release_values": {"type": "dict", "default": {}, "aliases": ["values"]},
"values_files": {"type": "list", "default": [], "elements": "str"},
"update_repo_cache": {"type": "bool", "default": False},
"disable_hook": {"type": "bool", "default": False},
"force": {"type": "bool", "default": False},
"purge": {"type": "bool", "default": True},
"wait": {"type": "bool", "default": False},
"wait_for_jobs": {"type": "bool", "default": False},
"wait_timeout": {"type": "str"},
"timeout": {"type": "str"},
"atomic": {"type": "bool", "default": False},
"server_side": {"type": "str", "choices": ["auto", "true", "false"]},
"force_conflicts": {"type": "bool", "default": False},
"create_namespace": {"type": "bool", "default": False},
"post_renderer": {"type": "str"},
"replace": {"type": "bool", "default": False},
"skip_crds": {"type": "bool", "default": False},
"history_max": {"type": "int"},
"set_values": {"type": "list", "elements": "dict"},
"reuse_values": {"type": "bool"},
"reset_values": {"type": "bool", "default": True},
"reset_then_reuse_values": {"type": "bool", "default": False},
"insecure_skip_tls_verify": {
"type": "bool",
"default": False,
"aliases": ["skip_tls_certs_check"],
},
"plain_http": {"type": "bool", "default": False},
"take_ownership": {"type": "bool", "default": False},
"skip_schema_validation": {"type": "bool", "default": False},
"cleanup_on_fail": {"type": "bool", "default": False},
}
)
return arg_spec
@@ -842,6 +1134,8 @@ def main():
("context", "ca_cert"),
("replace", "history_max"),
("wait_timeout", "timeout"),
("force", "server_side"),
("force", "force_conflicts"),
],
supports_check_mode=True,
)
@@ -857,7 +1151,7 @@ def main():
if not IMP_YAML:
module.fail_json(msg=missing_required_lib("yaml"), exception=IMP_YAML_ERR)
# Validate Helm version >=3.0.0,<4.0.0
# Validate Helm version >=3.0.0
module.validate_helm_version()
changed = False
@@ -877,8 +1171,12 @@ def main():
force = module.params.get("force")
purge = module.params.get("purge")
wait = module.params.get("wait")
wait_for_jobs = module.params.get("wait_for_jobs")
wait_timeout = module.params.get("wait_timeout")
atomic = module.params.get("atomic")
cleanup_on_fail = module.params.get("cleanup_on_fail")
server_side = module.params.get("server_side")
force_conflicts = module.params.get("force_conflicts")
create_namespace = module.params.get("create_namespace")
post_renderer = module.params.get("post_renderer")
replace = module.params.get("replace")
@@ -890,6 +1188,9 @@ def main():
reset_values = module.params.get("reset_values")
reset_then_reuse_values = module.params.get("reset_then_reuse_values")
insecure_skip_tls_verify = module.params.get("insecure_skip_tls_verify")
plain_http = module.params.get("plain_http")
take_ownership = module.params.get("take_ownership")
skip_schema_validation = module.params.get("skip_schema_validation")
if update_repo_cache:
run_repo_update(module)
@@ -899,6 +1200,33 @@ def main():
release_status = get_release_status(module, release_name, all_status=all_status)
helm_cmd = module.get_helm_binary()
if plain_http:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.13.0"):
module.fail_json(
msg="plain_http requires helm >= 3.13.0, current version is {0}".format(
helm_version
)
)
if take_ownership:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.17.0"):
module.fail_json(
msg="take_ownership requires helm >= 3.17.0, current version is {0}".format(
helm_version
)
)
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 = {}
if release_state == "absent" and release_status is not None:
# skip release statuses 'uninstalled' and 'uninstalling'
@@ -909,8 +1237,7 @@ def main():
if wait:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.7.0"):
opt_result["warnings"] = []
opt_result["warnings"].append(
module.warn(
"helm uninstall support option --wait for helm release >= 3.7.0"
)
wait = False
@@ -920,6 +1247,10 @@ def main():
)
changed = True
elif release_state == "present":
validate_value_options(
module, replace, reuse_values, reset_values, reset_then_reuse_values
)
if chart_version is not None:
helm_cmd += " --version=" + chart_version
@@ -928,7 +1259,7 @@ def main():
# Fetch chart info to have real version and real name for chart_ref from archive, folder or url
chart_info = fetch_chart_info(
module, helm_cmd, chart_ref, insecure_skip_tls_verify
module, helm_cmd, chart_ref, insecure_skip_tls_verify, plain_http
)
if dependency_update:
@@ -973,11 +1304,15 @@ def main():
release_values,
chart_ref,
wait,
wait_for_jobs,
wait_timeout,
disable_hook,
False,
values_files=values_files,
atomic=atomic,
cleanup_on_fail=cleanup_on_fail,
server_side=server_side,
force_conflicts=force_conflicts,
create_namespace=create_namespace,
post_renderer=post_renderer,
replace=replace,
@@ -990,19 +1325,29 @@ def main():
reset_values=reset_values,
reset_then_reuse_values=reset_then_reuse_values,
insecure_skip_tls_verify=insecure_skip_tls_verify,
plain_http=plain_http,
take_ownership=take_ownership,
skip_schema_validation=skip_schema_validation,
)
changed = True
else:
helm_diff_version = get_plugin_version("diff")
if helm_diff_version and (
not chart_repo_url
or (
chart_repo_url
and LooseVersion(helm_diff_version) >= LooseVersion("3.4.1")
helm_version_compatible = module.is_helm_version_compatible_with_helm_diff(
helm_diff_version
)
if (
helm_diff_version
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,
release_name,
chart_ref,
@@ -1017,14 +1362,24 @@ def main():
reset_values=reset_values,
reset_then_reuse_values=reset_then_reuse_values,
insecure_skip_tls_verify=insecure_skip_tls_verify,
plain_http=plain_http,
skip_schema_validation=skip_schema_validation,
)
if would_change and module._diff:
opt_result["diff"] = {"prepared": prepared}
else:
module.warn(
"The default idempotency check can fail to report changes in certain cases. "
"Install helm diff >= 3.4.1 for better results."
)
if helm_diff_version and not helm_version_compatible:
module.warn(
"Idempotency checks are currently disabled due to a version mismatch."
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(
release_status, chart_info, release_values, values_files
)
@@ -1037,11 +1392,15 @@ def main():
release_values,
chart_ref,
wait,
wait_for_jobs,
wait_timeout,
disable_hook,
force,
values_files=values_files,
atomic=atomic,
cleanup_on_fail=cleanup_on_fail,
server_side=server_side,
force_conflicts=force_conflicts,
create_namespace=create_namespace,
post_renderer=post_renderer,
replace=replace,
@@ -1054,6 +1413,9 @@ def main():
reset_values=reset_values,
reset_then_reuse_values=reset_then_reuse_values,
insecure_skip_tls_verify=insecure_skip_tls_verify,
plain_http=plain_http,
take_ownership=take_ownership,
skip_schema_validation=skip_schema_validation,
)
changed = True
+2 -2
View File
@@ -20,7 +20,7 @@ author:
- Lucas Boisserie (@LucasBoisserie)
requirements:
- "helm (https://github.com/helm/helm/releases)"
- "helm >= 3.0.0 (https://github.com/helm/helm/releases)"
- "yaml (https://pypi.org/project/PyYAML/)"
description:
@@ -253,7 +253,7 @@ def main():
if not IMP_YAML:
module.fail_json(msg=missing_required_lib("yaml"), exception=IMP_YAML_ERR)
# Validate Helm version >=3.0.0,<4.0.0
# Validate Helm version >=3.0.0
module.validate_helm_version()
release_name = module.params.get("release_name")
+67 -18
View File
@@ -16,7 +16,7 @@ version_added: 1.0.0
author:
- Abhijeet Kasurde (@Akasurde)
requirements:
- "helm (https://github.com/helm/helm/releases)"
- "helm >= 3.0.0 (https://github.com/helm/helm/releases)"
description:
- Manages Helm plugins.
options:
@@ -48,6 +48,22 @@ options:
required: false
type: str
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:
- kubernetes.core.helm_common_options
"""
@@ -118,6 +134,9 @@ from ansible_collections.kubernetes.core.plugins.module_utils.helm_args_common i
HELM_AUTH_ARG_SPEC,
HELM_AUTH_MUTUALLY_EXCLUSIVE,
)
from ansible_collections.kubernetes.core.plugins.module_utils.version import (
LooseVersion,
)
def argument_spec():
@@ -138,6 +157,14 @@ def argument_spec():
default="present",
choices=["present", "absent", "latest"],
),
verify=dict(
type="bool",
default=True,
),
keyring=dict(
type="path",
required=False,
),
)
)
return arg_spec
@@ -161,18 +188,50 @@ def main():
mutually_exclusive=mutually_exclusive(),
)
# Validate Helm version >=3.0.0,<4.0.0
# Validate helm version >= 3.0.0
module.validate_helm_version()
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"
if state == "present":
helm_cmd_common += " install %s" % module.params.get("plugin_path")
plugin_version = module.params.get("plugin_version")
verify = module.params.get("verify")
keyring = module.params.get("keyring")
if plugin_version is not None:
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:
rc, out, err = module.run_helm_command(
helm_cmd_common, fails_on_error=False
@@ -211,9 +270,9 @@ def main():
elif state == "absent":
plugin_name = module.params.get("plugin_name")
rc, output, err, command = module.get_helm_plugin_list()
out = parse_helm_plugin_list(output=output.splitlines())
plugins = parse_helm_plugin_list(output=output.splitlines())
if not out:
if not plugins:
module.exit_json(
failed=False,
changed=False,
@@ -224,12 +283,7 @@ def main():
rc=rc,
)
found = False
for line in out:
if line[0] == plugin_name:
found = True
break
if not found:
if all(plugin["name"] != plugin_name for plugin in plugins):
module.exit_json(
failed=False,
changed=False,
@@ -267,9 +321,9 @@ def main():
elif state == "latest":
plugin_name = module.params.get("plugin_name")
rc, output, err, command = module.get_helm_plugin_list()
out = parse_helm_plugin_list(output=output.splitlines())
plugins = parse_helm_plugin_list(output=output.splitlines())
if not out:
if not plugins:
module.exit_json(
failed=False,
changed=False,
@@ -280,12 +334,7 @@ def main():
rc=rc,
)
found = False
for line in out:
if line[0] == plugin_name:
found = True
break
if not found:
if all(plugin["name"] != plugin_name for plugin in plugins):
module.exit_json(
failed=False,
changed=False,
+6 -19
View File
@@ -16,7 +16,7 @@ version_added: 1.0.0
author:
- Abhijeet Kasurde (@Akasurde)
requirements:
- "helm (https://github.com/helm/helm/releases)"
- "helm >= 3.0.0 (https://github.com/helm/helm/releases)"
description:
- Gather information about Helm plugins installed in namespace.
options:
@@ -98,29 +98,16 @@ def main():
supports_check_mode=True,
)
# Validate Helm version >=3.0.0,<4.0.0
# Validate helm version >= 3.0.0
module.validate_helm_version()
plugin_name = module.params.get("plugin_name")
plugin_list = []
rc, output, err, command = module.get_helm_plugin_list()
out = parse_helm_plugin_list(output=output.splitlines())
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
plugins = 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]
module.exit_json(
changed=True,
@@ -128,7 +115,7 @@ def main():
stdout=output,
stderr=err,
rc=rc,
plugin_list=plugin_list,
plugin_list=plugins,
)
+12 -2
View File
@@ -21,7 +21,7 @@ description:
- There are options for unpacking the chart after download.
requirements:
- "helm >= 3.0, <4.0.0 (https://github.com/helm/helm/releases)"
- "helm >= 3.0.0 (https://github.com/helm/helm/releases)"
options:
chart_ref:
@@ -122,6 +122,13 @@ options:
- The path of a helm binary to use.
required: false
type: path
plain_http:
description:
- Use HTTP instead of HTTPS when working with OCI registries
- Requires Helm >= 3.13.0
type: bool
default: False
version_added: 6.1.0
"""
EXAMPLES = r"""
@@ -353,6 +360,7 @@ def main():
chart_ssl_cert_file=dict(type="path"),
chart_ssl_key_file=dict(type="path"),
binary_path=dict(type="path"),
plain_http=dict(type="bool", default=False),
)
module = AnsibleHelmModule(
argument_spec=argspec,
@@ -364,7 +372,7 @@ def main():
mutually_exclusive=[("chart_version", "chart_devel")],
)
# Validate Helm version >=3.0.0,<4.0.0
# Validate Helm version >=3.0.0
module.validate_helm_version()
helm_version = module.get_helm_version()
@@ -374,6 +382,7 @@ def main():
chart_ca_cert="3.1.0",
chart_ssl_cert_file="3.1.0",
chart_ssl_key_file="3.1.0",
plain_http="3.13.0",
)
def test_version_requirement(opt):
@@ -413,6 +422,7 @@ def main():
skip_tls_certs_check=dict(key="insecure-skip-tls-verify"),
chart_devel=dict(key="devel"),
untar_chart=dict(key="untar"),
plain_http=dict(key="plain-http"),
)
for k, v in helm_flag_args.items():
+48 -10
View File
@@ -20,7 +20,7 @@ author:
- Yuriy Novostavskiy (@yurnov)
requirements:
- "helm (https://github.com/helm/helm/releases) >= 3.8.0, <4.0.0"
- "helm (https://github.com/helm/helm/releases) >= 3.8.0"
description:
- Helm registry authentication module allows you to login C(helm registry login) and logout C(helm registry logout) from a Helm registry.
@@ -75,6 +75,14 @@ options:
- Path to the CA certificate SSL file for verify registry server certificate.
required: false
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:
description:
- The path of a helm binary to use.
@@ -98,17 +106,23 @@ EXAMPLES = r"""
RETURN = r"""
stdout:
type: str
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.
- 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
stout_lines:
sample: 'Login Succeeded\n'
stdout_lines:
type: list
description: Full C(helm) command stdout, in case you want to display it or examine the event log
returned: always
stderr:
type: str
description: >-
Full C(helm) 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.
description:
- 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.
- 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
sample: 'Login Succeeded\n'
stderr_lines:
@@ -148,6 +162,7 @@ def arg_spec():
key_file=dict(type="path", required=False),
cert_file=dict(type="path", required=False),
ca_file=dict(type="path", required=False),
plain_http=dict(type="bool", default=False),
)
@@ -160,6 +175,7 @@ def login(
key_file,
cert_file,
ca_file,
plain_http,
):
login_command = command + " registry login " + host
@@ -177,6 +193,8 @@ def login(
if ca_file is not None:
login_command += " --ca-file=" + ca_file
if plain_http:
login_command += " --plain-http"
return login_command
@@ -194,8 +212,8 @@ def main():
supports_check_mode=True,
)
# Validate Helm version >=3.0.0,<4.0.0
module.validate_helm_version()
# Validate Helm version >=3.8.0
module.validate_helm_version(version="3.8.0")
changed = False
@@ -207,6 +225,19 @@ def main():
key_file = module.params.get("key_file")
cert_file = module.params.get("cert_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()
@@ -215,7 +246,15 @@ def main():
changed = True
elif state == "present":
helm_cmd = login(
helm_cmd, host, insecure, username, password, key_file, cert_file, ca_file
helm_cmd,
host,
insecure,
username,
password,
key_file,
cert_file,
ca_file,
plain_http,
)
changed = True
@@ -238,7 +277,6 @@ def main():
command=helm_cmd,
)
helm_version = module.get_helm_version()
if LooseVersion(helm_version) >= LooseVersion("3.18.0") and state == "absent":
# https://github.com/ansible-collections/kubernetes.core/issues/944
module.warn(
+2 -2
View File
@@ -20,7 +20,7 @@ author:
- Lucas Boisserie (@LucasBoisserie)
requirements:
- "helm (https://github.com/helm/helm/releases)"
- "helm >= 3.0.0 (https://github.com/helm/helm/releases)"
- "yaml (https://pypi.org/project/PyYAML/)"
description:
@@ -295,7 +295,7 @@ def main():
if not IMP_YAML:
module.fail_json(msg=missing_required_lib("yaml"), exception=IMP_YAML_ERR)
# Validate Helm version >=3.0.0,<4.0.0
# Validate Helm version >= 3.0.0
module.validate_helm_version()
changed = False
+35 -1
View File
@@ -21,6 +21,10 @@ author:
description:
- 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:
binary_path:
description:
@@ -147,6 +151,13 @@ options:
- json
- file
version_added: 2.4.0
plain_http:
description:
- Use HTTP instead of HTTPS when working with OCI registries
- Requires Helm >= 3.13.0
type: bool
default: False
version_added: 6.1.0
"""
EXAMPLES = r"""
@@ -217,6 +228,10 @@ except ImportError:
from ansible.module_utils.basic import missing_required_lib
from ansible_collections.kubernetes.core.plugins.module_utils.helm import (
AnsibleHelmModule,
strip_registry_progress,
)
from ansible_collections.kubernetes.core.plugins.module_utils.version import (
LooseVersion,
)
@@ -236,6 +251,7 @@ def template(
values_files=None,
include_crds=False,
set_values=None,
plain_http=False,
):
cmd += " template "
@@ -262,6 +278,9 @@ def template(
if insecure_registry:
cmd += " --insecure-skip-tls-verify"
if plain_http:
cmd += " --plain-http"
if show_only:
for template in show_only:
cmd += " -s " + template
@@ -307,6 +326,7 @@ def main():
values_files=dict(type="list", default=[], elements="str"),
update_repo_cache=dict(type="bool", default=False),
set_values=dict(type="list", elements="dict"),
plain_http=dict(type="bool", default=False),
),
supports_check_mode=True,
)
@@ -327,15 +347,25 @@ def main():
values_files = module.params.get("values_files")
update_repo_cache = module.params.get("update_repo_cache")
set_values = module.params.get("set_values")
plain_http = module.params.get("plain_http")
if not IMP_YAML:
module.fail_json(msg=missing_required_lib("yaml"), exception=IMP_YAML_ERR)
# Validate Helm version >=3.0.0,<4.0.0
# Validate Helm version >=3.0.0
module.validate_helm_version()
helm_cmd = module.get_helm_binary()
if plain_http:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.13.0"):
module.fail_json(
msg="plain_http requires helm >= 3.13.0, current version is {0}".format(
helm_version
)
)
if update_repo_cache:
update_cmd = helm_cmd + " repo update"
module.run_helm_command(update_cmd)
@@ -360,10 +390,14 @@ def main():
values_files=values_files,
include_crds=include_crds,
set_values=set_values_args,
plain_http=plain_http,
)
if not check_mode:
rc, out, err = module.run_helm_command(tmpl_cmd)
# 'stdout' is documented to hold the rendered templates, so keep helm's
# OCI registry progress messages out of it.
out = strip_registry_progress(out)
else:
out = err = ""
rc = 0
+14 -1
View File
@@ -76,9 +76,21 @@ options:
- This option is ignored when I(content) is set or when I(state) is set to C(from_pod).
type: bool
default: False
copy_timeout:
description:
- Maximum time in seconds to spend streaming the archive to the pod and waiting for the remote
C(tar) process to finish extracting it.
- Raise this when copying large files over a slow connection.
- This option is ignored when I(state) is set to C(from_pod).
type: int
default: 300
version_added: 6.6.0
notes:
- the tar binary is required on the container when copying from local filesystem to pod.
- a POSIX shell at C(/bin/sh) and C(head) are also used, when present, to bound the archive
sent to the container so that the module can confirm the copy finished. Without them the
copy still runs but completion cannot be verified, and a warning is emitted.
- the (init) container has to be started before you copy files or directories to it.
"""
@@ -140,7 +152,7 @@ result:
import copy
from ansible.module_utils._text import to_native
from ansible.module_utils.common.text.converters import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
AnsibleModule,
)
@@ -180,6 +192,7 @@ def argspec():
"choices": ["to_pod", "from_pod"],
}
argument_spec["no_preserve"] = {"type": "bool", "default": False}
argument_spec["copy_timeout"] = {"type": "int", "default": 300}
return argument_spec
+47 -37
View File
@@ -149,7 +149,7 @@ import time
import traceback
from datetime import datetime
from ansible.module_utils._text import to_native
from ansible.module_utils.common.text.converters import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
AnsibleModule,
)
@@ -230,7 +230,7 @@ def filter_pods(pods, force, ignore_daemonset, delete_emptydir_data):
else:
to_delete.append((pod.metadata.namespace, pod.metadata.name))
warnings, errors = [], []
warnings, errors, info = [], [], []
if unmanaged:
pod_names = ",".join([pod[0] + "/" + pod[1] for pod in unmanaged])
if not force:
@@ -242,7 +242,7 @@ def filter_pods(pods, force, ignore_daemonset, delete_emptydir_data):
)
else:
# Pod not managed will be deleted as 'force' is true
warnings.append(
info.append(
"Deleting Pods not managed by ReplicationController, ReplicaSet, Job, DaemonSet or StatefulSet: {0}.".format(
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)
)
else:
warnings.append("Deleting Pods with local storage: {0}.".format(pod_names))
info.append("Deleting Pods with local storage: {0}.".format(pod_names))
for pod in localStorage:
to_delete.append((pod[0], pod[1]))
@@ -278,8 +278,8 @@ def filter_pods(pods, force, ignore_daemonset, delete_emptydir_data):
)
)
else:
warnings.append("Ignoring DaemonSet-managed Pods: {0}.".format(pod_names))
return to_delete, warnings, errors
info.append("Ignoring DaemonSet-managed Pods: {0}.".format(pod_names))
return to_delete, warnings, errors, info
class K8sDrainAnsible(object):
@@ -334,18 +334,19 @@ class K8sDrainAnsible(object):
def evict_pods(self, pods):
for namespace, name in pods:
try:
if self._drain_options.get("disable_eviction"):
self._api_instance.delete_namespaced_pod(
name=name, namespace=namespace, body=self._delete_options
)
else:
body = v1_eviction(
delete_options=self._delete_options,
metadata=V1ObjectMeta(name=name, namespace=namespace),
)
self._api_instance.create_namespaced_pod_eviction(
name=name, namespace=namespace, body=body
)
if not self._module.check_mode:
if self._drain_options.get("disable_eviction"):
self._api_instance.delete_namespaced_pod(
name=name, namespace=namespace, body=self._delete_options
)
else:
body = v1_eviction(
delete_options=self._delete_options,
metadata=V1ObjectMeta(name=name, namespace=namespace),
)
self._api_instance.create_namespaced_pod_eviction(
name=name, namespace=namespace, body=body
)
self._changed = True
except ApiException as exc:
if exc.reason != "Not Found":
@@ -362,11 +363,7 @@ class K8sDrainAnsible(object):
)
def list_pods(self):
params = {
"field_selector": "spec.nodeName={name}".format(
name=self._module.params.get("name")
)
}
params = {"field_selector": "spec.nodeName=" + self._module.params.get("name")}
pod_selectors = self._module.params.get("pod_selectors")
if pod_selectors:
params["label_selector"] = ",".join(pod_selectors)
@@ -376,7 +373,8 @@ class K8sDrainAnsible(object):
# Mark node as unschedulable
result = []
if not node_unschedulable:
self.patch_node(unschedulable=True)
if not self._module.check_mode:
self.patch_node(unschedulable=True)
result.append(
"node {0} marked unschedulable.".format(self._module.params.get("name"))
)
@@ -391,7 +389,8 @@ class K8sDrainAnsible(object):
def _revert_node_patch():
if self._changed:
self._changed = False
self.patch_node(unschedulable=False)
if not self._module.check_mode:
self.patch_node(unschedulable=False)
try:
pod_list = self.list_pods()
@@ -401,7 +400,7 @@ class K8sDrainAnsible(object):
delete_emptydir_data = self._drain_options.get(
"delete_emptydir_data", False
)
pods, warnings, errors = filter_pods(
pods, warnings, errors, info = filter_pods(
pod_list.items, force, ignore_daemonset, delete_emptydir_data
)
if errors:
@@ -431,18 +430,25 @@ class K8sDrainAnsible(object):
if pods:
self.evict_pods(pods)
number_pod = len(pods)
if self._drain_options.get("wait_timeout") is not None:
warn = self.wait_for_pod_deletion(
pods,
self._drain_options.get("wait_timeout"),
self._drain_options.get("wait_sleep"),
if self._module.check_mode:
result.append(
"Would have deleted {0} Pod(s) from node if not in check mode.".format(
number_pod
)
)
if warn:
warnings.append(warn)
result.append("{0} Pod(s) deleted from node.".format(number_pod))
else:
wait_timeout = self._drain_options.get("wait_timeout")
wait_sleep = self._drain_options.get("wait_sleep")
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:
for warning in warnings:
self._module.warn(warning)
for line in info:
self._module.debug(line)
return dict(result=" ".join(result))
def patch_node(self, unschedulable):
@@ -483,7 +489,8 @@ class K8sDrainAnsible(object):
self._module.exit_json(
result="node {0} already marked unschedulable.".format(name)
)
self.patch_node(unschedulable=True)
if not self._module.check_mode:
self.patch_node(unschedulable=True)
result["result"] = "node {0} marked unschedulable.".format(name)
self._changed = True
@@ -492,7 +499,8 @@ class K8sDrainAnsible(object):
self._module.exit_json(
result="node {0} already marked schedulable.".format(name)
)
self.patch_node(unschedulable=False)
if not self._module.check_mode:
self.patch_node(unschedulable=False)
result["result"] = "node {0} marked schedulable.".format(name)
self._changed = True
@@ -535,7 +543,9 @@ def argspec():
def main():
module = AnsibleK8SModule(module_class=AnsibleModule, argument_spec=argspec())
module = AnsibleK8SModule(
module_class=AnsibleModule, argument_spec=argspec(), supports_check_mode=True
)
if not HAS_EVICTION_API:
module.fail_json(
+1 -1
View File
@@ -131,7 +131,7 @@ except ImportError:
# ImportError are managed by the common module already.
pass
from ansible.module_utils._text import to_native
from ansible.module_utils.common.text.converters import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
AnsibleModule,
)
+40 -10
View File
@@ -53,6 +53,15 @@ options:
type: list
elements: str
version_added: 3.0.0
metadata_only:
description:
- Request metadata only response from the Kubernetes API server.
- This feature is useful for clients that only need to check for the existence of an object,
- or that only need to read its metadata.
- It can significantly reduce the size of the response from the API server.
type: bool
default: false
version_added: 6.6.0
extends_documentation_fragment:
- kubernetes.core.k8s_auth_options
@@ -135,6 +144,12 @@ EXAMPLES = r"""
(ocp_bootstrap_status.resources[0].data.status == 'complete')
retries: 60
delay: 15
- name: Get a list of all pods metadata only
kubernetes.core.k8s_info:
kind: Pod
metadata_only: true
register: pod_metadata_list
"""
RETURN = r"""
@@ -179,6 +194,8 @@ from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule impo
)
from ansible_collections.kubernetes.core.plugins.module_utils.args_common import (
AUTH_ARG_SPEC,
METADATA_ONLY_HEADER_VALUES,
METADATA_ONLY_HEADERS_SPEC,
WAIT_ARG_SPEC,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
@@ -216,15 +233,16 @@ def argspec():
args = copy.deepcopy(AUTH_ARG_SPEC)
args.update(WAIT_ARG_SPEC)
args.update(
dict(
kind=dict(required=True),
api_version=dict(default="v1", aliases=["api", "version"]),
name=dict(),
namespace=dict(),
label_selectors=dict(type="list", elements="str", default=[]),
field_selectors=dict(type="list", elements="str", default=[]),
hidden_fields=dict(type="list", elements="str"),
)
{
"kind": {"required": True},
"api_version": {"default": "v1", "aliases": ["api", "version"]},
"name": {},
"namespace": {},
"label_selectors": {"type": "list", "elements": "str", "default": []},
"field_selectors": {"type": "list", "elements": "str", "default": []},
"hidden_fields": {"type": "list", "elements": "str"},
"metadata_only": {"type": "bool", "default": False},
}
)
return args
@@ -233,8 +251,20 @@ def main():
module = AnsibleK8SModule(
module_class=AnsibleModule, argument_spec=argspec(), supports_check_mode=True
)
metadata_only_headers = {}
if module.params["metadata_only"]:
metadata_only_headers = copy.deepcopy(METADATA_ONLY_HEADERS_SPEC)
metadata_only_headers.update(
{"accept": METADATA_ONLY_HEADER_VALUES["partial_object_list"]}
)
if module.params["name"]:
metadata_only_headers.update(
{"accept": METADATA_ONLY_HEADER_VALUES["partial_object"]}
)
try:
client = get_api_client(module)
client = get_api_client(module, **metadata_only_headers)
svc = K8sService(client, module)
execute_module(module, svc)
except CoreException as e:
+14 -3
View File
@@ -33,6 +33,14 @@ options:
aliases:
- api
- version
hidden_fields:
description:
- List of fields to hide from the diff output.
- This is useful for fields that are not relevant to the patch operation, such as `metadata.managedFields`.
type: list
elements: str
default: []
version_added: 6.1.0
kind:
description:
- Use to specify an object model.
@@ -127,8 +135,8 @@ error:
import copy
import traceback
from ansible.module_utils._text import to_native
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 (
AnsibleModule,
)
@@ -147,6 +155,7 @@ from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions imp
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.service import (
diff_objects,
hide_fields,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.waiter import (
get_waiter,
@@ -174,6 +183,7 @@ JSON_PATCH_ARGS = {
"namespace": {"type": "str"},
"name": {"type": "str", "required": True},
"patch": {"type": "list", "required": True, "elements": "dict"},
"hidden_fields": {"type": "list", "elements": "str", "default": []},
}
@@ -203,6 +213,7 @@ def execute_module(module, client):
namespace = module.params.get("namespace")
patch = module.params.get("patch")
hidden_fields = module.params.get("hidden_fields")
wait = module.params.get("wait")
wait_sleep = module.params.get("wait_sleep")
wait_timeout = module.params.get("wait_timeout")
@@ -260,13 +271,13 @@ def execute_module(module, client):
module.fail_json(msg=msg, error=to_native(exc), status="", reason="")
success = True
result = {"result": obj}
result = {"result": hide_fields(obj, hidden_fields)}
if wait and not module.check_mode:
waiter = get_waiter(client, resource, condition=wait_condition)
success, result["result"], result["duration"] = waiter.wait(
wait_timeout, wait_sleep, name, namespace
)
match, diffs = diff_objects(existing.to_dict(), obj)
match, diffs = diff_objects(existing.to_dict(), obj, hidden_fields)
result["changed"] = not match
if module._diff:
result["diff"] = diffs
+1 -1
View File
@@ -149,7 +149,7 @@ except ImportError:
# Handled in module setup
pass
from ansible.module_utils._text import to_native
from ansible.module_utils.common.text.converters import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
AnsibleModule,
)
+1 -1
View File
@@ -126,7 +126,7 @@ result:
import copy
from ansible.module_utils._text import to_native
from ansible.module_utils.common.text.converters import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
AnsibleModule,
)
+490
View File
@@ -0,0 +1,490 @@
#!/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()
+1 -1
View File
@@ -9,7 +9,7 @@ sonar.python.coverage.reportPaths=coverage.xml
sonar.tests=tests/unit,tests/integration
sonar.python.version=3.12
sonar.newCode.referenceBranch=stable-5
sonar.newCode.referenceBranch=stable-6
sonar.exclusions=tests/**,.tox/**
+1 -4
View File
@@ -1,4 +1 @@
time=100
helm_info
helm_repository
helm_template
disabled # used by test targets helm_vX_XX_XX
@@ -9,23 +9,26 @@ chart_test_version: 4.2.4
chart_test_version_local_path: 1.32.0
chart_test_version_upgrade: 4.2.5
chart_test_version_upgrade_local_path: 1.33.0
chart_test_repo: "https://kubernetes.github.io/ingress-nginx"
chart_test_repo: "https://stenic.github.io/k8status/"
chart_test_git_repo: "http://github.com/helm/charts.git"
chart_test_values:
revisionHistoryLimit: 0
myValue: "changed"
test_namespace:
- "helm-test-crds"
- "helm-uninstall"
- "helm-read-envvars"
- "helm-dep-update"
- "helm-local-path-001"
- "helm-local-path-002"
- "helm-local-path-003"
- "helm-from-repository"
- "helm-from-url"
- "helm-reuse-values"
- "helm-chart-with-space-into-name"
- "helm-reset-then-reuse-values"
- "helm-insecure"
- "helm-test-crds-{{ helm_version | replace('.', '-') }}"
- "helm-uninstall-{{ helm_version | replace('.', '-') }}"
- "helm-read-envvars-{{ helm_version | replace('.', '-') }}"
- "helm-dep-update-{{ helm_version | replace('.', '-') }}"
- "helm-local-path-001-{{ helm_version | replace('.', '-') }}"
- "helm-local-path-002-{{ helm_version | replace('.', '-') }}"
- "helm-local-path-003-{{ helm_version | replace('.', '-') }}"
- "helm-from-repository-{{ helm_version | replace('.', '-') }}"
- "helm-from-url-{{ helm_version | replace('.', '-') }}"
- "helm-reuse-values-{{ helm_version | replace('.', '-') }}"
- "helm-chart-with-space-into-name-{{ helm_version | replace('.', '-') }}"
- "helm-reset-then-reuse-values-{{ helm_version | replace('.', '-') }}"
- "helm-insecure-{{ helm_version | replace('.', '-') }}"
- "helm-test-take-ownership-{{ helm_version | replace('.', '-') }}"
- "helm-skip-schema-validation-{{ helm_version | replace('.', '-') }}"
- "helm-wait-for-jobs-{{ helm_version | replace('.', '-') }}"
@@ -0,0 +1,6 @@
apiVersion: v2
name: test-chart-job
description: A chart with a Job for testing wait_for_jobs
type: application
version: 0.1.0
appVersion: "default"
@@ -0,0 +1,21 @@
apiVersion: batch/v1
kind: Job
metadata:
name: "{{ .Release.Name }}-job"
spec:
backoffLimit: 0
template:
spec:
automountServiceAccountToken: false
restartPolicy: Never
containers:
- name: test
image: "busybox:1.37"
command: ["sh", "-c", "echo done"]
resources:
requests:
cpu: "50m"
memory: "32Mi"
ephemeral-storage: "16Mi"
limits:
memory: "64Mi"
@@ -52,7 +52,9 @@ import json
import subprocess
import time
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.kubernetes.core.plugins.module_utils.helm import (
AnsibleHelmModule,
)
class HelmReleaseNotFoundError(Exception):
@@ -60,7 +62,9 @@ class HelmReleaseNotFoundError(Exception):
super().__init__(message)
def create_pending_install_release(helm_binary, chart_ref, chart_release, namespace):
def create_pending_install_release(
module, helm_binary, chart_ref, chart_release, namespace
):
# create pending-install release
command = [
helm_binary,
@@ -78,13 +82,14 @@ def create_pending_install_release(helm_binary, chart_ref, chart_release, namesp
command = [
helm_binary,
"list",
"--all",
"--output=json",
"--namespace",
namespace,
"--filter",
chart_release,
]
if not module.is_helm_v4():
command.append("--all")
cmd = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = cmd.communicate()
@@ -92,11 +97,11 @@ def create_pending_install_release(helm_binary, chart_ref, chart_release, namesp
if not data:
error = "Release %s not found." % chart_release
raise HelmReleaseNotFoundError(message=error)
return data[0]["status"] == "pending-install", data[0]["status"]
return data[0]["status"] in ("pending-install", "failed"), data[0]["status"]
def main():
module = AnsibleModule(
module = AnsibleHelmModule(
argument_spec=dict(
binary_path=dict(type="path", required=True),
chart_ref=dict(type="str", required=True),
@@ -106,6 +111,7 @@ def main():
)
params = dict(
module=module,
helm_binary=module.params.get("binary_path"),
chart_release=module.params.get("chart_release"),
chart_ref=module.params.get("chart_ref"),
@@ -116,7 +122,7 @@ def main():
result, status = create_pending_install_release(**params)
if not result:
module.fail_json(
msg="unable to create pending-install release, current status is %s"
msg="unable to create pending-install/failed release, current status is %s"
% status
)
module.exit_json(changed=True, msg="Release created with status '%s'" % status)
@@ -1,5 +1,3 @@
---
collections:
- kubernetes.core
dependencies:
- remove_namespace
@@ -1,7 +0,0 @@
---
- connection: local
gather_facts: true
hosts: localhost
roles:
- helm
@@ -1,15 +0,0 @@
---
- 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
+19 -7
View File
@@ -1,10 +1,22 @@
---
- 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 v4
ansible.builtin.include_role:
name: install_helm
vars:
helm_version: v3.6.0
- name: Test helm uninstall
ansible.builtin.include_tasks: test_helm_uninstall.yml
- name: Run tests
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,25 +1,19 @@
---
- 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"
- name: Main helm tests
block:
- name: Install helm-diff plugin
helm_plugin:
binary_path: "{{ helm_binary }}"
plugin_path: https://github.com/databus23/helm-diff
plugin_version: "{{ helm_version is version('v4.0.0', '>=') | ternary('v3.14.0', 'v3.10.0') }}"
verify: false
- name: "Ensure we honor the environment variables"
include_tasks: test_read_envvars.yml
when: helm_version != "v4.0.0"
- name: Deploy charts
include_tasks: "tests_chart/{{ test_chart_type }}.yml"
@@ -39,9 +33,6 @@
- name: test helm dependency update
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
include_tasks: test_helm_with_space_into_chart_name.yml
@@ -52,12 +43,24 @@
- name: Test insecure registry flag feature
include_tasks: test_helm_insecure.yml
- name: Test helm version
include_tasks: test_helm_version.yml
- name: Test take ownership flag feature
include_tasks: test_helm_take_ownership.yml
- name: Clean helm install
file:
path: "{{ item }}"
state: absent
with_items:
- "/tmp/helm/"
- name: Test helm skip_schema_validation
include_tasks: test_skip_schema_validation.yml
- name: Test helm wait_for_jobs
include_tasks: test_helm_wait_for_jobs.yml
always:
- name: Remove helm-diff plugin
helm_plugin:
binary_path: "{{ helm_binary }}"
plugin_name: diff
state: absent
ignore_errors: true
- name: Clean helm install
ansible.builtin.file:
path: "/tmp/helm/"
state: absent
@@ -5,7 +5,7 @@
name: test
chart_ref: "{{ chart_test }}"
namespace: "helm-test"
ignore_errors: yes
ignore_errors: true
register: helm_missing_binary
- name: Assert that helm is not installed
@@ -38,6 +38,28 @@
- '"--reset-then-reuse-values" not in install.command'
- 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
helm:
binary_path: "{{ helm_binary }}"
@@ -73,3 +95,4 @@
kind: Namespace
name: "{{ helm_namespace }}"
state: absent
wait: false
@@ -38,6 +38,21 @@
- '"--reuse-values=True" not in install.command'
- release_value["status"]["release_values"] == chart_release_values
- name: Retrieve release password
kubernetes.core.k8s_info:
namespace: "{{ helm_namespace }}"
kind: Secret
name: test-redis
register: redis_secret
- ansible.builtin.set_fact:
chart_reuse_values: "{{ chart_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 reuse_values=true
helm:
binary_path: "{{ helm_binary }}"
@@ -0,0 +1,101 @@
---
- name: Test helm take ownership
vars:
helm_namespace: "{{ test_namespace[13] }}"
block:
- name: Initial chart installation (no flag set)
helm:
binary_path: "{{ helm_binary }}"
chart_ref: "{{ chart_test_oci }}"
release_name: test-take-ownership
release_namespace: "{{ helm_namespace }}"
create_namespace: true
register: install
- name: Validate that take-ownership flag is not set
assert:
that:
- install is changed
- '"--take-ownership" not in install.command'
# 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-take-ownership-redis
register: redis_secret
- name: Upgrade chart (take-onwership flag set)
helm:
binary_path: "{{ helm_binary }}"
chart_ref: "{{ chart_test_oci }}"
release_name: test-take-ownership
release_namespace: "{{ helm_namespace }}"
take_ownership: true
values:
commonLabels:
take-onwership: "set"
global:
redis:
password: "{{ redis_secret.resources.0.data['redis-password'] | b64decode }}"
register: upgrade
ignore_errors: true
- name: Validate that take-ownership flag IS set if helm version is >= 3.17.0
assert:
that:
- upgrade is changed
- '"--take-ownership" in upgrade.command'
when: '"v3.17.0" <= helm_version'
- name: Validate that feature fails for helm < 3.17.0
assert:
that:
- upgrade is failed
- '"take_ownership requires helm >= 3.17.0" in upgrade.msg'
when: 'helm_version < "v3.17.0"'
- name: Upgrade chart (take-onwership flag not set)
helm:
binary_path: "{{ helm_binary }}"
chart_ref: "{{ chart_test_oci }}"
release_name: test-take-ownership
release_namespace: "{{ helm_namespace }}"
values:
commonLabels:
take-onwership: "not-set"
global:
redis:
password: "{{ redis_secret.resources.0.data['redis-password'] | b64decode }}"
register: upgrade
ignore_errors: true
- name: Validate that take-ownership flag IS set if helm version is >= 3.17.0
assert:
that:
- upgrade is changed
- '"--take-ownership" not in upgrade.command'
when: '"v3.17.0" <= helm_version'
- name: Validate that feature fails for helm < 3.17.0
assert:
that:
- upgrade is changed
- upgrade.msg is not defined
when: 'helm_version < "v3.17.0"'
always:
- name: Remove helm namespace
k8s:
api_version: v1
kind: Namespace
name: "{{ helm_namespace }}"
state: absent
@@ -31,26 +31,18 @@
- name: assert warning has been raised
assert:
that:
- uninstall.warnings
- uninstall.warnings is defined
- '"helm uninstall support option --wait for helm release >= 3.7.0" in uninstall.warnings'
- name: Create temp directory
tempfile:
state: directory
suffix: .test
register: _result
- set_fact:
helm_tmp_dir: "{{ _result.path }}"
- name: Unarchive Helm binary
unarchive:
src: 'https://get.helm.sh/helm-v3.7.0-linux-amd64.tar.gz'
dest: "{{ helm_tmp_dir }}"
remote_src: yes
- name: Install Helm v4
ansible.builtin.include_role:
name: install_helm
vars:
helm_version: v4.0.0
- name: Install chart
helm:
binary_path: "{{ helm_tmp_dir }}/linux-amd64/helm"
binary_path: "{{ helm_binary }}"
name: "{{ chart_name }}"
chart_ref: "{{ chart_source }}"
namespace: "{{ helm_namespace }}"
@@ -59,7 +51,7 @@
- name: uninstall chart again using recent version
helm:
state: absent
binary_path: "{{ helm_tmp_dir }}/linux-amd64/helm"
binary_path: "{{ helm_binary }}"
name: "{{ chart_name }}"
namespace: "{{ helm_namespace }}"
wait: yes
@@ -96,12 +88,6 @@
- _info.status is undefined
always:
- name: Delete temp directory
file:
path: "{{ helm_tmp_dir }}"
state: absent
ignore_errors: true
- name: Remove namespace
k8s:
kind: Namespace
@@ -0,0 +1,59 @@
---
- name: Test helm wait_for_jobs
vars:
helm_namespace: "{{ test_namespace[15] }}"
chart_local: "{{ role_path }}/files/test-chart-job"
block:
- name: Install chart with wait and wait_for_jobs
helm:
binary_path: "{{ helm_binary }}"
chart_ref: "{{ chart_local }}"
release_name: test-wait-for-jobs
release_namespace: "{{ helm_namespace }}"
create_namespace: true
wait: true
wait_for_jobs: true
wait_timeout: "120s"
register: install
ignore_errors: true
- name: Validate wait_for_jobs with helm >= 3.5.0 works
assert:
that:
- install is changed
- "'--wait' in install.command"
- "'--wait-for-jobs' in install.command"
when: "helm_version is ansible.builtin.version('v3.5.0', '>=')"
- name: Validate wait_for_jobs with helm < 3.5.0 fails
assert:
that:
- install is failed
- "'wait_for_jobs requires helm >= 3.5.0' in install.msg"
when: "helm_version is ansible.builtin.version('v3.5.0', '<')"
- name: Install chart with wait_for_jobs but without wait
helm:
binary_path: "{{ helm_binary }}"
chart_ref: "{{ chart_local }}"
release_name: test-wait-for-jobs-no-wait
release_namespace: "{{ helm_namespace }}"
create_namespace: true
wait_for_jobs: true
register: install_no_wait
- name: Validate wait_for_jobs is ignored without wait
assert:
that:
- install_no_wait is changed
- "'--wait-for-jobs' not in install_no_wait.command"
- "'--wait' not in install_no_wait.command"
always:
- name: Remove helm namespace
k8s:
api_version: v1
kind: Namespace
name: "{{ helm_namespace }}"
state: absent
@@ -1,20 +1,15 @@
---
- name: Test helm reuse_values
- name: Test helm skip_schema_validation
vars:
helm_namespace: "{{ test_namespace[12] }}"
helm_namespace: "{{ test_namespace[14] }}"
chart_release_values:
replica:
replicaCount: 3
master:
count: 1
kind: Deployment
chart_reuse_values:
replica:
replicaCount: 1
master:
count: 3
block:
- name: Initial chart installation
- name: Chart installation
helm:
binary_path: "{{ helm_binary }}"
chart_ref: oci://registry-1.docker.io/bitnamicharts/redis
@@ -22,21 +17,27 @@
release_namespace: "{{ helm_namespace }}"
create_namespace: true
release_values: "{{ chart_release_values }}"
skip_schema_validation: true
register: install
ignore_errors: true
when: helm_version == "v4.0.0"
- name: Debug install result
debug:
var: install
when: helm_version == "v4.0.0"
- name: Ensure helm installation was failed for v4.0.0
- name: Validate skip_schema_validation with helm >= 3.16.0 works
assert:
that:
- install is changed
- "'--skip-schema-validation' in install.command"
when: "helm_version is ansible.builtin.version('v3.16.0', '>=')"
- name: Validate skip_schema_validation with helm < 3.16.0 fails
assert:
that:
- install is failed
- "'Helm version must be >=3.0.0,<4.0.0' in install.msg"
when: helm_version == "v4.0.0"
- "'skip_schema_validation requires helm >= 3.16.0' in install.msg"
when: "helm_version is ansible.builtin.version('v3.16.0', '<')"
always:
- name: Remove helm namespace
@@ -30,9 +30,9 @@
binary_path: "{{ helm_binary }}"
name: "{{ chart_release_name }}"
chart_ref: "{{ chart_source }}"
chart_version: "{{ chart_source_version | default(omit) }}"
chart_version: "{{ chart_test_version }}"
namespace: "{{ helm_namespace }}"
ignore_errors: yes
ignore_errors: true
register: install_fail
- name: "Assert that Install fail {{ chart_test }} from {{ source }}"
@@ -46,7 +46,7 @@
binary_path: "{{ helm_binary }}"
name: "{{ chart_release_name }}"
chart_ref: "{{ chart_source }}"
chart_version: "{{ chart_source_version | default(omit) }}"
chart_version: "{{ chart_test_version }}"
namespace: "{{ helm_namespace }}"
create_namespace: true
register: install_check_mode
@@ -64,17 +64,18 @@
binary_path: "{{ helm_binary }}"
name: "{{ chart_release_name }}"
chart_ref: "{{ chart_source }}"
chart_version: "{{ chart_source_version | default(omit) }}"
chart_version: "{{ chart_test_version }}"
namespace: "{{ helm_namespace }}"
create_namespace: true
register: install
- name: "Assert that {{ chart_test }} chart is installed from {{ source }}"
- name: "Assert that {{ chart_test }} chart version {{ chart_test_version }} is installed from {{ source }}"
assert:
that:
- install is changed
- install.status.chart == chart_test+"-"+chart_test_version
- install.status.status | lower == 'deployed'
- install.status.release_values == {}
- name: Check helm_info content
helm_info:
@@ -92,7 +93,7 @@
- deployed
register: release_state_content_info
- name: "Assert that {{ chart_test }} is installed from {{ source }} with helm_info"
- name: "Assert that {{ chart_test }} chart version {{ chart_test_version }} is installed from {{ source }} with helm_info"
assert:
that:
- content_info.status.chart == chart_test+"-"+chart_test_version
@@ -104,9 +105,10 @@
binary_path: "{{ helm_binary }}"
name: "{{ chart_release_name }}"
chart_ref: "{{ chart_source }}"
chart_version: "{{ chart_source_version | default(omit) }}"
chart_version: "{{ chart_test_version }}"
namespace: "{{ helm_namespace }}"
register: install
diff: true
- name: Assert idempotency
assert:
@@ -120,7 +122,7 @@
binary_path: "{{ helm_binary }}"
name: "{{ chart_release_name }}"
chart_ref: "{{ chart_source }}"
chart_version: "{{ chart_source_version | default(omit) }}"
chart_version: "{{ chart_test_version }}"
namespace: "{{ helm_namespace }}"
values: "{{ chart_test_values }}"
register: install
@@ -131,17 +133,18 @@
- install is changed
- install.status.status | lower == 'deployed'
- install.status.chart == chart_test+"-"+chart_test_version
- "install.status['release_values'].revisionHistoryLimit == 0"
- install.status['release_values'] == chart_test_values
- name: Check idempotency after adding vars
helm:
binary_path: "{{ helm_binary }}"
name: "{{ chart_release_name }}"
chart_ref: "{{ chart_source }}"
chart_version: "{{ chart_source_version | default(omit) }}"
chart_version: "{{ chart_test_version }}"
namespace: "{{ helm_namespace }}"
values: "{{ chart_test_values }}"
register: install
diff: true
- name: Assert idempotency after add vars
assert:
@@ -149,14 +152,14 @@
- install is not changed
- install.status.status | lower == 'deployed'
- install.status.chart == chart_test+"-"+chart_test_version
- "install.status['release_values'].revisionHistoryLimit == 0"
- install.status['release_values'] == chart_test_values
- name: "Remove Vars to {{ chart_test }} from {{ source }}"
helm:
binary_path: "{{ helm_binary }}"
name: "{{ chart_release_name }}"
chart_ref: "{{ chart_source }}"
chart_version: "{{ chart_source_version | default(omit) }}"
chart_version: "{{ chart_test_version }}"
namespace: "{{ helm_namespace }}"
register: install
@@ -173,9 +176,10 @@
binary_path: "{{ helm_binary }}"
name: "{{ chart_release_name }}"
chart_ref: "{{ chart_source }}"
chart_version: "{{ chart_source_version | default(omit) }}"
chart_version: "{{ chart_test_version }}"
namespace: "{{ helm_namespace }}"
register: install
diff: true
- name: Assert idempotency after removing vars
assert:
@@ -190,7 +194,7 @@
binary_path: "{{ helm_binary }}"
name: "{{ chart_release_name }}"
chart_ref: "{{ chart_source_upgrade | default(chart_source) }}"
chart_version: "{{ chart_source_version_upgrade | default(omit) }}"
chart_version: "{{ chart_test_version_upgrade }}"
namespace: "{{ helm_namespace }}"
register: install
@@ -206,9 +210,10 @@
binary_path: "{{ helm_binary }}"
name: "{{ chart_release_name }}"
chart_ref: "{{ chart_source_upgrade | default(chart_source) }}"
chart_version: "{{ chart_source_version_upgrade | default(omit) }}"
chart_version: "{{ chart_test_version_upgrade }}"
namespace: "{{ helm_namespace }}"
register: install
diff: true
- name: Assert idempotency after upgrade
assert:
@@ -237,6 +242,7 @@
name: "{{ chart_release_name }}"
namespace: "{{ helm_namespace }}"
register: install
diff: true
- name: Assert idempotency
assert:
@@ -249,7 +255,7 @@
binary_path: "{{ helm_binary }}"
name: "{{ chart_release_replaced_name }}"
chart_ref: "{{ chart_source }}"
chart_version: "{{ chart_source_version | default(omit) }}"
chart_version: "{{ chart_test_version }}"
namespace: "{{ helm_namespace }}"
register: install
@@ -277,7 +283,7 @@
binary_path: "{{ helm_binary }}"
name: "{{ chart_release_replaced_name }}"
chart_ref: "{{ chart_source }}"
chart_version: "{{ chart_source_version | default(omit) }}"
chart_version: "{{ chart_test_version }}"
namespace: "{{ helm_namespace }}"
replace: True
register: install
@@ -305,7 +311,7 @@
binary_path: "{{ helm_binary }}"
name: "{{ chart_release_name }}"
chart_ref: "{{ chart_source }}"
chart_version: "{{ chart_source_version | default(omit) }}"
chart_version: "{{ chart_test_version }}"
namespace: "{{ helm_namespace }}"
values_files:
- "{{ role_path }}/files/values.yaml"
@@ -324,7 +330,7 @@
binary_path: "{{ helm_binary }}"
name: "{{ chart_release_name }}"
chart_ref: "{{ chart_source }}"
chart_version: "{{ chart_source_version | default(omit) }}"
chart_version: "{{ chart_test_version }}"
namespace: "{{ helm_namespace }}"
values_files:
- "{{ role_path }}/files/values.yaml"
@@ -346,7 +352,7 @@
helm_template:
binary_path: "{{ helm_binary }}"
chart_ref: "{{ chart_source }}"
chart_version: "{{ chart_source_version | default(omit) }}"
chart_version: "{{ chart_test_version }}"
output_dir: "{{ temp_dir }}"
values_files:
- "{{ role_path }}/files/values.yaml"
@@ -372,7 +378,7 @@
helm_template:
binary_path: "{{ helm_binary }}"
chart_ref: "{{ chart_source }}"
chart_version: "{{ chart_source_version | default(omit) }}"
chart_version: "{{ chart_test_version }}"
disable_hook: True
release_name: "myrelease"
release_namespace: "myreleasenamespace"
@@ -398,7 +404,7 @@
binary_path: "{{ helm_binary }}"
name: "{{ chart_release_name }}"
chart_ref: "{{ chart_source }}"
chart_version: "{{ chart_source_version | default(omit) }}"
chart_version: "{{ chart_test_version }}"
namespace: "{{ helm_namespace }}"
create_namespace: true
context: does-not-exist
@@ -417,6 +423,7 @@
state: absent
path: "{{ temp_dir }}"
ignore_errors: true
when: temp_dir is defined
- name: Remove helm namespace
k8s:
@@ -5,18 +5,38 @@
name: test_helm
repo_url: "{{ chart_test_repo }}"
- name: Install Chart from repository
include_tasks: "../tests_chart.yml"
vars:
source: repository
chart_source: "test_helm/{{ chart_test }}"
chart_source_version: "{{ chart_test_version }}"
chart_source_version_upgrade: "{{ chart_test_version_upgrade }}"
helm_namespace: "{{ test_namespace[7] }}"
- name: Create temporary file to save values in
ansible.builtin.tempfile:
suffix: .helm_values
register: value_file
- name: Remove chart repo
helm_repository:
binary_path: "{{ helm_binary }}"
name: test_helm
repo_url: "{{ chart_test_repo }}"
state: absent
- vars:
source: repository
chart_test: k8status
chart_source: "test_helm/k8status"
chart_test_version: "0.16.1"
chart_test_version_upgrade: "0.16.2"
helm_namespace: "{{ test_namespace[7] }}"
chart_test_values:
replicaCount: 3
block:
- name: Save values into file
ansible.builtin.copy:
content: "{{ chart_test_values }}"
dest: "{{ value_file.path }}"
- name: Install Chart from repository
ansible.builtin.include_tasks: "../tests_chart.yml"
always:
- name: Remove temporary file
ansible.builtin.file:
state: absent
path: "{{ value_file.path }}"
- name: Remove chart repo
helm_repository:
binary_path: "{{ helm_binary }}"
name: test_helm
repo_url: "{{ chart_test_repo }}"
state: absent
@@ -3,6 +3,11 @@
include_tasks: "../tests_chart.yml"
vars:
source: url
chart_source: "https://github.com/kubernetes/ingress-nginx/releases/download/helm-chart-{{ chart_test_version }}/{{ chart_test }}-{{ chart_test_version }}.tgz"
chart_source_upgrade: "https://github.com/kubernetes/ingress-nginx/releases/download/helm-chart-{{ chart_test_version_upgrade }}/{{ chart_test }}-{{ chart_test_version_upgrade }}.tgz"
chart_test: "k8status"
chart_test_values:
replicaCount: 3
chart_test_version: "0.16.1"
chart_test_version_upgrade: "0.16.2"
chart_source: https://github.com/stenic/k8status/releases/download/k8status-0.16.1/k8status-0.16.1.tgz
chart_source_upgrade: https://github.com/stenic/k8status/releases/download/k8status-0.16.2/k8status-0.16.2.tgz
helm_namespace: "{{ test_namespace[8] }}"
@@ -92,25 +92,11 @@
path: /tmp/helm/
state: absent
- name: Init Helm folders
file:
path: /tmp/helm
state: directory
- name: Set Helm old version
set_fact:
helm_archive_name: "helm-v3.8.0-linux-amd64.tar.gz"
helm_diff_old_version: "3.8.0"
- 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
- name: Install old version of helm
ansible.builtin.include_role:
name: install_helm
vars:
helm_version: "v3.8.0"
- name: Upgrade helm release (with reset_then_reuse_values=true)
kubernetes.core.helm:
@@ -140,7 +126,7 @@
binary_path: "{{ helm_binary }}"
state: present
plugin_path: https://github.com/databus23/helm-diff
plugin_version: "{{ helm_diff_old_version }}"
plugin_version: "3.8.0"
- name: Upgrade helm release (with reset_then_reuse_values=true)
kubernetes.core.helm:
@@ -166,6 +152,11 @@
- '"reset_then_reuse_values requires helm diff >= 3.9.12, current version is" in helm_upgrade.msg'
always:
- name: Delete Helm folders
file:
path: /tmp/helm/
state: absent
- name: Remove temporary directory
file:
path: "{{ helm_dir.path }}"
@@ -1,7 +1,10 @@
---
helm_binary: "/tmp/helm/{{ ansible_system | lower }}-amd64/helm"
default_kubeconfig_path: "~/.kube/config"
test_namespace:
- "helm-in-memory-kubeconfig"
- "helm-kubeconfig-with-ca-cert"
- "helm-kubeconfig-with-insecure-skip-tls-verify"
helm_versions:
- v3.10.3
- v3.16.4
- v4.0.0
@@ -57,7 +57,7 @@
assert:
that:
- _install is failed
- '"Error: Kubernetes cluster unreachable" in _install.msg'
- '"error: kubernetes cluster unreachable" in _install.msg | lower()'
- name: Test helm modules using in-memory kubeconfig
include_tasks: "tests_helm_auth.yml"
@@ -48,7 +48,7 @@
assert:
that:
- _install is failed
- '"Error: Kubernetes cluster unreachable" in _install.msg'
- '"error: kubernetes cluster unreachable" in _install.msg | lower()'
- name: Test helm modules using in-memory kubeconfig
include_tasks: "tests_helm_auth.yml"
@@ -1,21 +1,5 @@
---
- name: Test helm with in-memory kubeconfig
include_tasks: "from_in_memory_kubeconfig.yml"
- ansible.builtin.include_tasks: run_tests.yml
loop: "{{ helm_versions }}"
loop_control:
loop_var: test_helm_version
with_items:
- "v3.10.3"
- name: Test helm with custom kubeconfig and validate_certs=false
include_tasks: "from_kubeconfig_with_validate_certs.yml"
loop_control:
loop_var: test_helm_version
with_items:
- "v3.10.3"
- name: Test helm with custom kubeconfig and ca_cert
include_tasks: "from_kubeconfig_with_cacert.yml"
loop_control:
loop_var: test_helm_version
with_items:
- "v3.10.3"
loop_var: helm_version
@@ -0,0 +1,15 @@
---
- name: Run tests with helm version "{{ helm_version }}"
block:
- name: "Install Helm"
ansible.builtin.include_role:
name: install_helm
- name: Test helm with in-memory kubeconfig
ansible.builtin.include_tasks: "from_in_memory_kubeconfig.yml"
- name: Test helm with custom kubeconfig and validate_certs=false
include_tasks: "from_kubeconfig_with_validate_certs.yml"
- name: Test helm with custom kubeconfig and ca_cert
include_tasks: "from_kubeconfig_with_cacert.yml"
@@ -5,16 +5,6 @@
suffix: .helm
register: _dir
- name: Install helm binary
block:
- name: "Install {{ test_helm_version }}"
include_role:
name: install_helm
vars:
helm_version: "{{ test_helm_version }}"
when: test_helm_version is defined
- set_fact:
saved_kubeconfig_path: "{{ _dir.path }}/config"
@@ -44,6 +34,7 @@
ca_cert: "{{ test_ca_cert | default(omit) }}"
state: present
plugin_path: https://github.com/hydeenoble/helm-subenv
verify: false
register: plugin
- assert:
@@ -0,0 +1,3 @@
time=10
helm
helm_template
@@ -0,0 +1,20 @@
---
# Helm >= 4.2.1 is required for this test to be meaningful: that is the release which
# moved the OCI registry progress messages from stderr to stdout (helm/helm#32056).
helm_oci_version: v4.2.4
helm_oci_namespace: helm-oci-registry-progress
test_namespace: "{{ helm_oci_namespace }}"
# Matches the registry stood up by the setup_helm_registry role.
helm_oci_registry: "localhost:6035"
helm_oci_registry_username: testuser
helm_oci_registry_password: 'pass123!'
helm_oci_repo_path: testing
helm_oci_chart_name: test-chart-plus-version
# '+' is not allowed in an OCI tag, so Helm stores this as '1.0.0_build.1'.
helm_oci_chart_version: 1.0.0+build.1
# A version without build metadata, to cover the case where the progress messages
# happen to be valid YAML and so corrupt the parsed output silently.
helm_oci_chart_version_plain: 1.0.1
@@ -0,0 +1,6 @@
apiVersion: v2
name: test-chart-plus-version
description: A chart whose version carries semver build metadata
type: application
version: 1.0.0+build.1
appVersion: "default"
@@ -0,0 +1,6 @@
apiVersion: v1
kind: ConfigMap
metadata:
name: test-chart-plus-version-configmap
data:
myValue: test
@@ -1,4 +1,4 @@
---
dependencies:
- remove_namespace
- install_helm
- setup_helm_registry
@@ -0,0 +1,158 @@
---
# Regression test for https://github.com/ansible-collections/kubernetes.core/issues/1222
#
# Helm >= 4.2.1 writes OCI registry progress messages to stdout rather than stderr
# (helm/helm#32056): 'Pulled:', 'Digest:' and, when the reference contains an
# underscore, a free-text explanation. Helm rewrites '+' to '_' in OCI tags, so a
# chart version carrying semver build metadata is what triggers that explanation,
# which is not valid YAML.
#
# The helm module parses the stdout of 'helm show chart', and helm_template returns
# the stdout of 'helm template' as its documented result, so both have to skip those
# messages. Without the fix, the helm task below fails with
# "could not find expected ':'".
- name: Test OCI charts whose version contains build metadata
vars:
chart_ref: "oci://{{ helm_oci_registry }}/{{ helm_oci_repo_path }}/{{ helm_oci_chart_name }}"
block:
- name: "Install Helm {{ helm_oci_version }}"
ansible.builtin.include_role:
name: install_helm
vars:
helm_version: "{{ helm_oci_version }}"
- name: Create temporary directory to hold the chart
ansible.builtin.tempfile:
state: directory
suffix: .chart
register: _tmpd
- name: Copy the test chart
ansible.builtin.copy:
src: "{{ helm_oci_chart_name }}"
dest: "{{ _tmpd.path }}/"
- name: Log into the helm registry
ansible.builtin.command: >-
{{ helm_binary }} registry login --plain-http
-u {{ helm_oci_registry_username }} -p {{ helm_oci_registry_password }}
{{ helm_oci_registry }}
- name: Package and push both chart versions
ansible.builtin.command: "{{ item }}"
loop:
- >-
{{ helm_binary }} package {{ _tmpd.path }}/{{ helm_oci_chart_name }}
--version {{ helm_oci_chart_version }} --destination {{ _tmpd.path }}
- >-
{{ helm_binary }} package {{ _tmpd.path }}/{{ helm_oci_chart_name }}
--version {{ helm_oci_chart_version_plain }} --destination {{ _tmpd.path }}
- >-
{{ helm_binary }} push --plain-http
{{ _tmpd.path }}/{{ helm_oci_chart_name }}-{{ helm_oci_chart_version }}.tgz
oci://{{ helm_oci_registry }}/{{ helm_oci_repo_path }}
- >-
{{ helm_binary }} push --plain-http
{{ _tmpd.path }}/{{ helm_oci_chart_name }}-{{ helm_oci_chart_version_plain }}.tgz
oci://{{ helm_oci_registry }}/{{ helm_oci_repo_path }}
register: _push
- name: Ensure Helm stored the build metadata version with an underscore
ansible.builtin.assert:
that:
- "'1.0.0_build.1' in (_push.results[2].stdout + _push.results[2].stderr)"
fail_msg: >-
Expected Helm to rewrite '+' to '_' when pushing the chart tag. Without
that rewrite this target no longer covers the case it was written for.
# helm - the version with build metadata is the case that failed outright.
- name: Install the chart from the OCI registry
kubernetes.core.helm:
binary_path: "{{ helm_binary }}"
name: "{{ helm_oci_chart_name }}"
chart_ref: "{{ chart_ref }}"
chart_version: "{{ helm_oci_chart_version }}"
release_namespace: "{{ helm_oci_namespace }}"
create_namespace: true
plain_http: true
register: _install
- name: Ensure the release reports the chart version verbatim
ansible.builtin.assert:
that:
- _install is changed
- _install.status.chart == helm_oci_chart_name ~ '-' ~ helm_oci_chart_version
- name: Install the same chart again
kubernetes.core.helm:
binary_path: "{{ helm_binary }}"
name: "{{ helm_oci_chart_name }}"
chart_ref: "{{ chart_ref }}"
chart_version: "{{ helm_oci_chart_version }}"
release_namespace: "{{ helm_oci_namespace }}"
plain_http: true
register: _reinstall
- name: Ensure the module is idempotent
ansible.builtin.assert:
that:
- _reinstall is not changed
# helm_template - stdout is documented to hold only the rendered templates. Both
# chart versions are checked: the plain one covers the case where the progress
# messages are valid YAML and would otherwise be parsed as a manifest.
- name: Render the chart from the OCI registry
kubernetes.core.helm_template:
binary_path: "{{ helm_binary }}"
chart_ref: "{{ chart_ref }}"
chart_version: "{{ item }}"
release_name: "{{ helm_oci_chart_name }}"
plain_http: true
loop:
- "{{ helm_oci_chart_version }}"
- "{{ helm_oci_chart_version_plain }}"
register: _template
- name: Ensure stdout holds the rendered manifests and nothing else
ansible.builtin.assert:
that:
- "'Pulled:' not in item.stdout"
- "'Digest:' not in item.stdout"
- "'contains an underscore' not in item.stdout"
- item.stdout.startswith('---')
- (item.stdout | from_yaml_all | list | map(attribute='kind') | list) == ['ConfigMap']
fail_msg: "helm_template stdout was not only rendered manifests: {{ item.stdout[:200] }}"
loop: "{{ _template.results }}"
loop_control:
label: "{{ item.item }}"
always:
- name: Uninstall the release
kubernetes.core.helm:
binary_path: "{{ helm_binary }}"
name: "{{ helm_oci_chart_name }}"
release_namespace: "{{ helm_oci_namespace }}"
state: absent
when: helm_binary is defined
ignore_errors: true
- name: Remove the test namespace
kubernetes.core.k8s:
api_version: v1
kind: Namespace
name: "{{ helm_oci_namespace }}"
state: absent
wait: true
ignore_errors: true
- name: Log out of the helm registry
ansible.builtin.command: "{{ helm_binary }} registry logout {{ helm_oci_registry }}"
when: helm_binary is defined
ignore_errors: true
- name: Remove the temporary directory
ansible.builtin.file:
path: "{{ _tmpd.path }}"
state: absent
when: _tmpd is defined and _tmpd.path is defined
ignore_errors: true
@@ -0,0 +1 @@
redis*
@@ -0,0 +1,3 @@
helm_template
helm_pull
helm
@@ -0,0 +1,4 @@
[all]
helm-3.12.3 helm_version=v3.12.3 test_namespace=helm-plain-http-v3-12-3 tests_should_failed=true
helm-3.18.2 helm_version=v3.18.2 test_namespace=helm-plain-http-v3-18-2 tests_should_failed=false
helm-4.0.0 helm_version=v4.0.0 test_namespace=helm-plain-http-v4-0-0 tests_should_failed=false
@@ -0,0 +1,15 @@
- name: Run test for helm plain http option
hosts: all
gather_facts: true
strategy: free
vars:
ansible_connection: local
ansible_python_interpreter: "{{ ansible_playbook_python }}"
chart_test_oci: "oci://registry-1.docker.io/bitnamicharts/redis"
roles:
- role: setup_namespace
tasks:
- ansible.builtin.include_tasks: tasks/test.yaml
@@ -0,0 +1,95 @@
---
- name: Run test for helm
block:
- name: Create temporary directory to install chart In
ansible.builtin.tempfile:
state: directory
suffix: .helm
register: install_path
- name: Install required helm version
ansible.builtin.include_role:
name: install_helm
vars:
helm_install_path: "{{ install_path.path }}"
# helm
- name: Run helm with plain_http
kubernetes.core.helm:
binary_path: "{{ helm_binary }}"
chart_ref: "{{ chart_test_oci }}"
release_name: test-secure
release_namespace: "{{ test_namespace }}"
create_namespace: true
plain_http: true
register: install_chart
ignore_errors: true
- name: Ensure module failed as expected
ansible.builtin.assert:
that:
- install_chart is failed
- '"plain_http requires helm >= 3.13.0" in install_chart.msg'
when: tests_should_failed | bool
- name: Ensure the result command contains the expected option
ansible.builtin.assert:
that:
- install_chart is not failed
- '"--plain-http" in install_chart.command'
when: not (tests_should_failed | bool)
# helm_pull
- name: Trying to download helm chart with option plain_http
kubernetes.core.helm_pull:
chart_ref: "{{ chart_test_oci }}"
destination: "{{ playbook_dir }}"
binary_path: "{{ helm_binary }}"
plain_http: true
register: pull_chart
ignore_errors: true
- name: Ensure module failed as expected
ansible.builtin.assert:
that:
- pull_chart is failed
- '"plain_http requires helm >= 3.13.0" in pull_chart.msg'
when: tests_should_failed | bool
- name: Ensure the result command contains the expected option
ansible.builtin.assert:
that:
- pull_chart is not failed
- '"--plain-http" in pull_chart.command'
when: not (tests_should_failed | bool)
# helm_template
- name: Test helm render template
kubernetes.core.helm_template:
binary_path: "{{ helm_binary }}"
chart_ref: "{{ chart_test_oci }}"
output_dir: "{{ playbook_dir }}"
plain_http: true
register: template
ignore_errors: true
- name: Ensure module failed as expected
ansible.builtin.assert:
that:
- template is failed
- '"plain_http requires helm >= 3.13.0" in template.msg'
when: tests_should_failed | bool
- name: Ensure the result command contains the expected option
ansible.builtin.assert:
that:
- template is not failed
- '"--plain-http" in template.command'
when: not (tests_should_failed | bool)
always:
- name: Delete temporary file
ansible.builtin.file:
path: "{{ install_path.path }}"
state: absent
ignore_errors: true
+4
View File
@@ -0,0 +1,4 @@
#!/usr/bin/env bash
set -eux
export ANSIBLE_ROLES_PATH=../
ansible-playbook playbooks/play.yaml -i inventory.ini "$@"
@@ -1,3 +0,0 @@
---
dependencies:
- install_helm
@@ -1,165 +1,8 @@
---
- name: Install env plugin in check mode
helm_plugin:
binary_path: "{{ helm_binary }}"
state: present
plugin_path: https://github.com/adamreese/helm-env
register: check_install_env
check_mode: true
- assert:
that:
- check_install_env.changed
- name: Install env plugin
helm_plugin:
binary_path: "{{ helm_binary }}"
state: present
plugin_path: https://github.com/adamreese/helm-env
register: install_env
- assert:
that:
- install_env.changed
- name: Gather info about all plugin
helm_plugin_info:
binary_path: "{{ helm_binary }}"
register: plugin_info
- assert:
that:
- plugin_info.plugin_list is defined
- name: Install env plugin again
helm_plugin:
binary_path: "{{ helm_binary }}"
state: present
plugin_path: https://github.com/adamreese/helm-env
register: install_env
- assert:
that:
- not install_env.changed
- name: Uninstall env plugin in check mode
helm_plugin:
binary_path: "{{ helm_binary }}"
state: absent
plugin_name: env
register: check_uninstall_env
check_mode: true
- assert:
that:
- check_uninstall_env.changed
- name: Uninstall env plugin
helm_plugin:
binary_path: "{{ helm_binary }}"
state: absent
plugin_name: env
register: uninstall_env
- assert:
that:
- uninstall_env.changed
- name: Uninstall env plugin again
helm_plugin:
binary_path: "{{ helm_binary }}"
state: absent
plugin_name: env
register: uninstall_env
- assert:
that:
- not uninstall_env.changed
# https://github.com/ansible-collections/community.kubernetes/issues/399
- block:
- name: Copy required plugin files
copy:
src: "files/sample_plugin"
dest: "/tmp/helm_plugin_test/"
- name: Install sample_plugin from the directory
helm_plugin:
binary_path: "{{ helm_binary }}"
state: present
plugin_path: "/tmp/helm_plugin_test/sample_plugin"
register: sample_plugin_output
- name: Assert that sample_plugin is installed or not
assert:
that:
- sample_plugin_output.changed
- name: Gather Helm plugin info
helm_plugin_info:
binary_path: "{{ helm_binary }}"
register: r
- name: Set sample_plugin version
set_fact:
plugin_version: "{{ ( r.plugin_list | selectattr('name', 'equalto', plugin_name) | list )[0].version }}"
vars:
plugin_name: "sample_plugin"
- name: Assert if sample_plugin with multiline comment is installed
assert:
that:
- plugin_version == "0.0.1"
always:
- name: Uninstall sample_plugin
helm_plugin:
binary_path: "{{ helm_binary }}"
state: absent
plugin_name: sample_plugin
ignore_errors: yes
- block:
- name: uninstall helm plugin secrets
helm_plugin:
binary_path: "{{ helm_binary }}"
plugin_name: secrets
state: absent
- name: install helm-secrets on a specific version
helm_plugin:
binary_path: "{{ helm_binary }}"
plugin_path: https://github.com/jkroepke/helm-secrets
plugin_version: 3.4.1
state: present
- name: list helm plugin
helm_plugin_info:
plugin_name: secrets
binary_path: "{{ helm_binary }}"
register: plugin_list
- name: assert that secrets has been installed with specified version
assert:
that:
- plugin_list.plugin_list[0].version == "3.4.1"
- name: Update helm plugin version to latest
helm_plugin:
binary_path: "{{ helm_binary }}"
plugin_name: secrets
state: latest
register: _update
- name: assert update was performed
assert:
that:
- _update.changed
- '"Updated plugin: secrets" in _update.stdout'
always:
- name: Uninstall sample_plugin
helm_plugin:
binary_path: "{{ helm_binary }}"
state: absent
plugin_name: secrets
ignore_errors: yes
- name: Run tests
include_tasks: run_tests.yml
loop_control:
loop_var: helm_version
with_items:
- "v3.17.0"
- "v4.0.0"
@@ -0,0 +1,195 @@
---
- name: "Install {{ helm_version }}"
include_role:
name: install_helm
- block:
- name: Install env plugin in check mode
helm_plugin:
binary_path: "{{ helm_binary }}"
state: present
plugin_path: https://github.com/adamreese/helm-env
verify: false
register: check_install_env
check_mode: true
- assert:
that:
- check_install_env.changed
- name: Install env plugin
helm_plugin:
binary_path: "{{ helm_binary }}"
state: present
plugin_path: https://github.com/adamreese/helm-env
verify: false
register: install_env
- assert:
that:
- install_env.changed
- name: Gather info about all plugin
helm_plugin_info:
binary_path: "{{ helm_binary }}"
register: plugin_info
- assert:
that:
- plugin_info.plugin_list is defined
- name: Install env plugin again
helm_plugin:
binary_path: "{{ helm_binary }}"
state: present
plugin_path: https://github.com/adamreese/helm-env
verify: false
register: install_env
- assert:
that:
- not install_env.changed
- name: Uninstall env plugin in check mode
helm_plugin:
binary_path: "{{ helm_binary }}"
state: absent
plugin_name: env
verify: false
register: check_uninstall_env
check_mode: true
- assert:
that:
- check_uninstall_env.changed
- name: Uninstall env plugin
helm_plugin:
binary_path: "{{ helm_binary }}"
state: absent
plugin_name: env
register: uninstall_env
- assert:
that:
- uninstall_env.changed
- name: Uninstall env plugin again
helm_plugin:
binary_path: "{{ helm_binary }}"
state: absent
plugin_name: env
register: uninstall_env
- assert:
that:
- not uninstall_env.changed
always:
- name: Uninstall env plugin
helm_plugin:
binary_path: "{{ helm_binary }}"
state: absent
plugin_name: env
# https://github.com/ansible-collections/community.kubernetes/issues/399
- block:
- name: Copy required plugin files
copy:
src: "files/sample_plugin"
dest: "/tmp/helm_plugin_test/"
- name: Install sample_plugin from the directory
helm_plugin:
binary_path: "{{ helm_binary }}"
state: present
plugin_path: "/tmp/helm_plugin_test/sample_plugin"
register: sample_plugin_output
- name: Assert that sample_plugin is installed or not
assert:
that:
- sample_plugin_output.changed
- name: Gather Helm plugin info
helm_plugin_info:
binary_path: "{{ helm_binary }}"
register: r
- name: Set sample_plugin version
set_fact:
plugin_version: "{{ ( r.plugin_list | selectattr('name', 'equalto', plugin_name) | list )[0].version }}"
vars:
plugin_name: "sample_plugin"
- name: Assert if sample_plugin with multiline comment is installed
assert:
that:
- plugin_version == "0.0.1"
always:
- name: Uninstall sample_plugin
helm_plugin:
binary_path: "{{ helm_binary }}"
state: absent
plugin_name: sample_plugin
ignore_errors: true
- block:
- name: uninstall helm plugin unittest
helm_plugin:
binary_path: "{{ helm_binary }}"
plugin_name: unittest
state: absent
- name: install helm-unittest on a specific version
helm_plugin:
binary_path: "{{ helm_binary }}"
plugin_path: https://github.com/helm-unittest/helm-unittest
plugin_version: v1.0.1
verify: false
state: present
- name: list helm plugin
helm_plugin_info:
plugin_name: unittest
binary_path: "{{ helm_binary }}"
register: plugin_list
- name: assert that unittest has been installed with specified version
assert:
that:
- plugin_list.plugin_list[0].version == "1.0.1"
- name: Update helm plugin version to latest (check mode)
helm_plugin:
binary_path: "{{ helm_binary }}"
plugin_name: unittest
state: latest
register: _update_checkmode
check_mode: true
- name: Assert that module reported change while running in check mode
assert:
that:
- _update_checkmode.changed
- '"Updated plugin: unittest" not in _update_checkmode.stdout'
- name: Update helm plugin version to latest
helm_plugin:
binary_path: "{{ helm_binary }}"
plugin_name: unittest
state: latest
register: _update
- name: assert update was performed
assert:
that:
- _update.changed
- '"Updated plugin: unittest" in _update.stdout'
always:
- name: Uninstall sample_plugin
helm_plugin:
binary_path: "{{ helm_binary }}"
state: absent
plugin_name: unittest
@@ -5,7 +5,7 @@
- 3.8.0
- 3.1.0
- 3.0.0
- 2.3.0
- 4.0.0
- block:
- name: Create temp directory for helm tests
@@ -20,37 +20,13 @@
- set_fact:
destination: "{{ temp_dir }}"
- name: Create Helm directories
file:
state: directory
path: "{{ temp_dir }}/{{ item }}"
with_items: "{{ helm_versions }}"
- name: Unarchive Helm binary
unarchive:
src: "https://get.helm.sh/helm-v{{ item }}-linux-amd64.tar.gz"
dest: "{{ temp_dir }}/{{ item }}"
remote_src: yes
with_items: "{{ helm_versions }}"
# Testing helm pull with helm version == 2.3.0
- block:
- name: Assert that helm pull failed with helm <= 3.0.0
helm_pull:
binary_path: "{{ helm_path }}"
chart_ref: https://github.com/grafana/helm-charts/releases/download/grafana-5.6.0/grafana-5.6.0.tgz
destination: "{{ destination }}"
ignore_errors: true
register: _result
- name: assert that module failed with proper message
assert:
that:
- _result is failed
- _result.msg == "Helm version must be >=3.0.0,<4.0.0, current version is 2.3.0"
- name: Install Helm versions
ansible.builtin.include_role:
name: install_helm
loop: "{{ helm_versions }}"
vars:
helm_path: "{{ temp_dir }}/2.3.0/linux-amd64/helm"
helm_version: "v{{ item }}"
helm_install_path: "{{ temp_dir }}/{{ item }}"
# Testing helm pull with helm version == 3.0.0
- block:
@@ -103,7 +79,7 @@
- _result.msg == "Parameter chart_ca_cert requires helm >= 3.1.0, current version is 3.0.0"
vars:
helm_path: "{{ temp_dir }}/3.0.0/linux-amd64/helm"
helm_path: "{{ temp_dir }}/3.0.0/helm"
# Testing helm pull with helm version == 3.1.0
- block:
@@ -143,7 +119,7 @@
- _result.msg == "Parameter skip_tls_certs_check requires helm >= 3.3.0, current version is 3.1.0"
vars:
helm_path: "{{ temp_dir }}/3.1.0/linux-amd64/helm"
helm_path: "{{ temp_dir }}/3.1.0/helm"
# Testing helm pull with helm version == 3.8.0
- block:
@@ -317,7 +293,7 @@
- _chart_after_force.stat.isdir
vars:
helm_path: "{{ temp_dir }}/3.8.0/linux-amd64/helm"
helm_path: "{{ temp_dir }}/3.8.0/helm"
always:
@@ -4,9 +4,10 @@
username: testuser
password: testpassword
wrong_password: 'WrongPassword'
# Use the helm binary installed by the install_helm role rather than the one
# shipped with the CI image, whose version is outside of our control.
helm_binary: "/tmp/helm/{{ ansible_system | lower }}-amd64/helm"
registry_name: oci_registry
registry_port: 5000
registry_port: 5002
test_chart: https://github.com/grafana/helm-charts/releases/download/k8s-monitoring-1.6.8/k8s-monitoring-1.6.8.tgz
helm_versions:
- v3.17.0
- v3.20.0
- v4.0.0

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