Compare commits

..

44 Commits

Author SHA1 Message Date
patchback[bot]
96464f1ea8 Rebase PR #898 (#905) (#912)
This is a backport of PR #905 as merged into main (d329e7e).
This PR is a rebase of #898 for CI to pass
Thanks @efussi for your collaboration.
Closes #892

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
Reviewed-by: Bikouo Aubin
2025-05-02 18:37:25 +00:00
Bikouo Aubin
fe4858d556 Run integration tests using ansible-core 2.19 (#888) (#924)
* fix integration test ``k8s_full`` running with ansible-core 2.19

* Fix templating issues

* fix test on current ansible version

* fix tests cases

* Fix additional tests

* fix the templating mechanism

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

* Remove support for omit into template option

* Remove unnecessary unit tests

(cherry picked from commit 2cb5d6c316)
2025-05-02 17:16:51 +02:00
patchback[bot]
07e8a76f2d Update ansible-lint version to 25.1.2 (#919) (#920)
This is a backport of PR #919 as merged into main (b594d35).
Update ansible-lint version to 25.1.2

Reviewed-by: Bianca Henderson <beeankha@gmail.com>
2025-04-29 18:03:24 +00:00
Bianca Henderson
0488b79f0f Bugfix: fix unit-source for pre-release of ansible-core 2.20 (devel and milestone branch) (#903) (#911)
This is a backport of PR #903 as merged into main (d4fc22c).
SUMMARY
CI fix for #904
ISSUE TYPE

Bugfix Pull Request

COMPONENT NAME
tests/unit
ADDITIONAL INFORMATION

Reviewed-by: Bikouo Aubin
2025-04-25 15:18:53 +00:00
Bikouo Aubin
4fa6465f3e Release 3.3.1 (#890)
Release 3.3.1

Update galaxy.yml
Update changelog/changelog.yaml and CHANGELOG.rst

Reviewed-by: Yuriy Novostavskiy
Reviewed-by: Mike Graves <mgraves@redhat.com>
Reviewed-by: Alina Buzachis
2025-03-28 06:57:22 +00:00
Yuriy Novostavskiy
e1b341d9be Cherry-pick to stable-3: Fix linters in CI (#873) (#877)
SUMMARY
It seems that recent updates in linters break CI. Closes #874 ISSUE TYPE
Bugfix Pull Request
COMPONENT NAME
CI
ADDITIONAL INFORMATION
It's cherry-pick #873 to stable-3 as patch bot failed
Reviewed-by: Mike Graves mgraves@redhat.com
Reviewed-by: Yuriy Novostavskiy

Reviewed-by: Mike Graves <mgraves@redhat.com>
2025-02-06 19:17:04 +00:00
Yuriy Novostavskiy
8feb564b4d prepare release 3.3.0 (#863)
SUMMARY
Version 3.3.0 of ansible-collection kubernetes.core came with several improvements and bugfixes
ISSUE TYPE

New release pull request

Changelog
Minor Changes

k8s_drain - Improve error message for pod disruption budget when draining a node (#797).

Bugfixes

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

ADDITIONAL INFORMATION
Collection kubernets.core version 3.3.0 is compatible with ansible-core>=2.14.0

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

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

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

Docs Pull Request

COMPONENT NAME

helm
k8s
8s_info


ADDITIONAL INFORMATION
PR to be backported to stable-3 and stable-5
2025-01-17 18:54:26 +00:00
patchback[bot]
19b2efd0dd Remove deprecated .github/stale.yml to address #837 (#838) (#859)
This is a backport of PR #838 as merged into main (eb731cd).
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
2025-01-17 16:51:18 +00:00
patchback[bot]
1c3bf95b74 helm_pull: Silence false no_log warning (#796) (#857)
This is a backport of PR #796 as merged into main (ecc64ca).
SUMMARY
Apply no_log=True to pass_credentials to silence false positive warning.
Fixes similar issue to: #423
ISSUE TYPE

Bugfix Pull Request

COMPONENT NAME
changelog/fragements/796-false-positive-helmull.yaml
plugins/modules/helm_pull.py
2025-01-17 16:19:38 +00:00
Yuriy Novostavskiy
018c92429b Backport "fix linters in github actions (#848)" to stable-3 (#850)
Fix bug #846
within this commit ansible/ansible-lint updated to 24.12.2 and config moved to .config folder
(cherry picked from commit 159a63a)
This is cherry-pic of #848 as patchback failed here

Reviewed-by: Mike Graves <mgraves@redhat.com>
2025-01-17 15:52:54 +00:00
patchback[bot]
9267e03538 Clean up test namespace (#852) (#853)
This is a backport of PR #852 as merged into main (9f60b15).
SUMMARY

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

ISSUE TYPE


Bugfix Pull Request

COMPONENT NAME

ADDITIONAL INFORMATION
2025-01-17 15:29:19 +00:00
Yuriy Novostavskiy
eb3ab99709 Backport to Stable-3: Fix helm tests (#827) and Fix helm integration tests (#830) (#829)
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
SUMMARY


ISSUE TYPE


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

COMPONENT NAME


This is a backport of PR #830 as merged into main (7559b65).
SUMMARY
Fix charts ref on integration tests targets
ISSUE TYPE
Bugfix Pull Request

Reviewed-by: Mike Graves <mgraves@redhat.com>
2025-01-16 19:03:45 +00:00
patchback[bot]
a1ac6b99dc Remove kubeconfig value from module invocation log (#826) (#839)
(cherry picked from commit 6efabd3418)

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>
2024-12-19 12:06:45 +01:00
Yuriy Novostavskiy
4ad57fdb6c Cherry-pic to stable-3: Update Readme to match the template (#767) (#822)
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
(cherry picked from commit fdb8af7)
SUMMARY


ISSUE TYPE


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

COMPONENT NAME

ADDITIONAL INFORMATION

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


ISSUE TYPE


Bugfix Pull Request

COMPONENT NAME

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


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

ISSUE TYPE


Feature Pull Request

COMPONENT NAME
k8s_drain
2024-12-11 15:14:46 +00:00
patchback[bot]
c6bd8ab453 Fix k8s_drain runs into timeout with pods from stateful sets. (#793) (#807)
This is a backport of PR #793 as merged into main (fca0dc0).
SUMMARY
Fixes #792 .
The function wait_for_pod_deletion in k8s_drain never checks on which node a pod is actually running:
            try:
                response = self._api_instance.read_namespaced_pod(
                    namespace=pod[0], name=pod[1]
                )
                if not response:
                    pod = None
                time.sleep(wait_sleep)
This means that if a pod is successfully evicted and restarted with the same name on a new node, k8s_drain does not notice and thinks that the original pod is still running. This is the case for pods which are part of a stateful set.

ISSUE TYPE


Bugfix Pull Request

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

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

ISSUE TYPE


Bugfix Pull Request


COMPONENT NAME

ADDITIONAL INFORMATION

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

Bugfix Pull Request

COMPONENT NAME
GitHub actions/test

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

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

Fixes #639
ISSUE TYPE


Bugfix Pull Request

COMPONENT NAME

kustomize lookup plugin
ADDITIONAL INFORMATION

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

Bugfix Pull Request

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



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

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

Reviewed-by: Mike Graves <mgraves@redhat.com>
2024-07-10 14:32:08 +00:00
patchback[bot]
5c748bd4e9 Merge pull request #757 from gravesm/gha-python-version (#758)
This is a backport of PR #757 as merged into main (44a2fc3).
SUMMARY

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.

ISSUE TYPE


Bugfix Pull Request

COMPONENT NAME

ADDITIONAL INFORMATION

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

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


Bugfix Pull Request

COMPONENT NAME
helm
helm_pull
ADDITIONAL INFORMATION

Reviewed-by: Mike Graves <mgraves@redhat.com>
2024-06-18 13:05:53 +00:00
Yuriy Novostavskiy
615d3d8bd0 Prepare release 3.2.0 (#746)
SUMMARY
Prepare version 3.2.0
ISSUE TYPE

New Version Pull Request

ADDITIONAL INFORMATION
The current version of a major Ansible (Ansible 10) includes a collection version 3.1.0, meaning that the minor version (i.e. Ansible 10.1) will pick versions from the stable-3 branch. Hence, a recent documentation update will not be in Ansible and Ansible documentation site/kubernetes.core collection chapter until a new minor version released from stable-3 branch.
This PR also includes changes in README.md and Makefile that were missed in 3.1.0

Reviewed-by: Mike Graves <mgraves@redhat.com>
2024-06-14 15:31:50 +00:00
patchback[bot]
4854d7fbd9 Doc: add example of using kubectl connection plugin (#741) (#743)
[PR #741/fb80d973 backport][stable-3] Doc: add example of using kubectl connection plugin

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

Docs Pull Request

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

Reviewed-by: Yuriy Novostavskiy
Reviewed-by: Mike Graves <mgraves@redhat.com>
2024-06-06 14:28:18 +00:00
patchback[bot]
baa59f388c Defer removal of inventory/k8s to 6.0.0 (#734) (#738)
Defer removal of inventory/k8s to 6.0.0

SUMMARY
Defer removal of inventory plugin k8s to release 6.0.0.

ISSUE TYPE

Feature Pull Request

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

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>
2024-05-31 09:59:45 +02:00
patchback[bot]
e071ae73b6 kubevirt.core collection cross testing (#731) (#735)
* Initial

* update python version

* update python version

* checkout local version of collection

* add integration job

* indent

* Set workflow as non blocking

(cherry picked from commit c0666a5137)

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>
2024-05-31 09:46:31 +02:00
patchback[bot]
00cb40094a Defer removal of k8s inventory plugin to version 5.0. (#723) (#724)
[PR #723/cbadbe32 backport][stable-3] Defer removal of k8s inventory plugin to version 5.0.

This is a backport of PR #723 as merged into main (cbadbe3).
SUMMARY

Defer removal of k8s inventory plugin to version 5.0.

ISSUE TYPE


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

COMPONENT NAME

inventory/k8s.py
ADDITIONAL INFORMATION

Reviewed-by: Alina Buzachis
2024-05-22 11:56:29 +00:00
Mike Graves
ef829b8a56 Release 3.1.0 (#719)
Release 3.1.0

SUMMARY

Release prep for 3.1.0

ISSUE TYPE


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

COMPONENT NAME

ADDITIONAL INFORMATION

Reviewed-by: Alina Buzachis
Reviewed-by: Helen Bailey <hebailey@redhat.com>
2024-05-16 14:15:47 +00:00
patchback[bot]
d86a652c36 Update deprecation version for merge_type=json (#700) (#718)
[PR #700/a4c1bd85 backport][stable-3] Update deprecation version for merge_type=json

This is a backport of PR #700 as merged into main (a4c1bd8).
SUMMARY
When looking at the parts of plugins/module_utils/common.py and plugins/module_utils/k8s/service.py during the post 3.0.0 release (see https://github.com/ansible-collections/kubernetes.core/pull/663/files#diff-9ee2d0860a5643da4e1f35136e9e7c3a41c5f2fd2952c197e7e32b941e5a301c) that affect merge_type when set to json, I don't believe merge_type=json was deprecated for (and removed from) the k8s module, and instead the deprecation version has moved to 4.0.0. Hence, the documentation update.
ISSUE TYPE

Docs Pull Request

COMPONENT NAME
k8s module

Reviewed-by: Mike Graves <mgraves@redhat.com>
2024-05-15 18:57:45 +00:00
patchback[bot]
a4242f0131 minor: doc: use the same style of version_added across repo (#703) (#715)
[PR #703/63607630 backport][stable-3] minor(doc): use the same style of version_added across repo

This is a backport of PR #703 as merged into main (6360763).
SUMMARY
Currently is no single style of version_added, in some places it's unquoted, somewhere single quote is used, in another places it's double quoted. Moreover, some file had different styles in one single file.
The aim of this PR is to update whole repo to single style for version_added
ISSUE TYPE

Docs Pull Request

COMPONENT NAME
kustomize
helm
helm_info
helm_plugin
helm_plugin_info
helm_pull
helm_repository
helm_template
k8s_cluster_info
k8s_cp
k8s_drain
k8s_exec
k8s_log
k8s_rollback
k8s_taint
ADDITIONAL INFORMATION
The same style is proposed as used in amazon.aws collections

Reviewed-by: Mike Graves <mgraves@redhat.com>
2024-05-15 15:10:34 +00:00
Mike Graves
d75e9a0fa3 Fix unsafe text assertion in tests (#716) (#717)
[Manual backport/stable-3] Fix unsafe text assertion in tests (#716)

Fix unsafe text assertion in tests
SUMMARY
This fixes a problem with unsafe text in an assertion.
ISSUE TYPE
Bugfix Pull Request
COMPONENT NAME
ADDITIONAL INFORMATION
Reviewed-by: GomathiselviS
Reviewed-by: Bikouo Aubin
(cherry picked from commit 8858b19)
2024-05-15 14:35:14 +00:00
patchback[bot]
5044cfc030 fixed typo in filename of 'k8s_json_patch'-action (#652) (#714)
[PR #652/ac943e98 backport][stable-3] fixed typo in filename of 'k8s_json_patch'-action 

This is a backport of PR #652 as merged into main (ac943e9).
SUMMARY

The filename/symlink of the action for the 'k8s_json_patch'-module was wrong. Renamed file from 'ks8_json_patch.py' to ' k8s_json_patch.py'

ISSUE TYPE

Bugfix Pull Request

COMPONENT NAME

k8s_json_patch
ADDITIONAL INFORMATION


Because of the wrong filename things like unvaulting kubeconfig files did not worked.

Reviewed-by: Mike Graves <mgraves@redhat.com>
2024-05-14 17:07:48 +00:00
patchback[bot]
ddd7e79a12 Update kustomize.py add --enable-helm support (#592) (#712)
[PR #592/0408aa93 backport][stable-3] Update kustomize.py add --enable-helm support

This is a backport of PR #592 as merged into main (0408aa9).
Add --enable-helm support
SUMMARY
Fixes #568
ISSUE TYPE

Feature Pull Request

COMPONENT NAME
Lookup plugin: kubernetes.core.kustomize
ADDITIONAL INFORMATION
Current and maintained arg:
lookup('kubernetes.core.kustomize', dir=item)

Additional feature args:
lookup('kubernetes.core.kustomize', dir=item, enable_helm=false)
lookup('kubernetes.core.kustomize', dir=item, enable_helm=true)

Reviewed-by: Mike Graves <mgraves@redhat.com>
2024-05-13 17:58:34 +00:00
patchback[bot]
edc979ff11 add support of kubectl_local_env_vars (#698) (#702) (#705)
[PR #702/fb25ff44 backport][stable-3] add support of kubectl_local_env_vars (#698)

This is a backport of PR #702 as merged into main (fb25ff4).
SUMMARY
Support of local environmental variable that may be required to be set on Ansible Controller before the connection is set and may be used for kubectl command. This PR addressed for #698
The main idea is to have the support of  additional/extra local environmental variable that may be required for kubectl itself, i.e. for authorization in case of public clouds
ISSUE TYPE

Feature Pull Request

COMPONENT NAME
kubernetes.core.kubectl connection plugin
ADDITIONAL INFORMATION
This PR attempts to implement local env support for the kubectl connection plugin that may be useful in case of using kubectl against public cloud kubernetes environment that uses some authorization (i.e. aws cli) additionally to kubeconfig file. More detail in #698
The output that shows that the connection plugin can use local environment variable for kubectl command (with some debug that used during development but removed then):
root@ubuntu-shell:/# cat test.yaml
- hosts: localhost
  gather_facts: no
  any_errors_fatal: yes
  vars:
    ansible_connection: "kubectl"
    ansible_kubectl_namespace: "test"
    ansible_kubectl_config: "/.kube/config"
    ansible_kubectl_pod: "ubuntu"
    ansible_kubectl_container: "ubuntu"
    ansible_kubectl_local_env_vars:
      TESTVAR1: "test"
      TESTVAR2: "test"
      TESTVAR3: "test"
  environment:
    TEST_ENV1: value1
    TEST_ENV2: value2

  tasks:
  - name: test
    ansible.builtin.shell: env
    register: result
  - debug:
      var: result.stdout_lines
root@ubuntu-shell:/# ansible-playbook test.yaml
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'

PLAY [localhost] **************************************************************************************************************************************

TASK [test] *******************************************************************************************************************************************
changed: [localhost]

TASK [debug] ******************************************************************************************************************************************
ok: [localhost] => {
    "result.stdout_lines": [
        "KUBERNETES_PORT=tcp://10.96.0.1:443",
        "KUBERNETES_SERVICE_PORT=443",
        "HOSTNAME=ubuntu",
        "HOME=/root",
        "LC_CTYPE=C.UTF-8",
        "TEST_ENV1=value1",
        "TEST_ENV2=value2",
        "TERM=xterm",
        "KUBERNETES_PORT_443_TCP_ADDR=10.96.0.1",
        "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
        "KUBERNETES_PORT_443_TCP_PORT=443",
        "KUBERNETES_PORT_443_TCP_PROTO=tcp",
        "KUBERNETES_SERVICE_PORT_HTTPS=443",
        "KUBERNETES_PORT_443_TCP=tcp://10.96.0.1:443",
        "KUBERNETES_SERVICE_HOST=10.96.0.1",
        "PWD=/"
    ]
}

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

root@ubuntu-shell:/# ansible-playbook test.yaml -vvv
ansible-playbook [core 2.14.5]
  config file = None
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/local/lib/python3.10/dist-packages/ansible
  ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
  executable location = /usr/local/bin/ansible-playbook
  python version = 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] (/usr/bin/python3)
  jinja version = 3.1.3
  libyaml = True
No config file found; using defaults
host_list declined parsing /etc/ansible/hosts as it did not pass its verify_file() method
Skipping due to inventory source not existing or not being readable by the current user
script declined parsing /etc/ansible/hosts as it did not pass its verify_file() method
auto declined parsing /etc/ansible/hosts as it did not pass its verify_file() method
Skipping due to inventory source not existing or not being readable by the current user
yaml declined parsing /etc/ansible/hosts as it did not pass its verify_file() method
Skipping due to inventory source not existing or not being readable by the current user
ini declined parsing /etc/ansible/hosts as it did not pass its verify_file() method
Skipping due to inventory source not existing or not being readable by the current user
toml declined parsing /etc/ansible/hosts as it did not pass its verify_file() method
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'
Skipping callback 'default', as we already have a stdout callback.
Skipping callback 'minimal', as we already have a stdout callback.
Skipping callback 'oneline', as we already have a stdout callback.

PLAYBOOK: test.yaml ***********************************************************************************************************************************
1 plays in test.yaml

PLAY [localhost] **************************************************************************************************************************************

TASK [test] *******************************************************************************************************************************************
task path: /test.yaml:19
redirecting (type: connection) ansible.builtin.kubectl to kubernetes.core.kubectl
<127.0.0.1> ESTABLISH kubectl CONNECTION
<127.0.0.1> ENV: KUBERNETES_SERVICE_PORT_HTTPS=443
<127.0.0.1> ENV: KUBERNETES_SERVICE_PORT=443
<127.0.0.1> ENV: HOSTNAME=ubuntu-shell
<127.0.0.1> ENV: PWD=/
<127.0.0.1> ENV: HOME=/root
<127.0.0.1> ENV: KUBERNETES_PORT_443_TCP=tcp://10.96.0.1:443
<127.0.0.1> ENV: LS_COLORS=rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.zst=01;31:*.tzst=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.wim=01;31:*.swm=01;31:*.dwm=01;31:*.esd=01;31:*.jpg=01;35:*.jpeg=01;35:*.mjpg=01;35:*.mjpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.webp=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:
<127.0.0.1> ENV: TERM=xterm
<127.0.0.1> ENV: SHLVL=1
<127.0.0.1> ENV: KUBERNETES_PORT_443_TCP_PROTO=tcp
<127.0.0.1> ENV: KUBERNETES_PORT_443_TCP_ADDR=10.96.0.1
<127.0.0.1> ENV: KUBERNETES_SERVICE_HOST=10.96.0.1
<127.0.0.1> ENV: KUBERNETES_PORT=tcp://10.96.0.1:443
<127.0.0.1> ENV: KUBERNETES_PORT_443_TCP_PORT=443
<127.0.0.1> ENV: PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
<127.0.0.1> ENV: _=/usr/local/bin/ansible-playbook
<127.0.0.1> ENV: LC_CTYPE=C.UTF-8
<127.0.0.1> ENV: TESTVAR1=test
<127.0.0.1> ENV: TESTVAR2=test
<127.0.0.1> ENV: TESTVAR3=test
<127.0.0.1> EXEC ['/usr/local/bin/kubectl', '-n', 'test', '--kubeconfig', '/.kube/config', 'exec', '-i', 'ubuntu', '-c', 'ubuntu', '--', '/bin/sh', '-c', "/bin/sh -c 'echo ~ && sleep 0'"]
<127.0.0.1> EXEC ['/usr/local/bin/kubectl', '-n', 'test', '--kubeconfig', '/.kube/config', 'exec', '-i', 'ubuntu', '-c', 'ubuntu', '--', '/bin/sh', '-c', '/bin/sh -c \'( umask 77 && mkdir -p "` echo /root/.ansible/tmp `"&& mkdir "` echo /root/.ansible/tmp/ansible-tmp-1713785852.548581-6866-69007595335133 `" && echo ansible-tmp-1713785852.548581-6866-69007595335133="` echo /root/.ansible/tmp/ansible-tmp-1713785852.548581-6866-69007595335133 `" ) && sleep 0\'']
Using module file /usr/local/lib/python3.10/dist-packages/ansible/modules/command.py
<127.0.0.1> PUT /root/.ansible/tmp/ansible-local-6862s5_lr_wb/tmpxwmx0qeh TO /root/.ansible/tmp/ansible-tmp-1713785852.548581-6866-69007595335133/AnsiballZ_command.py
<127.0.0.1> EXEC ['/usr/local/bin/kubectl', '-n', 'test', '--kubeconfig', '/.kube/config', 'exec', '-i', 'ubuntu', '-c', 'ubuntu', '--', '/bin/sh', '-c', "/bin/sh -c 'chmod u+x /root/.ansible/tmp/ansible-tmp-1713785852.548581-6866-69007595335133/ /root/.ansible/tmp/ansible-tmp-1713785852.548581-6866-69007595335133/AnsiballZ_command.py && sleep 0'"]
<127.0.0.1> EXEC ['/usr/local/bin/kubectl', '-n', 'test', '--kubeconfig', '/.kube/config', 'exec', '-i', 'ubuntu', '-c', 'ubuntu', '--', '/bin/sh', '-c', "/bin/sh -c 'TEST_ENV1=value1 TEST_ENV2=value2 /usr/bin/python3 /root/.ansible/tmp/ansible-tmp-1713785852.548581-6866-69007595335133/AnsiballZ_command.py && sleep 0'"]
<127.0.0.1> EXEC ['/usr/local/bin/kubectl', '-n', 'test', '--kubeconfig', '/.kube/config', 'exec', '-i', 'ubuntu', '-c', 'ubuntu', '--', '/bin/sh', '-c', "/bin/sh -c 'rm -f -r /root/.ansible/tmp/ansible-tmp-1713785852.548581-6866-69007595335133/ > /dev/null 2>&1 && sleep 0'"]
changed: [localhost] => {
    "changed": true,
    "cmd": "env",
    "delta": "0:00:00.005088",
    "end": "2024-04-22 11:37:33.655340",
    "invocation": {
        "module_args": {
            "_raw_params": "env",
            "_uses_shell": true,
            "argv": null,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "stdin": null,
            "stdin_add_newline": true,
            "strip_empty_ends": true
        }
    },
    "msg": "",
    "rc": 0,
    "start": "2024-04-22 11:37:33.650252",
    "stderr": "",
    "stderr_lines": [],
    "stdout": "KUBERNETES_PORT=tcp://10.96.0.1:443\nKUBERNETES_SERVICE_PORT=443\nHOSTNAME=ubuntu\nHOME=/root\nLC_CTYPE=C.UTF-8\nTEST_ENV1=value1\nTEST_ENV2=value2\nTERM=xterm\nKUBERNETES_PORT_443_TCP_ADDR=10.96.0.1\nPATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\nKUBERNETES_PORT_443_TCP_PORT=443\nKUBERNETES_PORT_443_TCP_PROTO=tcp\nKUBERNETES_SERVICE_PORT_HTTPS=443\nKUBERNETES_PORT_443_TCP=tcp://10.96.0.1:443\nKUBERNETES_SERVICE_HOST=10.96.0.1\nPWD=/",
    "stdout_lines": [
        "KUBERNETES_PORT=tcp://10.96.0.1:443",
        "KUBERNETES_SERVICE_PORT=443",
        "HOSTNAME=ubuntu",
        "HOME=/root",
        "LC_CTYPE=C.UTF-8",
        "TEST_ENV1=value1",
        "TEST_ENV2=value2",
        "TERM=xterm",
        "KUBERNETES_PORT_443_TCP_ADDR=10.96.0.1",
        "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
        "KUBERNETES_PORT_443_TCP_PORT=443",
        "KUBERNETES_PORT_443_TCP_PROTO=tcp",
        "KUBERNETES_SERVICE_PORT_HTTPS=443",
        "KUBERNETES_PORT_443_TCP=tcp://10.96.0.1:443",
        "KUBERNETES_SERVICE_HOST=10.96.0.1",
        "PWD=/"
    ]
}

TASK [debug] ******************************************************************************************************************************************
task path: /test.yaml:22
redirecting (type: connection) ansible.builtin.kubectl to kubernetes.core.kubectl
ok: [localhost] => {
    "result.stdout_lines": [
        "KUBERNETES_PORT=tcp://10.96.0.1:443",
        "KUBERNETES_SERVICE_PORT=443",
        "HOSTNAME=ubuntu",
        "HOME=/root",
        "LC_CTYPE=C.UTF-8",
        "TEST_ENV1=value1",
        "TEST_ENV2=value2",
        "TERM=xterm",
        "KUBERNETES_PORT_443_TCP_ADDR=10.96.0.1",
        "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
        "KUBERNETES_PORT_443_TCP_PORT=443",
        "KUBERNETES_PORT_443_TCP_PROTO=tcp",
        "KUBERNETES_SERVICE_PORT_HTTPS=443",
        "KUBERNETES_PORT_443_TCP=tcp://10.96.0.1:443",
        "KUBERNETES_SERVICE_HOST=10.96.0.1",
        "PWD=/"
    ]
}

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

root@ubuntu-shell:/#

Reviewed-by: Mike Graves <mgraves@redhat.com>
2024-05-08 19:53:12 +00:00
patchback[bot]
37c1f911cb Add tests/sanity/ignore-2.18.txt (#704) (#706)
[PR #704/86d9a3f4 backport][stable-3] Add tests/sanity/ignore-2.18.txt

This is a backport of PR #704 as merged into main (86d9a3f).
SUMMARY

Add tests/sanity/ignore-2.18.txt

ISSUE TYPE


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

COMPONENT NAME

ADDITIONAL INFORMATION
2024-05-08 19:00:55 +00:00
patchback[bot]
80a5bf623a Merge pull request #707 from gravesm/linting-fix (#708)
[PR #707/874fbfed backport][stable-3] Update ansible-lint GHA

This is a backport of PR #707 as merged into main (874fbfe).
SUMMARY

There seems to be a bug in older versions of ansible-lint where pinning to a version for the GHA still installs the main branch.
See ansible/ansible-lint#3762 for more info.

ISSUE TYPE


Bugfix Pull Request

COMPONENT NAME

ADDITIONAL INFORMATION

Reviewed-by: Mike Graves <mgraves@redhat.com>
2024-05-08 15:32:59 +00:00
patchback[bot]
8f653558f6 helm - expand kubeconfig path with user's home dir (#654) (#695)
[PR #654/9f7c865c backport][stable-3] helm - expand kubeconfig path with user's home dir

This is a backport of PR #654 as merged into main (9f7c865).
SUMMARY

Currently the helm module fails when providing the default kubeconfig path explicitly, while the same path is fine for the k8s module.

ISSUE TYPE


Bugfix Pull Request

COMPONENT NAME

helm
ADDITIONAL INFORMATION



- name: Deploy kubelet-csr-approver
  delegate_to: client
  run_once: true
  kubernetes.core.helm:
    update_repo_cache: true
    kubeconfig: "~/.kube/config"
    state: present
    name: kubelet-csr-approver
    namespace: kubelet-csr-approver
    create_namespace: true
    chart_ref: kubelet-csr-approver/kubelet-csr-approver
    chart_version: 1.0.5
    values: "{{ lookup('template', 'values.yaml.j2') | from_yaml }}"
    atomic: true

Before change:
TASK [kubernetes/kubelet_csr_approver : Deploy kubelet-csr-approver] ***
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: FileNotFoundError: [Errno 2] No such file or directory: '~/.kube/config'
fatal: [node-1 -> client(192.168.121.56)]: FAILED! => {"changed": false, "module_stderr": "", "module_stdout": "Traceback (most recent call last):\r\n  File \"/home/vagrant/.ansible/tmp/ansible-tmp-1697293347.7135417-118207-9805169252135/AnsiballZ_helm.py\", line 107, in <module>\r\n    _ansiballz_main()\r\n  File \"/home/vagrant/.ansible/tmp/ansible-tmp-1697293347.7135417-118207-9805169252135/AnsiballZ_helm.py\", line 99, in _ansiballz_main\r\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\r\n  File \"/home/vagrant/.ansible/tmp/ansible-tmp-1697293347.7135417-118207-9805169252135/AnsiballZ_helm.py\", line 47, in invoke_module\r\n    runpy.run_module(mod_name='ansible_collections.kubernetes.core.plugins.modules.helm', init_globals=dict(_module_fqn='ansible_collections.kubernetes.core.plugins.modules.helm', _modlib_path=modlib_path),\r\n  File \"/usr/lib/python3.10/runpy.py\", line 224, in run_module\r\n    return _run_module_code(code, init_globals, run_name, mod_spec)\r\n  File \"/usr/lib/python3.10/runpy.py\", line 96, in _run_module_code\r\n    _run_code(code, mod_globals, init_globals,\r\n  File \"/usr/lib/python3.10/runpy.py\", line 86, in _run_code\r\n    exec(code, run_globals)\r\n  File \"/tmp/ansible_kubernetes.core.helm_payload_o8s36dti/ansible_kubernetes.core.helm_payload.zip/ansible_collections/kubernetes/core/plugins/modules/helm.py\", line 924, in <module>\r\n  File \"/tmp/ansible_kubernetes.core.helm_payload_o8s36dti/ansible_kubernetes.core.helm_payload.zip/ansible_collections/kubernetes/core/plugins/modules/helm.py\", line 737, in main\r\n  File \"/tmp/ansible_kubernetes.core.helm_payload_o8s36dti/ansible_kubernetes.core.helm_payload.zip/ansible_collections/kubernetes/core/plugins/modules/helm.py\", line 435, in run_repo_update\r\n  File \"/tmp/ansible_kubernetes.core.helm_payload_o8s36dti/ansible_kubernetes.core.helm_payload.zip/ansible_collections/kubernetes/core/plugins/module_utils/helm.py\", line 169, in run_helm_command\r\n  File \"/tmp/ansible_kubernetes.core.helm_payload_o8s36dti/ansible_kubernetes.core.helm_payload.zip/ansible_collections/kubernetes/core/plugins/module_utils/helm.py\", line 162, in env_update\r\n  File \"/tmp/ansible_kubernetes.core.helm_payload_o8s36dti/ansible_kubernetes.core.helm_payload.zip/ansible_collections/kubernetes/core/plugins/module_utils/helm.py\", line 120, in _prepare_helm_environment\r\nFileNotFoundError: [Errno 2] No such file or directory: '~/.kube/config'\r\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}

After change:
TASK [kubernetes/kubelet_csr_approver : Deploy kubelet-csr-approver] ***
changed: [node-1 -> client(192.168.121.56)]

Reviewed-by: Mike Graves <mgraves@redhat.com>
2024-03-13 13:57:36 +00:00
Bikouo Aubin
1c0734dd4e Prepare release 3.0.1 (#693) 2024-03-04 11:02:29 +01:00
patchback[bot]
e6d138dbf0 helm - Add reuse-values when running helm diff (#683) (#692)
helm - Add reuse-values when running helm diff

SUMMARY

closes #680

ISSUE TYPE

Bugfix Pull Request

COMPONENT NAME

helm

Reviewed-by: GomathiselviS
Reviewed-by: Alina Buzachis
(cherry picked from commit 23e94b60c1)

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>
2024-03-01 18:01:13 +01:00
patchback[bot]
eed4ebb0af Align helmdiff_check behavior with the deploy function (#670) (#690)
Align `helmdiff_check` behavior with the `deploy` function

SUMMARY
Align helmdiff_check behavior with the deploy function

Fixes #638
helmdiff_check respects set_values parameter
Fixes #669
helmdiff_check command line parameters sequence aligned to the deploy function

ISSUE TYPE

Bugfix Pull Request

COMPONENT NAME
kubernetes.core.helm

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

Co-authored-by: psmolkin <pavel.smolkin@gmail.com>
2024-03-01 17:50:35 +01:00
patchback[bot]
d3031fcbd3 [PR #676/19559892 backport][stable-3] fix(Collection's util resource discovery fails when complex subresources present #659) (#687)
* fix(Collection's util resource discovery fails when complex subresources present #659) (#676)

* fix(Collection's util resource discovery fails when complex subresources present #659)

* fix(add changelog fragment)

* update node image

* Create discovery.yml

* Update main.yml

---------

Co-authored-by: Bastien Bosser <bastien.bosser@eviden.com>
Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>
(cherry picked from commit 1955989278)

* adding sanity ignore file

* Remove refresh_ignore_files

* Update ignore files content

---------

Co-authored-by: bastienbosser <55381632+bastienbosser@users.noreply.github.com>
Co-authored-by: abikouo <abikouo@redhat.com>
2024-03-01 16:44:19 +01:00
GomathiselviS
e756cedf33 Prepare for release 3.0.0 (#662)
Prepare for release 3.0.0

SUMMARY



Updated version to 3.0.0
Executed antsibull-changelog to generate changelog

ISSUE TYPE


Docs Pull Request

COMPONENT NAME

ADDITIONAL INFORMATION

Reviewed-by: Alina Buzachis
Reviewed-by: Helen Bailey <hebailey@redhat.com>
Reviewed-by: GomathiselviS
2023-11-17 21:52:11 +00:00
69 changed files with 1849 additions and 2287 deletions

View File

@@ -3,3 +3,5 @@
plugins/connection/kubectl.py no-changed-when
# false positive result
plugins/connection/kubectl.py var-naming[no-reserved]
# stable-3 branch support ansible-core>=2.14.0
meta/runtime.yml meta-runtime[unsupported-version]

View File

@@ -50,6 +50,7 @@ jobs:
source: "./source"
cloud_common: "./cloudcommon"
ansible_posix: "./ansible_posix"
community_general: "./community_general"
strategy:
fail-fast: false
matrix:
@@ -61,7 +62,7 @@ jobs:
- true
- false
workflow-id: ${{ fromJson(needs.splitter.outputs.test_jobs) }}
name: "integration-py${{ matrix.python-version }}-${{ matrix.ansible-version }}-${{ matrix.workflow-id }}"
name: "integration-py${{ matrix.python-version }}-${{ matrix.ansible-version }}-${{ matrix.workflow-id }}-enable_turbo=${{ matrix.enable-turbo-mode }}"
steps:
- name: Read target
id: read-targets
@@ -118,6 +119,13 @@ jobs:
path: ${{ env.ansible_posix }}
ref: main
- name: checkout ansible-collections/community.general
uses: ansible-network/github_actions/.github/actions/checkout_dependency@main
with:
repository: ansible-collections/community.general
path: ${{ env.community_general }}
ref: main
- name: install cloud.common collection
uses: ansible-network/github_actions/.github/actions/build_install_collection@main
with:
@@ -130,6 +138,12 @@ jobs:
install_python_dependencies: true
source_path: ${{ env.ansible_posix }}
- name: install community.general collection
uses: ansible-network/github_actions/.github/actions/build_install_collection@main
with:
install_python_dependencies: false
source_path: ${{ env.community_general }}
- name: create kubernetes cluster
uses: helm/kind-action@v1.8.0
with:

View File

@@ -20,4 +20,4 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: run-ansible-lint
uses: ansible/ansible-lint@v24.12.2
uses: ansible/ansible-lint@v25.1.2

View File

@@ -4,122 +4,29 @@ Kubernetes Collection Release Notes
.. contents:: Topics
v5.2.0
v3.3.1
======
Release Summary
---------------
This release adds more functionality to the hidden_fields option and support for waiting on ClusterOperators to reach a ready state.
This release fixes the CI issues with the ``linters`` workflow.
Minor Changes
-------------
- k8s - Extend hidden_fields to allow the expression of more complex field types to be hidden (https://github.com/ansible-collections/kubernetes.core/pull/872)
- k8s_info - Extend hidden_fields to allow the expression of more complex field types to be hidden (https://github.com/ansible-collections/kubernetes.core/pull/872)
- waiter.py - add ClusterOperator support. The module can now check OpenShift cluster health by verifying ClusterOperator status requiring 'Available: True', 'Degraded: False', and 'Progressing: False' for success. (https://github.com/ansible-collections/kubernetes.core/issues/869)
v5.1.0
v3.3.0
======
Release Summary
---------------
This release came with new module ``helm_registry_auth``, improvements to the error messages in the k8s_drain module, new parameter ``insecure_registry`` for ``helm_template`` module and several bug fixes.
Minor Changes
-------------
- Bump version of ansible-lint to minimum 24.7.0 (https://github.com/ansible-collections/kubernetes.core/pull/765).
- Parameter insecure_registry added to helm_template as equivalent of insecure-skip-tls-verify (https://github.com/ansible-collections/kubernetes.core/pull/805).
- k8s_drain - Improve error message for pod disruption budget when draining a node (https://github.com/ansible-collections/kubernetes.core/issues/797).
Bugfixes
--------
- helm - Helm version checks did not support RC versions. They now accept any version tags. (https://github.com/ansible-collections/kubernetes.core/pull/745).
- helm_pull - Apply no_log=True to pass_credentials to silence false positive warning. (https://github.com/ansible-collections/kubernetes.core/pull/796).
- k8s_drain - Fix k8s_drain does not wait for single pod (https://github.com/ansible-collections/kubernetes.core/issues/769).
- k8s_drain - Fix k8s_drain runs into a timeout when evicting a pod which is part of a stateful set (https://github.com/ansible-collections/kubernetes.core/issues/792).
- kubeconfig option should not appear in module invocation log (https://github.com/ansible-collections/kubernetes.core/issues/782).
- kustomize - kustomize plugin fails with deprecation warnings (https://github.com/ansible-collections/kubernetes.core/issues/639).
- waiter - Fix waiting for daemonset when desired number of pods is 0. (https://github.com/ansible-collections/kubernetes.core/pull/756).
New Modules
-----------
- helm_registry_auth - Helm registry authentication module
v5.0.0
======
Release Summary
---------------
This major release drops support for ``ansible-core<2.15``.
Minor Changes
-------------
- connection/kubectl.py - Added an example of using the kubectl connection plugin to the documentation (https://github.com/ansible-collections/kubernetes.core/pull/741).
- inventory/k8s.py - Defer removal of k8s inventory plugin to version 6.0.0 (https://github.com/ansible-collections/kubernetes.core/pull/734).
Breaking Changes / Porting Guide
--------------------------------
- Remove support for ``ansible-core<2.15`` (https://github.com/ansible-collections/kubernetes.core/pull/737).
v4.0.0
======
Release Summary
---------------
This major release brings several bug fixes. We have also removed support for ``ansible-core<2.15`` and deprecated functions and class from ``module_utils/common.py``.
Minor Changes
-------------
- inventory/k8s.py - Defer removal of k8s inventory plugin to version 5.0 (https://github.com/ansible-collections/kubernetes.core/pull/723).
- k8s - The module and K8sService were changed so warnings returned by the K8S API are now displayed to the user.
Removed Features (previously deprecated)
----------------------------------------
- k8s - Support for ``merge_type=json`` has been removed in version 4.0.0. Please use ``kubernetes.core.k8s_json_patch`` instead (https://github.com/ansible-collections/kubernetes.core/pull/722).
- k8s_exec - the previously deprecated ``result.return_code`` return value has been removed, consider using ``result.rc`` instead (https://github.com/ansible-collections/kubernetes.core/pull/726).
- module_utils/common.py - the previously deprecated ``K8sAnsibleMixin`` class has been removed (https://github.com/ansible-collections/kubernetes.core/pull/726).
- module_utils/common.py - the previously deprecated ``configuration_digest()`` function has been removed (https://github.com/ansible-collections/kubernetes.core/pull/726).
- module_utils/common.py - the previously deprecated ``get_api_client()`` function has been removed (https://github.com/ansible-collections/kubernetes.core/pull/726).
- module_utils/common.py - the previously deprecated ``unique_string()`` function has been removed (https://github.com/ansible-collections/kubernetes.core/pull/726).
Bugfixes
--------
- Resolve Collections util resource discovery fails when complex subresources present (https://github.com/ansible-collections/kubernetes.core/pull/676).
- align `helmdiff_check()` function commandline rendering with the `deploy()` function (https://github.com/ansible-collections/kubernetes.core/pull/670).
- avoid unsafe conditions in integration tests (https://github.com/ansible-collections/kubernetes.core/pull/665).
- helm - use ``reuse-values`` when running ``helm diff`` command (https://github.com/ansible-collections/kubernetes.core/issues/680).
- integrations test helm_kubeconfig - set helm version to v3.10.3 to avoid incompatability with new bitnami charts (https://github.com/ansible-collections/kubernetes.core/pull/670).
v3.3.0
======
Release Summary
---------------
This release comes with improvements to the error messages in the k8s_drain module and several bug fixes.
Minor Changes
-------------
- inventory/k8s.py - Defer removal of k8s inventory plugin to version 6.0.0 (https://github.com/ansible-collections/kubernetes.core/pull/734).
- k8s_drain - Improve error message for pod disruption budget when draining a node (https://github.com/ansible-collections/kubernetes.core/issues/797).
Bugfixes
--------
- helm - Helm version checks did not support RC versions. They now accept any version tags. (https://github.com/ansible-collections/kubernetes.core/pull/745).
- helm_pull - Apply no_log=True to pass_credentials to silence false positive warning. (https://github.com/ansible-collections/kubernetes.core/pull/796).
- helm_pull - Apply no_log=True to pass_credentials to silence false positive warning.. (https://github.com/ansible-collections/kubernetes.core/pull/796).
- k8s_drain - Fix k8s_drain does not wait for single pod (https://github.com/ansible-collections/kubernetes.core/issues/769).
- k8s_drain - Fix k8s_drain runs into a timeout when evicting a pod which is part of a stateful set (https://github.com/ansible-collections/kubernetes.core/issues/792).
- kubeconfig option should not appear in module invocation log (https://github.com/ansible-collections/kubernetes.core/issues/782).
@@ -138,7 +45,6 @@ Minor Changes
-------------
- connection/kubectl.py - Added an example of using the kubectl connection plugin to the documentation (https://github.com/ansible-collections/kubernetes.core/pull/741).
- inventory/k8s.py - Defer removal of k8s inventory plugin to version 5.0 (https://github.com/ansible-collections/kubernetes.core/pull/723).
- inventory/k8s.py - Defer removal of k8s inventory plugin to version 6.0.0 (https://github.com/ansible-collections/kubernetes.core/pull/734).
v3.1.0

View File

@@ -48,7 +48,7 @@ Where modules have multiple parameters we recommend running through the 4-step m
For general information on running the integration tests see the
[Integration Tests page of the Module Development Guide](https://docs.ansible.com/ansible/devel/dev_guide/testing_integration.html#testing-integration),
especially the section on configuration for cloud tests.
especially the section on configuration for cloud tests. For questions about writing tests the Ansible Kubernetes community can be found on Libera.Chat IRC as detailed below.
### Updating documentation
@@ -70,3 +70,11 @@ Review the changes and create a pull request using updated files.
The `kubernetes.core` collection follows the Ansible project's
[Code of Conduct](https://docs.ansible.com/ansible/devel/community/code_of_conduct.html).
Please read and familiarize yourself with this document.
### IRC
Our IRC channels may require you to register your nickname. If you receive an error when you connect, see
[Libera.Chat's Nickname Registration guide](https://libera.chat/guides/registration) for instructions.
The `#ansible-kubernetes` channel on [libera.chat](https://libera.chat/) IRC is the main and official place to discuss use and development of the `kubernetes.core` collection.
For more information about Ansible's Kubernetes integration, browse the resources in the [Kubernetes Working Group](https://github.com/ansible/community/wiki/Kubernetes) Community wiki page.

View File

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

View File

@@ -1,29 +1,19 @@
# Kubernetes Collection for Ansible
[![CI](https://github.com/ansible-collections/kubernetes.core/workflows/CI/badge.svg?event=push)](https://github.com/ansible-collections/kubernetes.core/actions) [![Codecov](https://img.shields.io/codecov/c/github/ansible-collections/kubernetes.core)](https://codecov.io/gh/ansible-collections/kubernetes.core)
This repository hosts the `kubernetes.core` (formerly known as `community.kubernetes`) Ansible Collection.
## Description
The collection includes a variety of Ansible content to help automate the management of applications in Kubernetes and OpenShift clusters, as well as the provisioning and maintenance of clusters themselves.
## Communication
* Join the Ansible forum:
* [Get Help](https://forum.ansible.com/c/help/6): get help or help others.
* [Posts tagged with 'kubernetes'](https://forum.ansible.com/tag/kubernetes): subscribe to participate in collection-related conversations.
* [Social Spaces](https://forum.ansible.com/c/chat/4): gather and interact with fellow enthusiasts.
* [News & Announcements](https://forum.ansible.com/c/news/5): track project-wide announcements including social events.
* The Ansible [Bullhorn newsletter](https://docs.ansible.com/ansible/devel/community/communication.html#the-bullhorn): used to announce releases and important changes.
For more information about communication, see the [Ansible communication guide](https://docs.ansible.com/ansible/devel/community/communication.html).
## Requirements
<!--start requires_ansible-->
## Ansible version compatibility
### Ansible version compatibility
This collection has been tested against following Ansible versions: **>=2.15.0**.
This collection has been tested against following Ansible versions: **>=2.14.0**.
For collections that support Ansible 2.9, please ensure you update your `network_os` to use the
fully qualified collection name (for example, `cisco.ios.ios`).
@@ -47,28 +37,28 @@ This collection supports Kubernetes versions >= 1.24.
Click on the name of a plugin or module to view that content's documentation:
<!--start collection content-->
### Connection plugins
#### Connection plugins
Name | Description
--- | ---
[kubernetes.core.kubectl](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.kubectl_connection.rst)|Execute tasks in pods running on Kubernetes.
### K8s filter plugins
#### K8s filter plugins
Name | Description
--- | ---
kubernetes.core.k8s_config_resource_name|Generate resource name for the given resource of type ConfigMap, Secret
### Inventory plugins
#### Inventory plugins
Name | Description
--- | ---
[kubernetes.core.k8s](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_inventory.rst)|Kubernetes (K8s) inventory source
### Lookup plugins
#### Lookup plugins
Name | Description
--- | ---
[kubernetes.core.k8s](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_lookup.rst)|Query the K8s API
[kubernetes.core.kustomize](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.kustomize_lookup.rst)|Build a set of kubernetes resources using a 'kustomization.yaml' file.
### Modules
#### Modules
Name | Description
--- | ---
[kubernetes.core.helm](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.helm_module.rst)|Manages Kubernetes packages with the Helm package manager
@@ -76,7 +66,6 @@ Name | Description
[kubernetes.core.helm_plugin](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.helm_plugin_module.rst)|Manage Helm plugins
[kubernetes.core.helm_plugin_info](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.helm_plugin_info_module.rst)|Gather information about Helm plugins
[kubernetes.core.helm_pull](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.helm_pull_module.rst)|download a chart from a repository and (optionally) unpack it in local directory.
[kubernetes.core.helm_registry_auth](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.helm_registry_auth_module.rst)|Helm registry authentication module
[kubernetes.core.helm_repository](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.helm_repository_module.rst)|Manage Helm repositories.
[kubernetes.core.helm_template](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.helm_template_module.rst)|Render chart templates
[kubernetes.core.k8s](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_module.rst)|Manage Kubernetes (K8s) objects
@@ -106,7 +95,7 @@ You can also include it in a `requirements.yml` file and install it via `ansible
---
collections:
- name: kubernetes.core
version: 5.2.0
version: 3.3.1
```
### Installing the Kubernetes Python Library
@@ -267,6 +256,10 @@ If you encounter issues or have questions, you can submit a support request thro
See the [raw generated changelog](https://github.com/ansible-collections/kubernetes.core/blob/main/CHANGELOG.rst).
## More Information
For more information about Ansible's Kubernetes integration, join the `#ansible-kubernetes` channel on [libera.chat](https://libera.chat/) IRC, and browse the resources in the [Kubernetes Working Group](https://github.com/ansible/community/wiki/Kubernetes) Community wiki page.
## Code of Conduct
We follow the [Ansible Code of Conduct](https://docs.ansible.com/ansible/devel/community/code_of_conduct.html) in all our interactions within this project.

View File

@@ -885,8 +885,7 @@ releases:
minor_changes:
- k8s_drain - Improve error message for pod disruption budget when draining
a node (https://github.com/ansible-collections/kubernetes.core/issues/797).
release_summary: This release comes with improvements to the error messages
in the k8s_drain module and several bug fixes.
release_summary: This release comes with improvements to the error messages in the k8s_drain module and several bug fixes.
fragments:
- 20240530-ansible-core-support-update.yaml
- 20240611-helm-rc-version.yaml
@@ -899,121 +898,10 @@ releases:
- 796-false-positive-helmull.yaml
- 798-drain-pdb-error-message.yaml
- readme_template_update.yml
release_date: '2025-01-20'
4.0.0:
release_date: '2025-01-22'
3.3.1:
changes:
bugfixes:
- Resolve Collections util resource discovery fails when complex subresources
present (https://github.com/ansible-collections/kubernetes.core/pull/676).
- align `helmdiff_check()` function commandline rendering with the `deploy()`
function (https://github.com/ansible-collections/kubernetes.core/pull/670).
- avoid unsafe conditions in integration tests (https://github.com/ansible-collections/kubernetes.core/pull/665).
- helm - use ``reuse-values`` when running ``helm diff`` command (https://github.com/ansible-collections/kubernetes.core/issues/680).
- integrations test helm_kubeconfig - set helm version to v3.10.3 to avoid incompatability
with new bitnami charts (https://github.com/ansible-collections/kubernetes.core/pull/670).
minor_changes:
- inventory/k8s.py - Defer removal of k8s inventory plugin to version 5.0 (https://github.com/ansible-collections/kubernetes.core/pull/723).
- k8s - The module and K8sService were changed so warnings returned by the K8S
API are now displayed to the user.
release_summary: This major release brings several bug fixes. We have also removed
support for ``ansible-core<2.15`` and deprecated functions and class from
``module_utils/common.py``.
removed_features:
- k8s - Support for ``merge_type=json`` has been removed in version 4.0.0. Please
use ``kubernetes.core.k8s_json_patch`` instead (https://github.com/ansible-collections/kubernetes.core/pull/722).
- k8s_exec - the previously deprecated ``result.return_code`` return value has
been removed, consider using ``result.rc`` instead (https://github.com/ansible-collections/kubernetes.core/pull/726).
- module_utils/common.py - the previously deprecated ``K8sAnsibleMixin`` class
has been removed (https://github.com/ansible-collections/kubernetes.core/pull/726).
- module_utils/common.py - the previously deprecated ``configuration_digest()``
function has been removed (https://github.com/ansible-collections/kubernetes.core/pull/726).
- module_utils/common.py - the previously deprecated ``get_api_client()`` function
has been removed (https://github.com/ansible-collections/kubernetes.core/pull/726).
- module_utils/common.py - the previously deprecated ``unique_string()`` function
has been removed (https://github.com/ansible-collections/kubernetes.core/pull/726).
release_summary: This release fixes the CI issues with the ``linters`` workflow.
fragments:
- 20231206-fix-unsafe-condition-in-integration.yml
- 20240117-fix-helm-diff-cmd-line-rendering.yml
- 20240222-Collections-util-resource-discovery-fails-when-complex-subresources-present.yml
- 20240228-fix-helm-diff-with-reuse-values.yml
- 20240423-k8s-display-warnings-to-users.yml
- 4.0.0.yaml
- inventory-update_removal_date.yml
- k8s-merge_type-removed.yml
- module_utils-common-remove-deprecated-functions-and-class.yaml
release_date: '2024-05-24'
5.0.0:
changes:
breaking_changes:
- Remove support for ``ansible-core<2.15`` (https://github.com/ansible-collections/kubernetes.core/pull/737).
minor_changes:
- connection/kubectl.py - Added an example of using the kubectl connection plugin
to the documentation (https://github.com/ansible-collections/kubernetes.core/pull/741).
- inventory/k8s.py - Defer removal of k8s inventory plugin to version 6.0.0
(https://github.com/ansible-collections/kubernetes.core/pull/734).
release_summary: This major release drops support for ``ansible-core<2.15``.
fragments:
- 20240530-ansible-core-support-update.yaml
- 20240530-defer-removal-and-ansible-core-support-update.yaml
- 5.0.0.yml
release_date: '2024-05-31'
5.1.0:
changes:
bugfixes:
- helm - Helm version checks did not support RC versions. They now accept any
version tags. (https://github.com/ansible-collections/kubernetes.core/pull/745).
- helm_pull - Apply no_log=True to pass_credentials to silence false positive
warning. (https://github.com/ansible-collections/kubernetes.core/pull/796).
- k8s_drain - Fix k8s_drain does not wait for single pod (https://github.com/ansible-collections/kubernetes.core/issues/769).
- k8s_drain - Fix k8s_drain runs into a timeout when evicting a pod which is
part of a stateful set (https://github.com/ansible-collections/kubernetes.core/issues/792).
- kubeconfig option should not appear in module invocation log (https://github.com/ansible-collections/kubernetes.core/issues/782).
- kustomize - kustomize plugin fails with deprecation warnings (https://github.com/ansible-collections/kubernetes.core/issues/639).
- waiter - Fix waiting for daemonset when desired number of pods is 0. (https://github.com/ansible-collections/kubernetes.core/pull/756).
minor_changes:
- Bump version of ansible-lint to minimum 24.7.0 (https://github.com/ansible-collections/kubernetes.core/pull/765).
- Parameter insecure_registry added to helm_template as equivalent of insecure-skip-tls-verify
(https://github.com/ansible-collections/kubernetes.core/pull/805).
- k8s_drain - Improve error message for pod disruption budget when draining
a node (https://github.com/ansible-collections/kubernetes.core/issues/797).
release_summary: This release came with new module ``helm_registry_auth``, improvements
to the error messages in the k8s_drain module, new parameter ``insecure_registry``
for ``helm_template`` module and several bug fixes.
fragments:
- 0-readme.yml
- 20240601-doc-example-of-using-kubectl.yaml
- 20240611-helm-rc-version.yaml
- 20240620-fix-kustomize-plugin-fails-with-deprecation-warnings.yml
- 20241102-fix-ci-post-2.18-issue.yaml
- 20241103-completly-remove-obsolate-communication-channel.yaml
- 20241207-add-insecure-skip-tls-verify-to-helm-template.yaml
- 20241213-kubeconfig-set-no_log-true.yaml
- 756-fix-daemonset-waiting.yaml
- 765-bump-ansible-lint-version.yml
- 770-fix-k8s-drain-doesnt-wait-for-single-pod.yaml
- 793-fix-k8s-drain-runs-into-timeout.yaml
- 796-false-positive-helmull.yaml
- 798-drain-pdb-error-message.yaml
- readme_template_update.yml
modules:
- description: Helm registry authentication module
name: helm_registry_auth
namespace: ''
release_date: '2025-01-20'
5.2.0:
changes:
minor_changes:
- k8s - Extend hidden_fields to allow the expression of more complex field types
to be hidden (https://github.com/ansible-collections/kubernetes.core/pull/872)
- k8s_info - Extend hidden_fields to allow the expression of more complex field
types to be hidden (https://github.com/ansible-collections/kubernetes.core/pull/872)
- 'waiter.py - add ClusterOperator support. The module can now check OpenShift
cluster health by verifying ClusterOperator status requiring ''Available:
True'', ''Degraded: False'', and ''Progressing: False'' for success. (https://github.com/ansible-collections/kubernetes.core/issues/869)'
release_summary: This release adds more functionality to the hidden_fields option
and support for waiting on ClusterOperators to reach a ready state.
fragments:
- 5.2.0.yml
- 643-extend-hidden-fields.yaml
- 879-clusteroperator-waiter.py.yaml
release_date: '2025-03-27'
- release_summary.yml
release_date: '2025-03-26'

View File

@@ -0,0 +1,3 @@
---
minor_changes:
- action/k8s_info - update templating mechanism with changes from ``ansible-core 2.19`` (https://github.com/ansible-collections/kubernetes.core/pull/888).

View File

@@ -0,0 +1,3 @@
---
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).

View File

@@ -0,0 +1,3 @@
---
minor_changes:
- Bump version of ansible-lint to 25.1.2 (https://github.com/ansible-collections/kubernetes.core/pull/919).

View File

@@ -1,332 +0,0 @@
.. _kubernetes.core.helm_registry_auth_module:
**********************************
kubernetes.core.helm_registry_auth
**********************************
**Helm registry authentication module**
Version added: 5.1.0
.. contents::
:local:
:depth: 1
Synopsis
--------
- Helm registry authentication module allows you to login ``helm registry login`` and logout ``helm registry logout`` from a Helm registry.
Requirements
------------
The below requirements are needed on the host that executes this module.
- helm (https://github.com/helm/helm/releases) => 3.8.0
Parameters
----------
.. raw:: html
<table border=0 cellpadding=0 class="documentation-table">
<tr>
<th colspan="1">Parameter</th>
<th>Choices/<font color="blue">Defaults</font></th>
<th width="100%">Comments</th>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>binary_path</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>The path of a helm binary to use.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>ca_file</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to the CA certificate SSL file for verify registry server certificate.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>cert_file</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to the client certificate SSL file for identify registry client using this certificate file.</div>
</td>
</tr>
<tr>
<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">string</span>
/ <span style="color: red">required</span>
</div>
</td>
<td>
</td>
<td>
<div>Provide a URL for accessing the registry.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: registry_url</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>insecure</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><div style="color: blue"><b>no</b>&nbsp;&larr;</div></li>
<li>yes</li>
</ul>
</td>
<td>
<div>Allow connections to SSL sites without certs.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>key_file</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to the client key SSL file for identify registry client using this key file.</div>
</td>
</tr>
<tr>
<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 the registry.</div>
<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>state</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>present</b>&nbsp;&larr;</div></li>
<li>absent</li>
</ul>
</td>
<td>
<div>Desired state of the registry.</div>
<div>If set to V(present) attempt to log in to the remote registry server using the URL specified in O(host).</div>
<div>If set to V(absent) attempt to log out from the remote registry server using the URL specified in O(host).</div>
</td>
</tr>
<tr>
<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 the registry.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: repo_username</div>
</td>
</tr>
</table>
<br/>
Examples
--------
.. code-block:: yaml
- name: Login to remote registry
kubernetes.core.helm_registry_auth:
username: admin
password: "sample_password"
host: localhost:5000
- name: Logout from remote registry
kubernetes.core.helm_registry_auth:
state: absent
host: localhost:5000
Return Values
-------------
Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html
<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>command</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>Full <code>helm</code> command executed</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;">/usr/local/bin/helm registry login oci-registry.domain.example --username=admin --password-stdin --insecure</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>failed</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
</td>
<td>always</td>
<td>
<div>Indicate if the <code>helm</code> command failed</div>
<br/>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>stderr</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>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>
<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>stderr_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>
</div>
</td>
<td>always</td>
<td>
<div>Full <code>helm</code> command stderr, in case you want to display it or examine the event log</div>
<br/>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>stdout</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>Full <code>helm</code> command stdout, in case you want to display it or examine the event log</div>
<br/>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>stout_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>
</div>
</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>
<br/>
</td>
</tr>
</table>
<br/><br/>
Status
------
Authors
~~~~~~~
- Yuriy Novostavskiy (@yurnov)

View File

@@ -158,26 +158,6 @@ Parameters
<div>Include custom resource descriptions in rendered templates.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>insecure_registry</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 5.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>Skip TLS certificate checks for the chart download</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>

View File

@@ -121,7 +121,7 @@ Parameters
<td>
<div><code>apply</code> compares the desired resource definition with the previously supplied resource definition, ignoring properties that are automatically generated</div>
<div><code>apply</code> works better with Services than &#x27;force=yes&#x27;</div>
<div>Mutually exclusive with <code>merge_type</code>.</div>
<div>mutually exclusive with <code>merge_type</code></div>
</td>
</tr>
<tr>
@@ -513,17 +513,18 @@ Parameters
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>json</li>
<li>merge</li>
<li>strategic-merge</li>
</ul>
</td>
<td>
<div>Whether to override the default patch merge approach with a specific type. By default, the strategic merge will typically be used.</div>
<div>For example, Custom Resource Definitions typically aren&#x27;t updatable by the usual strategic merge. You may want to use <code>merge</code> if you see &quot;strategic merge patch format is not supported&quot;.</div>
<div>For example, Custom Resource Definitions typically aren&#x27;t updatable by the usual strategic merge. You may want to use <code>merge</code> if you see &quot;strategic merge patch format is not supported&quot;</div>
<div>See <a href='https://kubernetes.io/docs/tasks/run-application/update-api-object-kubectl-patch/#use-a-json-merge-patch-to-update-a-deployment'>https://kubernetes.io/docs/tasks/run-application/update-api-object-kubectl-patch/#use-a-json-merge-patch-to-update-a-deployment</a></div>
<div>If more than one <code>merge_type</code> is given, the merge_types will be tried in order. This defaults to <code>[&#x27;strategic-merge&#x27;, &#x27;merge&#x27;]</code>, which is ideal for using the same parameters on resource kinds that combine Custom Resources and built-in resources.</div>
<div>Mutually exclusive with <code>apply</code>.</div>
<div><em>merge_type=json</em> has been removed in version 4.0.0. Please use <span class='module'>kubernetes.core.k8s_json_patch</span> instead.</div>
<div>mutually exclusive with <code>apply</code></div>
<div><em>merge_type=json</em> is deprecated and will be removed in version 4.0.0. Please use <span class='module'>kubernetes.core.k8s_json_patch</span> instead.</div>
</td>
</tr>
<tr>

View File

@@ -25,7 +25,7 @@ tags:
- openshift
- okd
- cluster
version: 5.2.0
version: 3.3.1
build_ignore:
- .DS_Store
- "*.tar.gz"

View File

@@ -1,5 +1,5 @@
---
requires_ansible: '>=2.15.0'
requires_ansible: '>=2.14.0'
action_groups:
helm:

View File

@@ -25,30 +25,18 @@ from ansible.module_utils.parsing.convert_bool import boolean
from ansible.module_utils.six import iteritems, string_types
from ansible.plugins.action import ActionBase
try:
from ansible.template import trust_as_template
except ImportError:
trust_as_template = None
class RemoveOmit(object):
def __init__(self, buffer, omit_value):
try:
import yaml
except ImportError:
raise AnsibleError("Failed to import the required Python library (PyYAML).")
self.data = yaml.safe_load_all(buffer)
self.omit = omit_value
def remove_omit(self, data):
if isinstance(data, dict):
result = dict()
for key, value in iteritems(data):
if value == self.omit:
continue
result[key] = self.remove_omit(value)
return result
if isinstance(data, list):
return [self.remove_omit(v) for v in data if v != self.omit]
return data
def output(self):
return [self.remove_omit(d) for d in self.data]
def _from_yaml_to_definition(buffer):
try:
import yaml
except ImportError:
raise AnsibleError("Failed to import the required Python library (PyYAML).")
return list(yaml.safe_load_all(buffer))
ENV_KUBECONFIG_PATH_SEPARATOR = ";" if platform.system() == "Windows" else ":"
@@ -207,7 +195,6 @@ class ActionModule(ActionBase):
"'template' is only a supported parameter for the 'k8s' module."
)
omit_value = task_vars.get("omit")
template_params = []
if isinstance(template, string_types) or isinstance(template, dict):
template_params.append(self.get_template_args(template))
@@ -230,17 +217,18 @@ class ActionModule(ActionBase):
old_vars = self._templar.available_variables
default_environment = {}
for key in (
"newline_sequence",
"variable_start_string",
"variable_end_string",
"block_start_string",
"block_end_string",
"trim_blocks",
"lstrip_blocks",
):
if hasattr(self._templar.environment, key):
default_environment[key] = getattr(self._templar.environment, key)
if trust_as_template is None:
for key in (
"newline_sequence",
"variable_start_string",
"variable_end_string",
"block_start_string",
"block_end_string",
"trim_blocks",
"lstrip_blocks",
):
if hasattr(self._templar.environment, key):
default_environment[key] = getattr(self._templar.environment, key)
for template_item in template_params:
# We need to convert unescaped sequences to proper escaped sequences for Jinja2
newline_sequence = template_item["newline_sequence"]
@@ -257,26 +245,35 @@ class ActionModule(ActionBase):
with self.get_template_data(template_item["path"]) as template_data:
# add ansible 'template' vars
temp_vars = copy.deepcopy(task_vars)
overrides = {}
for key, value in iteritems(template_item):
if hasattr(self._templar.environment, key):
if value is not None:
setattr(self._templar.environment, key, value)
else:
overrides[key] = value
if trust_as_template is None:
setattr(self._templar.environment, key, value)
elif trust_as_template is None:
setattr(
self._templar.environment,
key,
default_environment.get(key),
)
self._templar.available_variables = temp_vars
result = self._templar.do_template(
template_data,
preserve_trailing_newlines=True,
escape_backslashes=False,
)
if omit_value is not None:
result_template.extend(RemoveOmit(result, omit_value).output())
if trust_as_template:
template_data = trust_as_template(template_data)
result = self._templar.template(
template_data,
preserve_trailing_newlines=True,
escape_backslashes=False,
overrides=overrides,
)
else:
result_template.append(result)
result = self._templar.do_template(
template_data,
preserve_trailing_newlines=True,
escape_backslashes=False,
)
result_template.extend(_from_yaml_to_definition(result))
self._templar.available_variables = old_vars
resource_definition = self._task.args.get("definition", None)
if not resource_definition:

View File

@@ -125,19 +125,19 @@ 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.common import (
HAS_K8S_MODULE_HELPER,
k8s_import_exception,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
get_api_client,
)
try:
from kubernetes.dynamic.exceptions import DynamicApiError
except ImportError:
pass
def format_dynamic_api_exc(exc):
if exc.body:

View File

@@ -149,7 +149,6 @@ def k8s_apply(resource, definition, **kwargs):
force_conflicts=kwargs.get("force_conflicts"),
field_manager=kwargs.get("field_manager"),
dry_run=kwargs.get("dry_run"),
serialize=kwargs.get("serialize"),
)
if not existing:
return resource.create(
@@ -159,7 +158,6 @@ def k8s_apply(resource, definition, **kwargs):
return resource.get(
name=definition["metadata"]["name"],
namespace=definition["metadata"].get("namespace"),
**kwargs
)
return resource.patch(
body=desired,

File diff suppressed because it is too large Load Diff

View File

@@ -159,13 +159,11 @@ class AnsibleHelmModule(object):
self.helm_env = self._prepare_helm_environment()
return self.helm_env
def run_helm_command(self, command, fails_on_error=True, data=None):
def run_helm_command(self, command, fails_on_error=True):
if not HAS_YAML:
self.fail_json(msg=missing_required_lib("PyYAML"), exception=YAML_IMP_ERR)
rc, out, err = self.run_command(
command, environ_update=self.env_update, data=data
)
rc, out, err = self.run_command(command, environ_update=self.env_update)
if fails_on_error and rc != 0:
self.fail_json(
msg="Failure when executing Helm command. Exited {0}.\nstdout: {1}\nstderr: {2}".format(

View File

@@ -139,7 +139,6 @@ def perform_action(svc, definition: Dict, params: Dict) -> Dict:
result = {"changed": False, "result": {}}
instance = {}
warnings = []
resource = svc.find_resource(kind, api_version, fail=True)
definition["kind"] = resource.kind
@@ -173,7 +172,7 @@ def perform_action(svc, definition: Dict, params: Dict) -> Dict:
return result
if params.get("apply"):
instance, warnings = svc.apply(resource, definition, existing)
instance = svc.apply(resource, definition, existing)
result["method"] = "apply"
elif not existing:
if state == "patched":
@@ -184,19 +183,16 @@ def perform_action(svc, definition: Dict, params: Dict) -> Dict:
)
)
return result
instance, warnings = svc.create(resource, definition)
instance = svc.create(resource, definition)
result["method"] = "create"
result["changed"] = True
elif params.get("force", False):
instance, warnings = svc.replace(resource, definition, existing)
instance = svc.replace(resource, definition, existing)
result["method"] = "replace"
else:
instance, warnings = svc.update(resource, definition, existing)
instance = svc.update(resource, definition, existing)
result["method"] = "update"
if warnings:
result["warnings"] = warnings
# If needed, wait and/or create diff
success = True

View File

@@ -2,9 +2,7 @@
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
import copy
from json import loads
from re import compile
from typing import Any, Dict, List, Optional, Tuple, Union
from typing import Any, Dict, List, Optional, Tuple
from ansible.module_utils.common.dict_transformations import dict_merge
from ansible_collections.kubernetes.core.plugins.module_utils.hashes import (
@@ -144,12 +142,18 @@ class K8sService:
name: str,
namespace: str,
merge_type: str = None,
) -> Tuple[Dict, List[str]]:
) -> Dict:
if merge_type == "json":
self.module.deprecate(
msg="json as a merge_type value is deprecated. Please use the k8s_json_patch module instead.",
version="4.0.0",
collection_name="kubernetes.core",
)
try:
params = dict(name=name, namespace=namespace, serialize=False)
params = dict(name=name, namespace=namespace)
if merge_type:
params["content_type"] = "application/{0}-patch+json".format(merge_type)
return decode_response(self.client.patch(resource, definition, **params))
return self.client.patch(resource, definition, **params).to_dict()
except Exception as e:
reason = e.body if hasattr(e, "body") else e
msg = "Failed to patch object: {0}".format(reason)
@@ -326,124 +330,123 @@ class K8sService:
result["resources"].append(hide_fields(res, hidden_fields))
return result
def create(self, resource: Resource, definition: Dict) -> Tuple[Dict, List[str]]:
def create(self, resource: Resource, definition: Dict) -> Dict:
namespace = definition["metadata"].get("namespace")
name = definition["metadata"].get("name")
if self._client_side_dry_run:
return _encode_stringdata(definition), []
try:
return decode_response(
self.client.create(
resource, definition, namespace=namespace, serialize=False
k8s_obj = _encode_stringdata(definition)
else:
try:
k8s_obj = self.client.create(
resource, definition, namespace=namespace
).to_dict()
except ConflictError:
# Some resources, like ProjectRequests, can't be created multiple times,
# because the resources that they create don't match their kind
# In this case we'll mark it as unchanged and warn the user
self.module.warn(
"{0} was not found, but creating it returned a 409 Conflict error. This can happen \
if the resource you are creating does not directly create a resource of the same kind.".format(
name
)
)
)
except ConflictError:
# Some resources, like ProjectRequests, can't be created multiple times,
# because the resources that they create don't match their kind
# In this case we'll mark it as unchanged and warn the user
self.module.warn(
"{0} was not found, but creating it returned a 409 Conflict error. This can happen \
if the resource you are creating does not directly create a resource of the same kind.".format(
name
)
)
return dict(), []
except Exception as e:
reason = e.body if hasattr(e, "body") else e
msg = "Failed to create object: {0}".format(reason)
raise CoreException(msg) from e
return dict()
except Exception as e:
reason = e.body if hasattr(e, "body") else e
msg = "Failed to create object: {0}".format(reason)
raise CoreException(msg) from e
return k8s_obj
def apply(
self,
resource: Resource,
definition: Dict,
existing: Optional[ResourceInstance] = None,
) -> Tuple[Dict, List[str]]:
) -> Dict:
namespace = definition["metadata"].get("namespace")
server_side_apply = self.module.params.get("server_side_apply")
if server_side_apply:
requires("kubernetes", "19.15.0", reason="to use server side apply")
if self._client_side_dry_run:
ignored, patch = apply_object(resource, _encode_stringdata(definition))
if existing:
return dict_merge(existing.to_dict(), patch), []
k8s_obj = dict_merge(existing.to_dict(), patch)
else:
return patch, []
try:
params = {}
if server_side_apply:
params["server_side"] = True
params.update(server_side_apply)
return decode_response(
self.client.apply(
resource, definition, namespace=namespace, serialize=False, **params
)
)
except Exception as e:
reason = e.body if hasattr(e, "body") else e
msg = "Failed to apply object: {0}".format(reason)
raise CoreException(msg) from e
k8s_obj = patch
else:
try:
params = {}
if server_side_apply:
params["server_side"] = True
params.update(server_side_apply)
k8s_obj = self.client.apply(
resource, definition, namespace=namespace, **params
).to_dict()
except Exception as e:
reason = e.body if hasattr(e, "body") else e
msg = "Failed to apply object: {0}".format(reason)
raise CoreException(msg) from e
return k8s_obj
def replace(
self,
resource: Resource,
definition: Dict,
existing: ResourceInstance,
) -> Tuple[Dict, List[str]]:
) -> Dict:
append_hash = self.module.params.get("append_hash", False)
name = definition["metadata"].get("name")
namespace = definition["metadata"].get("namespace")
if self._client_side_dry_run:
return _encode_stringdata(definition), []
try:
return decode_response(
self.client.replace(
k8s_obj = _encode_stringdata(definition)
else:
try:
k8s_obj = self.client.replace(
resource,
definition,
name=name,
namespace=namespace,
append_hash=append_hash,
serialize=False,
)
)
except Exception as e:
reason = e.body if hasattr(e, "body") else e
msg = "Failed to replace object: {0}".format(reason)
raise CoreException(msg) from e
).to_dict()
except Exception as e:
reason = e.body if hasattr(e, "body") else e
msg = "Failed to replace object: {0}".format(reason)
raise CoreException(msg) from e
return k8s_obj
def update(
self, resource: Resource, definition: Dict, existing: ResourceInstance
) -> Tuple[Dict, List[str]]:
) -> Dict:
name = definition["metadata"].get("name")
namespace = definition["metadata"].get("namespace")
if self._client_side_dry_run:
return dict_merge(existing.to_dict(), _encode_stringdata(definition)), []
exception = None
for merge_type in self.module.params.get("merge_type") or [
"strategic-merge",
"merge",
]:
try:
return self.patch_resource(
resource,
definition,
name,
namespace,
merge_type=merge_type,
)
except CoreException as e:
exception = e
continue
raise exception
k8s_obj = dict_merge(existing.to_dict(), _encode_stringdata(definition))
else:
exception = None
for merge_type in self.module.params.get("merge_type") or [
"strategic-merge",
"merge",
]:
try:
k8s_obj = self.patch_resource(
resource,
definition,
name,
namespace,
merge_type=merge_type,
)
exception = None
except CoreException as e:
exception = e
continue
break
if exception:
raise exception
return k8s_obj
def delete(
self,
@@ -473,7 +476,7 @@ class K8sService:
if label_selectors:
params["label_selector"] = ",".join(label_selectors)
if delete_options:
if delete_options and not self.module.check_mode:
body = {
"apiVersion": "v1",
"kind": "DeleteOptions",
@@ -501,214 +504,42 @@ def diff_objects(
result["before"] = diff[0]
result["after"] = diff[1]
if list(result["after"].keys()) == ["metadata"] and list(
if list(result["after"].keys()) != ["metadata"] or list(
result["before"].keys()
) == ["metadata"]:
# If only metadata.generation and metadata.resourceVersion changed, ignore it
ignored_keys = set(["generation", "resourceVersion"])
) != ["metadata"]:
return False, result
if set(result["after"]["metadata"].keys()).issubset(ignored_keys) and set(
result["before"]["metadata"].keys()
).issubset(ignored_keys):
return True, result
# If only metadata.generation and metadata.resourceVersion changed, ignore it
ignored_keys = set(["generation", "resourceVersion"])
if not set(result["after"]["metadata"].keys()).issubset(ignored_keys):
return False, result
if not set(result["before"]["metadata"].keys()).issubset(ignored_keys):
return False, result
result["before"] = hide_fields(result["before"], hidden_fields)
result["after"] = hide_fields(result["after"], hidden_fields)
return False, result
return True, result
def hide_field_tree(hidden_field: str) -> List[str]:
result = []
key, rest = hide_field_split2(hidden_field)
result.append(key)
while rest:
key, rest = hide_field_split2(rest)
result.append(key)
return result
def build_hidden_field_tree(hidden_fields: List[str]) -> Dict[str, Any]:
"""Group hidden field targeting the same json key
Example:
Input: ['env[3]', 'env[0]']
Output: {'env': [0, 3]}
"""
output = {}
for hidden_field in hidden_fields:
current = output
tree = hide_field_tree(hidden_field)
for idx, key in enumerate(tree):
if current.get(key, "") is None:
break
if idx == (len(tree) - 1):
current[key] = None
elif key not in current:
current[key] = {}
current = current[key]
return output
# hide_field should be able to cope with simple or more complicated
# field definitions
# e.g. status or metadata.managedFields or
# spec.template.spec.containers[0].env[3].value or
# metadata.annotations[kubectl.kubernetes.io/last-applied-configuration]
def hide_field(
definition: Union[Dict[str, Any], List[Any]], hidden_field: Dict[str, Any]
) -> Dict[str, Any]:
def dict_contains_key(obj: Dict[str, Any], key: str) -> bool:
return key in obj
def list_contains_key(obj: List[Any], key: str) -> bool:
return int(key) < len(obj)
hidden_keys = list(hidden_field.keys())
field_contains_key = dict_contains_key
field_get_key = str
if isinstance(definition, list):
# Sort with reverse=true so that when we delete an item from the list, the order is not changed
hidden_keys = sorted(
[k for k in hidden_field.keys() if k.isdecimal()], reverse=True
)
field_contains_key = list_contains_key
field_get_key = int
for key in hidden_keys:
if field_contains_key(definition, key):
value = hidden_field.get(key)
convert_key = field_get_key(key)
if value is None:
del definition[convert_key]
else:
definition[convert_key] = hide_field(definition[convert_key], value)
if (
definition[convert_key] == dict()
or definition[convert_key] == list()
):
del definition[convert_key]
return definition
def hide_fields(
definition: Dict[str, Any], hidden_fields: Optional[List[str]]
) -> Dict[str, Any]:
def hide_fields(definition: dict, hidden_fields: Optional[list]) -> dict:
if not hidden_fields:
return definition
result = copy.deepcopy(definition)
hidden_field_tree = build_hidden_field_tree(hidden_fields)
return hide_field(result, hidden_field_tree)
for hidden_field in hidden_fields:
result = hide_field(result, hidden_field)
return result
def decode_response(resp) -> Tuple[Dict, List[str]]:
"""
This function decodes unserialized responses from the Kubernetes python
client and decodes the RFC2616 14.46 warnings found in the response
headers.
"""
obj = ResourceInstance(None, loads(resp.data.decode("utf8"))).to_dict()
warnings = []
if (
resp.headers is not None
and "warning" in resp.headers
and resp.headers["warning"] is not None
):
warnings = resp.headers["warning"].split(", ")
return obj, decode_warnings(warnings)
def decode_warnings(warnings: str) -> List[str]:
"""
This function decodes RFC2616 14.46 warnings in a simplified way, where
only the warn-texts are returned in a list.
"""
p = compile('\\d{3} .+ (".+")')
decoded = []
for warning in warnings:
m = p.match(warning)
if m:
try:
parsed, unused = parse_quoted_string(m.group(1))
decoded.append(parsed)
except ValueError:
continue
return decoded
def parse_quoted_string(quoted_string: str) -> Tuple[str, str]:
"""
This function was adapted from:
https://github.com/kubernetes/apimachinery/blob/bb8822152cabfb4f34dbc26270f874ce53db50de/pkg/util/net/http.go#L609
"""
if len(quoted_string) == 0:
raise ValueError("invalid quoted string: 0-length")
if quoted_string[0] != '"':
raise ValueError("invalid quoted string: missing initial quote")
quoted_string = quoted_string[1:]
remainder = ""
escaping = False
closed_quote = False
result = []
for i, b in enumerate(quoted_string):
if b == '"':
if escaping:
result.append(b)
escaping = False
else:
closed_quote = True
remainder_start = i + 1
remainder = quoted_string[remainder_start:].strip()
break
elif b == "\\":
if escaping:
result.append(b)
escaping = False
else:
escaping = True
else:
result.append(b)
escaping = False
if not closed_quote:
raise ValueError("invalid quoted string: missing closing quote")
return "".join(result), remainder
# hide_field_split2 returns the first key in hidden_field and the rest of the hidden_field
# We expect the first key to either be in brackets, to be terminated by the start of a left
# bracket, or to be terminated by a dot.
# examples would be:
# field.another.next -> (field, another.next)
# field[key].value -> (field, [key].value)
# [key].value -> (key, value)
# [one][two] -> (one, [two])
def hide_field_split2(hidden_field: str) -> Tuple[str, str]:
lbracket = hidden_field.find("[")
rbracket = hidden_field.find("]")
dot = hidden_field.find(".")
if lbracket == 0:
# skip past right bracket and any following dot
rest = hidden_field[rbracket + 1 :] # noqa: E203
if rest and rest[0] == ".":
rest = rest[1:]
return (hidden_field[lbracket + 1 : rbracket], rest) # noqa: E203
if lbracket != -1 and (dot == -1 or lbracket < dot):
return (hidden_field[:lbracket], hidden_field[lbracket:])
# hide_field is not hugely sophisticated and designed to cope
# with e.g. status or metadata.managedFields rather than e.g.
# spec.template.spec.containers[0].env[3].value
def hide_field(definition: dict, hidden_field: str) -> dict:
split = hidden_field.split(".", 1)
if len(split) == 1:
return split[0], ""
return split
if split[0] in definition:
if len(split) == 2:
definition[split[0]] = hide_field(definition[split[0]], split[1])
else:
del definition[split[0]]
return definition

View File

@@ -117,34 +117,11 @@ def exists(resource: Optional[ResourceInstance]) -> bool:
return bool(resource) and not empty_list(resource)
def cluster_operator_ready(resource: ResourceInstance) -> bool:
"""
Predicate to check if a single ClusterOperator is healthy.
Returns True if:
- "Available" is True
- "Degraded" is False
- "Progressing" is False
"""
if not resource:
return False
# Extract conditions from the resource's status
conditions = resource.get("status", {}).get("conditions", [])
status = {x.get("type", ""): x.get("status") for x in conditions}
return (
(status.get("Degraded") == "False")
and (status.get("Progressing") == "False")
and (status.get("Available") == "True")
)
RESOURCE_PREDICATES = {
"DaemonSet": daemonset_ready,
"Deployment": deployment_ready,
"Pod": pod_ready,
"StatefulSet": statefulset_ready,
"ClusterOperator": cluster_operator_ready,
}

View File

@@ -1,238 +0,0 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: © Ericsson AB 2024
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r"""
---
module: helm_registry_auth
short_description: Helm registry authentication module
version_added: 5.1.0
author:
- Yuriy Novostavskiy (@yurnov)
requirements:
- "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.
options:
state:
description:
- Desired state of the registry.
- If set to V(present) attempt to log in to the remote registry server using the URL specified in O(host).
- If set to V(absent) attempt to log out from the remote registry server using the URL specified in O(host).
required: false
default: present
choices: ['present', 'absent']
type: str
host:
description:
- Provide a URL for accessing the registry.
required: true
aliases: [ registry_url ]
type: str
insecure:
description:
- Allow connections to SSL sites without certs.
required: false
default: false
type: bool
username:
description:
- Username for the registry.
required: false
type: str
aliases: [ repo_username ]
password:
description:
- Password for the registry.
required: false
type: str
aliases: [ repo_password ]
key_file:
description:
- Path to the client key SSL file for identify registry client using this key file.
required: false
type: path
cert_file:
description:
- Path to the client certificate SSL file for identify registry client using this certificate file.
required: false
type: path
ca_file:
description:
- Path to the CA certificate SSL file for verify registry server certificate.
required: false
type: path
binary_path:
description:
- The path of a helm binary to use.
required: false
type: path
"""
EXAMPLES = r"""
- name: Login to remote registry
kubernetes.core.helm_registry_auth:
username: admin
password: "sample_password"
host: localhost:5000
- name: Logout from remote registry
kubernetes.core.helm_registry_auth:
state: absent
host: localhost:5000
"""
RETURN = r"""
stdout:
type: str
description: Full C(helm) command stdout, in case you want to display it or examine the event log
returned: always
stout_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.
returned: always
sample: 'Login Succeeded\n'
stderr_lines:
type: list
description: Full C(helm) command stderr, in case you want to display it or examine the event log
returned: always
command:
type: str
description: Full C(helm) command executed
returned: always
sample: '/usr/local/bin/helm registry login oci-registry.domain.example --username=admin --password-stdin --insecure'
failed:
type: bool
description: Indicate if the C(helm) command failed
returned: always
sample: false
"""
from ansible_collections.kubernetes.core.plugins.module_utils.helm import (
AnsibleHelmModule,
)
def arg_spec():
return dict(
binary_path=dict(type="path", required=False),
host=dict(type="str", aliases=["registry_url"], required=True),
state=dict(default="present", choices=["present", "absent"], required=False),
insecure=dict(type="bool", default=False, required=False),
username=dict(type="str", aliases=["repo_username"], required=False),
password=dict(
type="str", aliases=["repo_password"], no_log=True, required=False
),
key_file=dict(type="path", required=False),
cert_file=dict(type="path", required=False),
ca_file=dict(type="path", required=False),
)
def login(
command,
host,
insecure,
username,
password,
key_file,
cert_file,
ca_file,
):
login_command = command + " registry login " + host
if username is not None and password is not None:
login_command += " --username=" + username + " --password-stdin"
if insecure:
login_command += " --insecure"
if key_file is not None:
login_command += " --key-file=" + key_file
if cert_file is not None:
login_command += " --cert-file=" + cert_file
if ca_file is not None:
login_command += " --ca-file=" + ca_file
return login_command
def logout(command, host):
return command + " registry logout " + host
def main():
global module
module = AnsibleHelmModule(
argument_spec=arg_spec(),
required_together=[["username", "password"]],
supports_check_mode=True,
)
changed = False
host = module.params.get("host")
state = module.params.get("state")
insecure = module.params.get("insecure")
username = module.params.get("username")
password = module.params.get("password")
key_file = module.params.get("key_file")
cert_file = module.params.get("cert_file")
ca_file = module.params.get("ca_file")
helm_cmd = module.get_helm_binary()
if state == "absent":
helm_cmd = logout(helm_cmd, host)
changed = True
elif state == "present":
helm_cmd = login(
helm_cmd, host, insecure, username, password, key_file, cert_file, ca_file
)
changed = True
if module.check_mode:
module.exit_json(changed=changed, command=helm_cmd)
rc, out, err = module.run_helm_command(
helm_cmd, data=password, fails_on_error=False
)
if rc != 0:
if state == "absent" and "Error: not logged in" in err:
changed = False
else:
module.fail_json(
msg="Failure when executing Helm command. Exited {0}.\nstdout: {1}\nstderr: {2}".format(
rc, out, err
),
stderr=err,
command=helm_cmd,
)
module.exit_json(changed=changed, stdout=out, stderr=err, command=helm_cmd)
if __name__ == "__main__":
main()

View File

@@ -72,13 +72,6 @@ options:
- If the directory already exists, it will be overwritten.
required: false
type: path
insecure_registry:
description:
- Skip TLS certificate checks for the chart download
required: false
type: bool
default: false
version_added: 5.1.0
release_name:
description:
- Release name to use in rendered templates.
@@ -228,7 +221,6 @@ def template(
dependency_update=None,
disable_hook=None,
output_dir=None,
insecure_registry=None,
show_only=None,
release_name=None,
release_namespace=None,
@@ -259,9 +251,6 @@ def template(
if output_dir:
cmd += " --output-dir=" + output_dir
if insecure_registry:
cmd += " --insecure-skip-tls-verify"
if show_only:
for template in show_only:
cmd += " -s " + template
@@ -300,7 +289,6 @@ def main():
include_crds=dict(type="bool", default=False),
release_name=dict(type="str", aliases=["name"]),
output_dir=dict(type="path"),
insecure_registry=dict(type="bool", default=False),
release_namespace=dict(type="str"),
release_values=dict(type="dict", default={}, aliases=["values"]),
show_only=dict(type="list", default=[], elements="str"),
@@ -320,7 +308,6 @@ def main():
include_crds = module.params.get("include_crds")
release_name = module.params.get("release_name")
output_dir = module.params.get("output_dir")
insecure_registry = module.params.get("insecure_registry")
show_only = module.params.get("show_only")
release_namespace = module.params.get("release_namespace")
release_values = module.params.get("release_values")
@@ -350,7 +337,6 @@ def main():
disable_hook=disable_hook,
release_name=release_name,
output_dir=output_dir,
insecure_registry=insecure_registry,
release_namespace=release_namespace,
release_values=release_values,
show_only=show_only,

View File

@@ -57,14 +57,15 @@ options:
- Whether to override the default patch merge approach with a specific type. By default, the strategic
merge will typically be used.
- For example, Custom Resource Definitions typically aren't updatable by the usual strategic merge. You may
want to use C(merge) if you see "strategic merge patch format is not supported".
want to use C(merge) if you see "strategic merge patch format is not supported"
- See U(https://kubernetes.io/docs/tasks/run-application/update-api-object-kubectl-patch/#use-a-json-merge-patch-to-update-a-deployment)
- If more than one C(merge_type) is given, the merge_types will be tried in order. This defaults to
C(['strategic-merge', 'merge']), which is ideal for using the same parameters on resource kinds that
combine Custom Resources and built-in resources.
- Mutually exclusive with C(apply).
- I(merge_type=json) has been removed in version 4.0.0. Please use M(kubernetes.core.k8s_json_patch) instead.
- mutually exclusive with C(apply)
- I(merge_type=json) is deprecated and will be removed in version 4.0.0. Please use M(kubernetes.core.k8s_json_patch) instead.
choices:
- json
- merge
- strategic-merge
type: list
@@ -100,7 +101,7 @@ options:
- C(apply) compares the desired resource definition with the previously supplied resource definition,
ignoring properties that are automatically generated
- C(apply) works better with Services than 'force=yes'
- Mutually exclusive with C(merge_type).
- mutually exclusive with C(merge_type)
default: False
type: bool
template:
@@ -188,8 +189,7 @@ options:
description:
- Hide fields matching this option in the result
- An example might be C(hidden_fields=[metadata.managedFields])
or V(hidden_fields=[spec.containers[0].env[3].value])
or V(hidden_fields=[metadata.annotations[kubectl.kubernetes.io/last-applied-configuration]])
- Only field definitions that don't reference list items are supported (so V(spec.containers[0]) would not work)
type: list
elements: str
version_added: 3.0.0
@@ -460,7 +460,7 @@ def argspec():
argument_spec.update(copy.deepcopy(AUTH_ARG_SPEC))
argument_spec.update(copy.deepcopy(WAIT_ARG_SPEC))
argument_spec["merge_type"] = dict(
type="list", elements="str", choices=["merge", "strategic-merge"]
type="list", elements="str", choices=["json", "merge", "strategic-merge"]
)
argument_spec["validate"] = dict(type="dict", default=None, options=validate_spec())
argument_spec["append_hash"] = dict(type="bool", default=False)

View File

@@ -106,8 +106,7 @@ EXAMPLES = r"""
kubernetes.core.k8s_drain:
state: drain
name: foo
delete_options:
force: yes
force: yes
- name: Drain node "foo", but abort if there are pods not managed by a ReplicationController, Job, or DaemonSet, and use a grace period of 15 minutes.
kubernetes.core.k8s_drain:

View File

@@ -135,7 +135,7 @@ from ansible.module_utils._text import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
AnsibleModule,
)
from ansible_collections.kubernetes.core.plugins.module_utils.args_common import (
from ansible_collections.kubernetes.core.plugins.module_utils.common import (
AUTH_ARG_SPEC,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
@@ -219,6 +219,12 @@ def execute_module(module, client):
else:
rc = int(err["details"]["causes"][0]["message"])
module.deprecate(
"The 'return_code' return key is being renamed to 'rc'. "
"Both keys are being returned for now to allow users to migrate their automation.",
version="4.0.0",
collection_name="kubernetes.core",
)
module.exit_json(
# Some command might change environment, but ultimately failing at end
changed=True,

View File

@@ -48,8 +48,7 @@ options:
description:
- Hide fields matching any of the field definitions in the result
- An example might be C(hidden_fields=[metadata.managedFields])
or V(hidden_fields=[spec.containers[0].env[3].value])
or V(hidden_fields=[metadata.annotations[kubectl.kubernetes.io/last-applied-configuration]])
- Only field definitions that don't reference list items are supported (so V(spec.containers[0]) would not work)
type: list
elements: str
version_added: 3.0.0

View File

@@ -73,7 +73,7 @@
assert:
that:
- install is changed
- install.status.chart == chart_test+"-"+chart_test_version
- install.status.chart == "{{ chart_test }}-{{ chart_test_version }}"
- install.status.status | lower == 'deployed'
- name: Check helm_info content
@@ -95,7 +95,7 @@
- name: "Assert that {{ chart_test }} is installed from {{ source }} with helm_info"
assert:
that:
- content_info.status.chart == chart_test+"-"+chart_test_version
- content_info.status.chart == "{{ chart_test }}-{{ chart_test_version }}"
- content_info.status.status | lower == 'deployed'
- release_state_content_info.status.status | lower == 'deployed'
@@ -112,7 +112,7 @@
assert:
that:
- install is not changed
- install.status.chart == chart_test+"-"+chart_test_version
- install.status.chart == "{{ chart_test }}-{{ chart_test_version }}"
- install.status.status | lower == 'deployed'
- name: "Add vars to {{ chart_test }} from {{ source }}"
@@ -130,7 +130,7 @@
that:
- install is changed
- install.status.status | lower == 'deployed'
- install.status.chart == chart_test+"-"+chart_test_version
- install.status.chart == "{{ chart_test }}-{{ chart_test_version }}"
- "install.status['values'].revisionHistoryLimit == 0"
- name: Check idempotency after adding vars
@@ -148,7 +148,7 @@
that:
- install is not changed
- install.status.status | lower == 'deployed'
- install.status.chart == chart_test+"-"+chart_test_version
- install.status.chart == "{{ chart_test }}-{{ chart_test_version }}"
- "install.status['values'].revisionHistoryLimit == 0"
- name: "Remove Vars to {{ chart_test }} from {{ source }}"
@@ -165,7 +165,7 @@
that:
- install is changed
- install.status.status | lower == 'deployed'
- install.status.chart == chart_test+"-"+chart_test_version
- install.status.chart == "{{ chart_test }}-{{ chart_test_version }}"
- install.status['values'] == {}
- name: Check idempotency after removing vars
@@ -182,7 +182,7 @@
that:
- install is not changed
- install.status.status | lower == 'deployed'
- install.status.chart == chart_test+"-"+chart_test_version
- install.status.chart == "{{ chart_test }}-{{ chart_test_version }}"
- install.status['values'] == {}
- name: "Upgrade {{ chart_test }} from {{ source }}"
@@ -199,7 +199,7 @@
that:
- install is changed
- install.status.status | lower == 'deployed'
- install.status.chart == chart_test+"-"+chart_test_version_upgrade
- install.status.chart == "{{ chart_test }}-{{ chart_test_version_upgrade }}"
- name: Check idempotency after upgrade
helm:
@@ -215,7 +215,7 @@
that:
- install is not changed
- install.status.status | lower == 'deployed'
- install.status.chart == chart_test+"-"+chart_test_version_upgrade
- install.status.chart == "{{ chart_test }}-{{ chart_test_version_upgrade }}"
- name: "Remove {{ chart_test }} from {{ source }}"
helm:
@@ -316,7 +316,7 @@
that:
- install is changed
- install.status.status | lower == 'deployed'
- install.status.chart == chart_test+"-"+chart_test_version
- install.status.chart == "{{ chart_test }}-{{ chart_test_version }}"
- "install.status['values'].revisionHistoryLimit == 0"
- name: "Install {{ chart_test }} from {{ source }} with values_files (again)"
@@ -357,7 +357,7 @@
- result is changed
- result is not failed
- result.rc == 0
- result.command is match(helm_binary+" template "+chart_source)
- result.command is match("{{ helm_binary }} template {{ chart_source }}")
- name: Check templates created
stat:

View File

@@ -1,2 +0,0 @@
time=16
helm_registry_auth

View File

@@ -1,9 +0,0 @@
---
# Username and password for the registry
# ../files/registry.password contains username and hashed password
username: testuser
password: testpassword
wrong_password: 'WrongPassword'
registry_name: oci_registry
registry_port: 5000
test_chart: https://github.com/grafana/helm-charts/releases/download/k8s-monitoring-1.6.8/k8s-monitoring-1.6.8.tgz

View File

@@ -1 +0,0 @@
testuser:$2y$05$PmdUjSCJYdRUZlsYy8QGWuJDiwuHtWXa28YrELlN5haeHkZ1seZZG

View File

@@ -1,3 +0,0 @@
---
dependencies:
- install_helm

View File

@@ -1,7 +0,0 @@
---
- name: Test helm_registry_auth module
hosts: localhost
connection: local
gather_facts: true
roles:
- helm_registry_auth

View File

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

View File

@@ -1,178 +0,0 @@
---
- name: Run module test
# using a shell and command module to run the test as test can be non-idempotent
# and it allow to not install any additional dependencies
block:
- name: Ensure that helm is installed
ansible.builtin.shell: helm version --client --short | grep v3
register: _helm_version
failed_when: _helm_version.rc != 0
- name: Ensure that Docker demon is running
ansible.builtin.command: "docker info"
register: _docker_info
failed_when: _docker_info.rc != 0
- name: Create a tmpfile htpasswd directory
ansible.builtin.tempfile:
state: directory
suffix: .httppasswd
register: _tmpfile
- name: Copy htpasswd to the tmpfile directory
ansible.builtin.copy:
src: registry.password
dest: "{{ _tmpfile.path }}/registry.password"
- name: Setup the registry
ansible.builtin.command: >-
docker run -d --rm
-p {{ registry_port }}:5000
--name "{{ registry_name }}"
-v "{{ _tmpfile.path }}:/auth"
-e "REGISTRY_AUTH=htpasswd"
-e "REGISTRY_AUTH_HTPASSWD_REALM=Registry Realm"
-e REGISTRY_AUTH_HTPASSWD_PATH=/auth/registry.password
registry:2
register: _setup_registry
failed_when: _setup_registry.rc != 0
- name: Ensure that the registry is running and rechable
ansible.builtin.wait_for:
host: localhost
port: "{{ registry_port }}"
- name: Test the registry with correct credentials to ensure that the registry is running
ansible.builtin.shell: >-
echo {{ password | quote }} | helm registry login localhost:{{ registry_port }}
-u {{ username }} --password-stdin
register: _login_correct
failed_when: _login_correct.rc != 0
- name: Clean up credentials to run test on clean environment
ansible.builtin.shell: >-
helm registry logout localhost:{{ registry_port }}
register: _logout
failed_when: _logout.rc != 0
- name: Create directory for helm chart
ansible.builtin.tempfile:
state: directory
suffix: ".helm"
register: _destination
- name: Pull test helm chart
ansible.builtin.uri:
url: "{{ test_chart }}"
dest: "{{ _destination.path }}/k8s-monitoring-1.6.8.tgz"
return_content: no
status_code: 200
- name: Test module helm_registry_auth with correct credentials
helm_registry_auth:
username: "{{ username }}"
password: "{{ password }}"
host: localhost:{{ registry_port }}
state: present
register: _helm_registry_auth_correct
- name: Assert that the registry is logged in
# Helm binary prints the message to stderr, refence: https://github.com/helm/helm/issues/13464
assert:
that:
- "'Login Succeeded' in _helm_registry_auth_correct.stderr"
- "'{{ password }}' not in _helm_registry_auth_correct.command"
- "'{{ password }}' not in _helm_registry_auth_correct.stdout"
- "'{{ password }}' not in _helm_registry_auth_correct.stderr"
- name: Ensure that push to the registry is working
ansible.builtin.shell: >-
helm push "{{ _destination.path }}/k8s-monitoring-1.6.8.tgz" oci://localhost:{{ registry_port }}/test/
register: _save_chart
failed_when: _save_chart.rc != 0
- name: Assert that the chart is saved
# Helm binary prints the message to stderr, refence: https://github.com/helm/helm/issues/13464
assert:
that: "'Pushed: localhost:{{ registry_port }}/test/k8s-monitoring' in _save_chart.stderr"
- name: Test logout
helm_registry_auth:
host: localhost:{{ registry_port }}
state: absent
register: _helm_registry_auth_logout
- name: Assert logout
# Helm binary prints the message to stderr
assert:
that: "'Removing login credentials' in _helm_registry_auth_logout.stderr"
- name: Test logout idempotency
helm_registry_auth:
host: localhost:{{ registry_port }}
state: absent
register: _helm_registry_auth_logout_idempotency
- name: Assert logout operation did not report change
ansible.builtin.assert:
that: _helm_registry_auth_logout_idempotency is not changed
- name: Ensure that not able to push to the registry
ansible.builtin.shell: >-
helm push "{{ _destination.path }}/k8s-monitoring-1.6.8.tgz" oci://localhost:{{ registry_port }}/test/
register: _save_chart
failed_when: _save_chart.rc == 0
- name: Read content of ~/.config/helm/registry/config.json
ansible.builtin.slurp:
src: ~/.config/helm/registry/config.json
register: _config_json
- name: Assert that auth data is remove and the chart is not saved
# Helm binary prints the message to stderr
ansible.builtin.assert:
that:
- "'push access denied' in _save_chart.stderr"
- "'authorization failed' in _save_chart.stderr"
- "_save_chart.rc != 0"
- "'localhost:{{ registry_port }}' not in _config_json.content | b64decode"
- name: Test module helm_registry_auth with wrong credentials
helm_registry_auth:
username: "{{ username }}"
password: "{{ wrong_password }}"
host: localhost:{{ registry_port }}
state: present
register: _helm_registry_auth_wrong
ignore_errors: true
- name: Read content of ~/.config/helm/registry/config.json
ansible.builtin.slurp:
src: ~/.config/helm/registry/config.json
register: _config_json
- name: Assert that the registry is not logged in and auth data is not saved
ansible.builtin.assert:
that:
- "'401 Unauthorized' in _helm_registry_auth_wrong.stderr"
- "'{{ wrong_password }}' not in _helm_registry_auth_correct.command"
- "'{{ wrong_password }}' not in _helm_registry_auth_correct.stdout"
- "'{{ wrong_password }}' not in _helm_registry_auth_correct.stderr"
- "'localhost:{{ registry_port }}' not in _config_json.content | b64decode"
# Clean up
always:
- name: Stop and remove the registry
ansible.builtin.command: docker stop {{ registry_name }}
ignore_errors: true
- name: Remove the tmpfile
ansible.builtin.file:
state: absent
path: "{{ item }}"
force: true
loop:
- "{{ _tmpfile.path }}"
- "{{ _destination.path }}"
ignore_errors: true

View File

@@ -26,7 +26,8 @@
assert:
that:
- k8s_configmap is changed
- k8s_configmap.result.metadata.annotations|default(False)
- '"annotations" in k8s_configmap.result.metadata'
- k8s_configmap.result.metadata.annotations != {}
- name: Add same configmap again
k8s:
@@ -467,7 +468,7 @@
assert:
that:
- k8s_secret is changed
- k8s_secret.result.data.foo
- k8s_secret.result.data.foo != ""
- name: Add same secret
k8s:
@@ -748,7 +749,7 @@
assert:
that:
- _create is changed
- not _info.resources
- _info.resources | length == 0
# server side apply over kubernetes client releases
- name: Create temporary directory

View File

@@ -38,7 +38,7 @@
- name: Assert that there are pods
assert:
that:
- pods_create.resources
- pods_create.resources | length > 0
- name: Remove the daemonset
k8s:
@@ -74,7 +74,7 @@
- name: Assert that deleting the daemonset deleted the pods
assert:
that:
- not pods_delete.resources
- pods_delete.resources | length == 0
# test deletion using label selector
- name: Deploy load balancer
@@ -152,6 +152,27 @@
register: _deployment
failed_when: _deployment.resources | length == 0
- name: Trying to delete nginx deployment in check mode and with deleteOptions set
k8s:
kind: Deployment
api_version: apps/v1
namespace: "{{ test_namespace }}"
name: nginx-d
state: absent
delete_options:
propagationPolicy: Foreground
check_mode: true
register: _delete
- name: Validate that Deployment nginx-d still exists
k8s_info:
kind: Deployment
api_version: apps/v1
namespace: "{{ test_namespace }}"
name: nginx-d
register: _deployment
failed_when: _deployment.resources | length != 1
- name: Trying to delete using delete_all=true but missing kind option
k8s:
api_version: apps/v1

View File

@@ -182,7 +182,7 @@
- name: assert that pods are running on cordoned node
assert:
that:
- Pod.resources | selectattr('status.phase', 'equalto', 'Running') | selectattr('spec.nodeName', 'equalto', node_to_drain) | list | length > 0
- "{{ Pod.resources | selectattr('status.phase', 'equalto', 'Running') | selectattr('spec.nodeName', 'equalto', node_to_drain) | list | length > 0 }}"
- name: Uncordon node
k8s_drain:
@@ -236,7 +236,7 @@
assert:
that:
- drain_result is changed
- '"node "+node_to_drain+" marked unschedulable." in drain_result.result'
- '"node {{ node_to_drain }} marked unschedulable." in drain_result.result'
- name: assert that unmanaged pod were deleted
k8s_info:
@@ -244,7 +244,7 @@
kind: Pod
name: '{{ drain_pod_name }}'
register: _result
failed_when: _result.resources
failed_when: _result.resources | length > 0
- name: assert that emptyDir pod was deleted
k8s_info:
@@ -338,7 +338,7 @@
assert:
that:
- disable_evict is changed
- '"node "+node_to_drain+" marked unschedulable." in disable_evict.result'
- '"node {{ node_to_drain }} marked unschedulable." in disable_evict.result'
- name: assert that unmanaged pod were deleted
k8s_info:
@@ -346,7 +346,7 @@
kind: Pod
name: '{{ drain_pod_name }}-01'
register: _result
failed_when: _result.resources
failed_when: _result.resources | length > 0
# test: drain using pod_selectors
- name: Uncordon node
@@ -401,7 +401,7 @@
assert:
that:
- drain_pod_selector is changed
- '"node "+node_to_drain+" marked unschedulable." in drain_pod_selector.result'
- '"node {{ node_to_drain }} marked unschedulable." in drain_pod_selector.result'
- name: assert that pod created before is still running
k8s_info:
@@ -429,8 +429,8 @@
assert:
that:
- drain_pod_selector_equal is changed
- '"node "+node_to_drain+" already marked unschedulable." in drain_pod_selector_equal.result'
- '"Deleting Pods not managed by ReplicationController, ReplicaSet, Job, DaemonSet or StatefulSet: "+test_namespace+"/ansible-drain-pod." in drain_pod_selector_equal.warnings'
- '"node {{ node_to_drain }} already marked unschedulable." in drain_pod_selector_equal.result'
- '"Deleting Pods not managed by ReplicationController, ReplicaSet, Job, DaemonSet or StatefulSet: {{ test_namespace }}/ansible-drain-pod." in drain_pod_selector_equal.warnings'
- name: Uncordon node
k8s_drain:

View File

@@ -394,9 +394,11 @@
register: k8s_info_testing6
failed_when: not k8s_info_testing6.resources or k8s_info_testing6.resources[0].status.phase != "Active"
- name: Create large configmap data
command: dd if=/dev/urandom bs=500K count=1
register: cmap_data
- name: Create a file with specific size and attributes, to be used as swap space
community.general.filesize:
path: /tmp/configmap.bin
size: 500K
source: /dev/urandom
- name: Create configmap with large value
k8s:
@@ -407,7 +409,7 @@
name: testmap
namespace: testing
data:
testkey: "{{ cmap_data.stdout | b64encode }}"
testkey: "{{ lookup('file', '/tmp/configmap.bin') | b64encode }}"
wait: true
register: result
@@ -424,7 +426,7 @@
- assert:
that:
- result.resources[0].data.testkey == (cmap_data.stdout | b64encode)
- result.resources[0].data.testkey == (lookup('file', '/tmp/configmap.bin') | b64encode)
# test setting module defaults for kubernetes.core.k8s_info
- block:

View File

@@ -36,7 +36,7 @@
label_selectors:
- "job=gc"
register: wait_job
until: wait_job.resources
until: wait_job.resources | length > 0
retries: 5
delay: 10
@@ -87,7 +87,7 @@
label_selectors:
- "job=gc"
register: wait_job
until: wait_job.resources
until: wait_job.resources | length > 0
retries: 5
delay: 10
@@ -139,7 +139,7 @@
label_selectors:
- "job=gc"
register: wait_job
until: wait_job.resources
until: wait_job.resources | length > 0
retries: 5
delay: 10
@@ -225,7 +225,7 @@
- name: Assert job is deleted
assert:
that: not job.resources
that: job.resources | length == 0
always:
- name: Delete namespace

View File

@@ -69,7 +69,7 @@
- name: assert pod has been created
assert:
that:
- pods.resources | length == 1
- "{{ pods.resources | length == 1 }}"
- name: create pod using generate_name parameter should succeed
k8s:
@@ -86,7 +86,7 @@
- name: assert pod has been created
assert:
that:
- pods.resources | length == 2
- "{{ pods.resources | length == 2 }}"
- name: create pod using metadata.generateName parameter should succeed
k8s:
@@ -102,7 +102,7 @@
- name: assert pod has been created
assert:
that:
- pods.resources | length == 3
- "{{ pods.resources | length == 3 }}"
- name: create object using metadata.generateName should support wait option
k8s:

View File

@@ -77,7 +77,6 @@
definition: "{{ hide_fields_base_configmap | combine({'data':{'anew':'value'}}) }}"
hidden_fields:
- data
- metadata.annotations[kubectl.kubernetes.io/last-applied-configuration]
apply: true
register: hf6
diff: true
@@ -87,22 +86,6 @@
that:
- hf6.changed
- name: Ensure hidden fields are not present
assert:
that:
- >-
'annotations' not in hf6.result.metadata or
'kubectl.kubernetes.io/last-applied-configuration'
not in hf6.result.metadata.annotations
- >-
'annotations' not in hf6.diff.before.metadata or
'kubectl.kubernetes.io/last-applied-configuration'
not in hf6.diff.before.metadata.annotations
- >-
'annotations' not in hf6.diff.after.metadata or
'kubectl.kubernetes.io/last-applied-configuration'
not in hf6.diff.after.metadata.annotations
- name: Hidden field should not show up in deletion
k8s:
definition: "{{ hide_fields_base_configmap}}"

View File

@@ -47,7 +47,7 @@
- result.changed
- result.result.metadata.labels.label2 == "bar"
- result.result.spec.containers[0].image == "busybox:glibc"
- result.diff
- result.diff != {}
- name: Describe pod
kubernetes.core.k8s_info:

View File

@@ -11,7 +11,7 @@
assert:
that:
- fake_pod is failed
- fake_pod.msg == "Pod "+test_namespace+"/this_pod_does_exist not found."
- 'fake_pod.msg == "Pod {{ test_namespace }}/this_pod_does_exist not found."'
- name: create hello-world deployment
k8s:

View File

@@ -129,7 +129,7 @@
that:
- scale_down is changed
- '"duration" in scale_down'
- scale_down.diff
- scale_down.diff != {}
- name: Scale the deployment once again (idempotency)
k8s_scale:
@@ -274,7 +274,7 @@
assert:
that:
- scale_down_no_wait is changed
- scale_down_no_wait.diff
- scale_down_no_wait.diff != {}
- scale_down_no_wait_pods.resources | length == 1
# scale multiple resource using label selectors

View File

@@ -65,7 +65,7 @@
assert:
that:
- _result.result.status.phase == 'Running'
- _result.result.spec.nodeName == node_to_taint
- _result.result.spec.nodeName == "{{ node_to_taint }}"
- name: Taint node (check_mode)
kubernetes.core.k8s_taint:
@@ -89,8 +89,8 @@
assert:
that:
- _result.changed
- item['effect'] == taint_patch_1[0]['effect']
- item['key'] == taint_patch_1[0]['key']
- "{{ item['effect'] == taint_patch_1[0]['effect'] }}"
- "{{ item['key'] == taint_patch_1[0]['key'] }}"
loop: "{{ _result.result.spec.taints }}"
- name: Taint node (idempotency) - (check_mode)
@@ -421,7 +421,7 @@
- name: Assert that taints have been removed
assert:
that:
- _result.resources | selectattr('spec.taints', 'undefined')
- _result.resources | selectattr('spec.taints', 'undefined') | list | length > 0
always:

View File

@@ -7,7 +7,7 @@
kubernetes.core.k8s_service:
template: "pod_one.j2"
state: present
ignore_errors: yes
ignore_errors: true
register: r
- name: Check for expected failures in last tasks
@@ -35,7 +35,7 @@
k8s_pod_name_one: pod
k8s_pod_namespace: "{{ template_namespace }}"
register: r
ignore_errors: yes
ignore_errors: true
- name: Check if definition and template are mutually exclusive
assert:
@@ -52,7 +52,7 @@
k8s_pod_name_one: pod
k8s_pod_namespace: "{{ template_namespace }}"
register: r
ignore_errors: yes
ignore_errors: true
- name: Check if src and template are mutually exclusive
assert:
@@ -63,7 +63,7 @@
- name: Create pod using template (direct specification)
kubernetes.core.k8s:
template: "pod_one.j2"
wait: yes
wait: true
wait_timeout: "{{ k8s_wait_timeout | default(omit) }}"
vars:
k8s_pod_name_one: pod-1
@@ -79,7 +79,7 @@
kubernetes.core.k8s:
template:
- default
wait: yes
wait: true
wait_timeout: "{{ k8s_wait_timeout | default(omit) }}"
vars:
k8s_pod_name_one: pod-2
@@ -96,7 +96,7 @@
kubernetes.core.k8s:
template:
path: "pod_one.j2"
wait: yes
wait: true
wait_timeout: "{{ k8s_wait_timeout | default(omit) }}"
vars:
k8s_pod_name_one: pod-3
@@ -114,12 +114,11 @@
path: "pod_two.j2"
variable_start_string: '[['
variable_end_string: ']]'
wait: yes
wait: true
wait_timeout: "{{ k8s_wait_timeout | default(omit) }}"
vars:
k8s_pod_name_two: pod-4
k8s_pod_namespace: "[[ template_namespace ]]"
ansible_python_interpreter: "[[ ansible_playbook_python ]]"
k8s_pod_namespace: "template-test"
register: r
- name: Assert that pod creation succeeded using template
@@ -131,7 +130,7 @@
kubernetes.core.k8s:
template:
path: "pod_three.j2"
wait: yes
wait: true
wait_timeout: "{{ k8s_wait_timeout | default(omit) }}"
vars:
k8s_pod_name_three_one: pod-5
@@ -152,7 +151,7 @@
variable_start_string: '[['
variable_end_string: ']]'
- path: "pod_three.j2"
wait: yes
wait: true
wait_timeout: "{{ k8s_wait_timeout | default(omit) }}"
vars:
k8s_pod_name_one: pod-7
@@ -213,8 +212,8 @@
- name: check that resources creation failed
assert:
that:
- resource.results.0.resources | length == 0
- resource.results.1.resources | length == 0
- '{{ resource.results[0].resources | length == 0 }}'
- '{{ resource.results[1].resources | length == 0 }}'
- name: create pod without namespace (continue_on_error = true)
kubernetes.core.k8s:
@@ -239,63 +238,6 @@
- resource.result.results | selectattr('changed') | list | length == 1
- resource.result.results | selectattr('error', 'defined') | list | length == 1
# Test resource definition using template with 'omit'
- name: Deploy configmap using template
k8s:
namespace: "{{ template_namespace }}"
name: test-data
template: configmap.yml.j2
- name: Read configmap created
k8s_info:
kind: configmap
namespace: "{{ template_namespace }}"
name: test-data
register: _configmap
- name: Validate that the configmap does not contains annotations
assert:
that:
- '"annotations" not in _configmap.resources.0.metadata'
- name: Create resource once again
k8s:
namespace: "{{ template_namespace }}"
name: test-data
template: configmap.yml.j2
register: _configmap
- name: assert that nothing changed
assert:
that:
- _configmap is not changed
- name: Create resource once again (using description)
k8s:
namespace: "{{ template_namespace }}"
name: test-data
template: configmap.yml.j2
register: _configmap
vars:
k8s_configmap_desc: "This is a simple configmap used to test ansible k8s collection"
- name: assert that configmap was changed
assert:
that:
- _configmap is changed
- name: Read configmap created
k8s_info:
kind: configmap
namespace: "{{ template_namespace }}"
name: test-data
register: _configmap
- name: Validate that the configmap does not contains annotations
assert:
that:
- _configmap.resources.0.metadata.annotations.description == "This is a simple configmap used to test ansible k8s collection"
always:
- name: Remove namespace (Cleanup)
kubernetes.core.k8s:

View File

@@ -1,7 +0,0 @@
apiVersion: v1
kind: ConfigMap
metadata:
annotations:
description: "{{ k8s_configmap_desc | default(omit) }}"
data:
key: "testing-template"

View File

@@ -56,8 +56,8 @@
# Without wantlist=True lookup should return mapping
- test5 is mapping
- test6 is mapping
# errors='ignore'
- test7 is string
# errors='ignore' (return null with ansible-core 2.19)
- test7 is string or not test7
- test8 is not defined
- name: Create another namespace with label
@@ -130,9 +130,9 @@
assert:
that:
- result_configmap.apiVersion == 'v1'
- result_configmap.metadata.name == configmap_name
- result_configmap.metadata.namespace == test_namespace[2]
- result_configmap.data.value == configmap_data
- result_configmap.metadata.name == "{{ configmap_name }}"
- result_configmap.metadata.namespace == "{{ test_namespace[2] }}"
- result_configmap.data.value == "{{ configmap_data }}"
# test lookup plugin using src parameter
- block:
@@ -159,9 +159,9 @@
assert:
that:
- src_configmap.apiVersion == 'v1'
- src_configmap.metadata.name == configmap_name
- src_configmap.metadata.namespace == test_namespace[2]
- src_configmap.data.value == configmap_data
- src_configmap.metadata.name == "{{ configmap_name }}"
- src_configmap.metadata.namespace == "{{ test_namespace[2] }}"
- src_configmap.data.value == "{{ configmap_data }}"
always:
- name: Delete temporary file created
@@ -198,9 +198,9 @@
assert:
that:
- configmap_no_ssl.apiVersion == 'v1'
- configmap_no_ssl.metadata.name == configmap_name
- configmap_no_ssl.metadata.namespace == test_namespace[2]
- configmap_no_ssl.data.value == configmap_data
- configmap_no_ssl.metadata.name == "{{ configmap_name }}"
- configmap_no_ssl.metadata.namespace == "{{ test_namespace[2] }}"
- configmap_no_ssl.data.value == "{{ configmap_data }}"
- name: Retrieve configmap using authentication aliases (validate_certs=true)
set_fact:
@@ -210,9 +210,9 @@
assert:
that:
- configmap_with_ssl.apiVersion == 'v1'
- configmap_with_ssl.metadata.name == configmap_name
- configmap_with_ssl.metadata.namespace == test_namespace[2]
- configmap_with_ssl.data.value == configmap_data
- configmap_with_ssl.metadata.name == "{{ configmap_name }}"
- configmap_with_ssl.metadata.namespace == "{{ test_namespace[2] }}"
- configmap_with_ssl.data.value == "{{ configmap_data }}"
always:
- name: Delete temporary directory

View File

@@ -4,10 +4,17 @@
namespace_to_create: "{{ item.name | default(item) }}"
namespace_labels: "{{ item.labels | default(omit) }}"
with_items: "{{ test_namespace }}"
when: test_namespace | type_debug == "list"
when:
- test_namespace is not string
- test_namespace is not mapping
- test_namespace is iterable
- include_tasks: tasks/create.yml
vars:
namespace_to_create: "{{ test_namespace }}"
namespace_labels: "{{ test_namespace_labels | default(omit) }}"
when: test_namespace | type_debug == "AnsibleUnicode"
when:
- test_namespace is string
- test_namespace is iterable
- test_namespace is sequence
- test_namespace is not mapping

View File

@@ -1,16 +1,24 @@
plugins/module_utils/client/discovery.py import-3.6!skip
plugins/module_utils/client/discovery.py import-3.7!skip
plugins/module_utils/client/discovery.py import-3.8!skip
plugins/module_utils/client/discovery.py import-3.9!skip
plugins/module_utils/client/discovery.py import-3.10!skip
plugins/module_utils/client/discovery.py import-3.11!skip
plugins/module_utils/client/resource.py import-3.6!skip
plugins/module_utils/client/resource.py import-3.7!skip
plugins/module_utils/client/resource.py import-3.8!skip
plugins/module_utils/client/resource.py import-3.9!skip
plugins/module_utils/client/resource.py import-3.10!skip
plugins/module_utils/client/resource.py import-3.11!skip
plugins/module_utils/k8sdynamicclient.py import-3.6!skip
plugins/module_utils/k8sdynamicclient.py import-3.7!skip
plugins/module_utils/k8sdynamicclient.py import-3.8!skip
plugins/module_utils/k8sdynamicclient.py import-3.9!skip
plugins/module_utils/k8sdynamicclient.py import-3.10!skip
plugins/module_utils/k8sdynamicclient.py import-3.11!skip
plugins/modules/k8s.py validate-modules:parameter-type-not-in-doc
plugins/modules/k8s_scale.py validate-modules:parameter-type-not-in-doc
plugins/modules/k8s_service.py validate-modules:parameter-type-not-in-doc
tests/unit/module_utils/fixtures/clusteroperator.yml yamllint!skip
tests/unit/module_utils/fixtures/definitions.yml yamllint!skip
tests/unit/module_utils/fixtures/deployments.yml yamllint!skip
tests/unit/module_utils/fixtures/pods.yml yamllint!skip
@@ -26,6 +34,4 @@ plugins/modules/k8s_service.py validate-modules:return-syntax-error
plugins/modules/k8s_taint.py validate-modules:return-syntax-error
tests/integration/targets/k8s_delete/files/deployments.yaml yamllint!skip
tests/integration/targets/helm_diff/files/test-chart-reuse-values/templates/configmap.yaml yamllint!skip
tests/integration/targets/helm_registry_auth/tasks/main.yaml yamllint!skip
tests/integration/targets/helm_diff/files/test-chart-deployment-time/templates/configmap.yaml yamllint!skip

View File

@@ -1,9 +1,18 @@
plugins/module_utils/client/discovery.py import-3.6!skip
plugins/module_utils/client/discovery.py import-3.7!skip
plugins/module_utils/client/discovery.py import-3.8!skip
plugins/module_utils/client/discovery.py import-3.9!skip
plugins/module_utils/client/discovery.py import-3.10!skip
plugins/module_utils/client/discovery.py import-3.11!skip
plugins/module_utils/client/resource.py import-3.6!skip
plugins/module_utils/client/resource.py import-3.7!skip
plugins/module_utils/client/resource.py import-3.8!skip
plugins/module_utils/client/resource.py import-3.9!skip
plugins/module_utils/client/resource.py import-3.10!skip
plugins/module_utils/client/resource.py import-3.11!skip
plugins/module_utils/k8sdynamicclient.py import-3.6!skip
plugins/module_utils/k8sdynamicclient.py import-3.7!skip
plugins/module_utils/k8sdynamicclient.py import-3.8!skip
plugins/module_utils/k8sdynamicclient.py import-3.9!skip
plugins/module_utils/k8sdynamicclient.py import-3.10!skip
plugins/module_utils/k8sdynamicclient.py import-3.11!skip
@@ -11,7 +20,6 @@ plugins/module_utils/version.py pylint!skip
plugins/modules/k8s.py validate-modules:parameter-type-not-in-doc
plugins/modules/k8s_scale.py validate-modules:parameter-type-not-in-doc
plugins/modules/k8s_service.py validate-modules:parameter-type-not-in-doc
tests/unit/module_utils/fixtures/clusteroperator.yml yamllint!skip
tests/unit/module_utils/fixtures/definitions.yml yamllint!skip
tests/unit/module_utils/fixtures/deployments.yml yamllint!skip
tests/integration/targets/k8s_delete/files/deployments.yaml yamllint!skip
@@ -27,5 +35,4 @@ plugins/modules/k8s_scale.py validate-modules:return-syntax-error
plugins/modules/k8s_service.py validate-modules:return-syntax-error
plugins/modules/k8s_taint.py validate-modules:return-syntax-error
tests/integration/targets/helm_diff/files/test-chart-reuse-values/templates/configmap.yaml yamllint!skip
tests/integration/targets/helm_registry_auth/tasks/main.yaml yamllint!skip
tests/integration/targets/helm_diff/files/test-chart-deployment-time/templates/configmap.yaml yamllint!skip

View File

@@ -1,11 +1,20 @@
plugins/module_utils/client/discovery.py import-3.6!skip
plugins/module_utils/client/discovery.py import-3.7!skip
plugins/module_utils/client/discovery.py import-3.8!skip
plugins/module_utils/client/discovery.py import-3.9!skip
plugins/module_utils/client/discovery.py import-3.10!skip
plugins/module_utils/client/discovery.py import-3.11!skip
plugins/module_utils/client/discovery.py import-3.12!skip
plugins/module_utils/client/resource.py import-3.6!skip
plugins/module_utils/client/resource.py import-3.7!skip
plugins/module_utils/client/resource.py import-3.8!skip
plugins/module_utils/client/resource.py import-3.9!skip
plugins/module_utils/client/resource.py import-3.10!skip
plugins/module_utils/client/resource.py import-3.11!skip
plugins/module_utils/client/resource.py import-3.12!skip
plugins/module_utils/k8sdynamicclient.py import-3.6!skip
plugins/module_utils/k8sdynamicclient.py import-3.7!skip
plugins/module_utils/k8sdynamicclient.py import-3.8!skip
plugins/module_utils/k8sdynamicclient.py import-3.9!skip
plugins/module_utils/k8sdynamicclient.py import-3.10!skip
plugins/module_utils/k8sdynamicclient.py import-3.11!skip
@@ -14,7 +23,6 @@ plugins/module_utils/version.py pylint!skip
plugins/modules/k8s.py validate-modules:parameter-type-not-in-doc
plugins/modules/k8s_scale.py validate-modules:parameter-type-not-in-doc
plugins/modules/k8s_service.py validate-modules:parameter-type-not-in-doc
tests/unit/module_utils/fixtures/clusteroperator.yml yamllint!skip
tests/unit/module_utils/fixtures/definitions.yml yamllint!skip
tests/unit/module_utils/fixtures/deployments.yml yamllint!skip
tests/integration/targets/k8s_delete/files/deployments.yaml yamllint!skip
@@ -30,5 +38,4 @@ plugins/modules/k8s_scale.py validate-modules:return-syntax-error
plugins/modules/k8s_service.py validate-modules:return-syntax-error
plugins/modules/k8s_taint.py validate-modules:return-syntax-error
tests/integration/targets/helm_diff/files/test-chart-reuse-values/templates/configmap.yaml yamllint!skip
tests/integration/targets/helm_registry_auth/tasks/main.yaml yamllint!skip
tests/integration/targets/helm_diff/files/test-chart-deployment-time/templates/configmap.yaml yamllint!skip

View File

@@ -14,7 +14,6 @@ plugins/module_utils/version.py pylint!skip
plugins/modules/k8s.py validate-modules:parameter-type-not-in-doc
plugins/modules/k8s_scale.py validate-modules:parameter-type-not-in-doc
plugins/modules/k8s_service.py validate-modules:parameter-type-not-in-doc
tests/unit/module_utils/fixtures/clusteroperator.yml yamllint!skip
tests/unit/module_utils/fixtures/definitions.yml yamllint!skip
tests/unit/module_utils/fixtures/deployments.yml yamllint!skip
tests/integration/targets/k8s_delete/files/deployments.yaml yamllint!skip
@@ -30,5 +29,4 @@ plugins/modules/k8s_scale.py validate-modules:return-syntax-error
plugins/modules/k8s_service.py validate-modules:return-syntax-error
plugins/modules/k8s_taint.py validate-modules:return-syntax-error
tests/integration/targets/helm_diff/files/test-chart-reuse-values/templates/configmap.yaml yamllint!skip
tests/integration/targets/helm_registry_auth/tasks/main.yaml yamllint!skip
tests/integration/targets/helm_diff/files/test-chart-deployment-time/templates/configmap.yaml yamllint!skip

View File

@@ -11,7 +11,6 @@ plugins/module_utils/version.py pylint!skip
plugins/modules/k8s.py validate-modules:parameter-type-not-in-doc
plugins/modules/k8s_scale.py validate-modules:parameter-type-not-in-doc
plugins/modules/k8s_service.py validate-modules:parameter-type-not-in-doc
tests/unit/module_utils/fixtures/clusteroperator.yml yamllint!skip
tests/unit/module_utils/fixtures/definitions.yml yamllint!skip
tests/unit/module_utils/fixtures/deployments.yml yamllint!skip
tests/integration/targets/k8s_delete/files/deployments.yaml yamllint!skip
@@ -27,5 +26,4 @@ plugins/modules/k8s_scale.py validate-modules:return-syntax-error
plugins/modules/k8s_service.py validate-modules:return-syntax-error
plugins/modules/k8s_taint.py validate-modules:return-syntax-error
tests/integration/targets/helm_diff/files/test-chart-reuse-values/templates/configmap.yaml yamllint!skip
tests/integration/targets/helm_registry_auth/tasks/main.yaml yamllint!skip
tests/integration/targets/helm_diff/files/test-chart-deployment-time/templates/configmap.yaml yamllint!skip

View File

@@ -11,7 +11,6 @@ plugins/module_utils/version.py pylint!skip
plugins/modules/k8s.py validate-modules:parameter-type-not-in-doc
plugins/modules/k8s_scale.py validate-modules:parameter-type-not-in-doc
plugins/modules/k8s_service.py validate-modules:parameter-type-not-in-doc
tests/unit/module_utils/fixtures/clusteroperator.yml yamllint!skip
tests/unit/module_utils/fixtures/definitions.yml yamllint!skip
tests/unit/module_utils/fixtures/deployments.yml yamllint!skip
tests/integration/targets/k8s_delete/files/deployments.yaml yamllint!skip
@@ -27,5 +26,4 @@ plugins/modules/k8s_scale.py validate-modules:return-syntax-error
plugins/modules/k8s_service.py validate-modules:return-syntax-error
plugins/modules/k8s_taint.py validate-modules:return-syntax-error
tests/integration/targets/helm_diff/files/test-chart-reuse-values/templates/configmap.yaml yamllint!skip
tests/integration/targets/helm_registry_auth/tasks/main.yaml yamllint!skip
tests/integration/targets/helm_diff/files/test-chart-deployment-time/templates/configmap.yaml yamllint!skip

View File

@@ -1,105 +0,0 @@
# -*- coding: utf-8 -*-
# Copyright: (c) 2022, 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
from datetime import datetime
from ansible_collections.kubernetes.core.plugins.action.k8s_info import RemoveOmit
def get_omit_token():
return "__omit_place_holder__%s" % datetime.now().strftime("%Y%m%d%H%M%S")
def test_remove_omit_from_str():
omit_token = get_omit_token()
src = """
project: ansible
collection: {omit}
""".format(
omit=omit_token
)
result = RemoveOmit(src, omit_value=omit_token).output()
assert len(result) == 1
assert result[0] == dict(project="ansible")
def test_remove_omit_from_list():
omit_token = get_omit_token()
src = """
items:
- {omit}
""".format(
omit=omit_token
)
result = RemoveOmit(src, omit_value=omit_token).output()
assert len(result) == 1
assert result[0] == dict(items=[])
def test_remove_omit_from_list_of_dict():
omit_token = get_omit_token()
src = """
items:
- owner: ansible
team: {omit}
- simple_list_item
""".format(
omit=omit_token
)
result = RemoveOmit(src, omit_value=omit_token).output()
assert len(result) == 1
assert result[0] == dict(items=[dict(owner="ansible"), "simple_list_item"])
def test_remove_omit_combined():
omit_token = get_omit_token()
src = """
items:
- {omit}
- list_item_a
- list_item_b
parent:
child:
subchilda: {omit}
subchildb:
name: {omit}
age: 3
""".format(
omit=omit_token
)
result = RemoveOmit(src, omit_value=omit_token).output()
assert len(result) == 1
assert result[0] == dict(
items=["list_item_a", "list_item_b"],
parent=dict(child=dict(subchildb=dict(age=3))),
)
def test_remove_omit_mutiple_documents():
omit_token = get_omit_token()
src = [
"""
project: ansible
collection: {omit}
""".format(
omit=omit_token
),
"---",
"""
project: kubernetes
environment: production
collection: {omit}""".format(
omit=omit_token
),
]
src = "\n".join(src)
print(src)
result = RemoveOmit(src, omit_value=omit_token).output()
assert len(result) == 2
assert result[0] == dict(project="ansible")
assert result[1] == dict(project="kubernetes", environment="production")

View File

@@ -1,99 +0,0 @@
---
apiVersion: config.openshift.io/v1
kind: ClusterOperator
metadata:
name: authentication
spec: {}
status:
conditions:
- message: All is well
reason: AsExpected
status: 'False'
type: Degraded
- message: 'AuthenticatorCertKeyProgressing: All is well'
reason: AsExpected
status: 'False'
type: Progressing
- message: All is well
reason: AsExpected
status: 'True'
type: Available
- message: All is well
reason: AsExpected
status: 'True'
type: Upgradeable
- reason: NoData
status: Unknown
type: EvaluationConditionsDetected
---
apiVersion: config.openshift.io/v1
kind: ClusterOperator
metadata:
name: dns
spec: {}
status:
conditions:
- message: DNS "default" is available.
reason: AsExpected
status: 'True'
type: Available
- message: 'DNS "default" reports Progressing=True: "Have 2 available node-resolver
pods, want 3."'
reason: DNSReportsProgressingIsTrue
status: 'True'
type: Progressing
- reason: DNSNotDegraded
status: 'False'
type: Degraded
- message: 'DNS default is upgradeable: DNS Operator can be upgraded'
reason: DNSUpgradeable
status: 'True'
type: Upgradeable
---
apiVersion: config.openshift.io/v1
kind: ClusterOperator
metadata:
name: dns
spec: {}
status:
conditions:
- message: DNS "default" is available.
reason: AsExpected
status: 'True'
type: Available
- message: 'DNS "default" reports Progressing=True: "Have 2 available node-resolver
pods, want 3."'
reason: DNSReportsProgressingIsTrue
status: 'False'
type: Progressing
- reason: DNSNotDegraded
status: 'True'
type: Degraded
- message: 'DNS default is upgradeable: DNS Operator can be upgraded'
reason: DNSUpgradeable
status: 'False'
type: Upgradeable
---
apiVersion: config.openshift.io/v1
kind: ClusterOperator
metadata:
name: dns
spec: {}
status:
conditions:
- message: DNS "default" is available.
reason: AsExpected
status: 'False'
type: Available
- message: 'DNS "default" reports Progressing=True: "Have 2 available node-resolver
pods, want 3."'
reason: DNSReportsProgressingIsTrue
status: 'True'
type: Progressing
- reason: DNSNotDegraded
status: 'True'
type: Degraded
- message: 'DNS default is upgradeable: DNS Operator can be upgraded'
reason: DNSUpgradeable
status: 'False'
type: Upgradeable

View File

@@ -44,8 +44,8 @@ def test_warn_on_k8s_version(monkeypatch, stdin, capfd):
assert return_value.get("warnings") is not None
warnings = return_value["warnings"]
assert len(warnings) == 1
assert "kubernetes" in warnings[0]
assert MINIMAL_K8S_VERSION in warnings[0]
assert "kubernetes" in str(warnings[0])
assert MINIMAL_K8S_VERSION in str(warnings[0])
dependencies = [

View File

@@ -242,7 +242,7 @@ def test_module_run_helm_command(_ansible_helm_module):
assert (rc, out, err) == (0, output, error)
_ansible_helm_module.run_command.assert_called_once_with(
command, environ_update=env_update, data=None
command, environ_update=env_update
)

View File

@@ -1,264 +0,0 @@
# Copyright [2025] [Red Hat, Inc.]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.service import (
build_hidden_field_tree,
hide_fields,
)
def test_hiding_missing_field_does_nothing():
output = dict(
kind="ConfigMap", metadata=dict(name="foo"), data=dict(one="1", two="2")
)
hidden_fields = ["doesnotexist"]
assert hide_fields(output, hidden_fields) == output
def test_hiding_simple_field():
output = dict(
kind="ConfigMap", metadata=dict(name="foo"), data=dict(one="1", two="2")
)
hidden_fields = ["metadata"]
expected = dict(kind="ConfigMap", data=dict(one="1", two="2"))
assert hide_fields(output, hidden_fields) == expected
def test_hiding_only_key_in_dict_removes_dict():
output = dict(kind="ConfigMap", metadata=dict(name="foo"), data=dict(one="1"))
hidden_fields = ["data.one"]
expected = dict(kind="ConfigMap", metadata=dict(name="foo"))
assert hide_fields(output, hidden_fields) == expected
def test_hiding_all_keys_in_dict_removes_dict():
output = dict(
kind="ConfigMap", metadata=dict(name="foo"), data=dict(one="1", two="2")
)
hidden_fields = ["data.one", "data.two"]
expected = dict(kind="ConfigMap", metadata=dict(name="foo"))
assert hide_fields(output, hidden_fields) == expected
def test_hiding_multiple_fields():
output = dict(
kind="ConfigMap", metadata=dict(name="foo"), data=dict(one="1", two="2")
)
hidden_fields = ["metadata", "data.one"]
expected = dict(kind="ConfigMap", data=dict(two="2"))
assert hide_fields(output, hidden_fields) == expected
def test_hiding_dict_key():
output = dict(
kind="ConfigMap",
metadata=dict(
name="foo",
annotations={
"kubectl.kubernetes.io/last-applied-configuration": '{"testvalue"}'
},
),
data=dict(one="1", two="2"),
)
hidden_fields = [
"metadata.annotations[kubectl.kubernetes.io/last-applied-configuration]",
]
expected = dict(
kind="ConfigMap", metadata=dict(name="foo"), data=dict(one="1", two="2")
)
assert hide_fields(output, hidden_fields) == expected
def test_hiding_list_value_key():
output = dict(
kind="Pod",
metadata=dict(name="foo"),
spec=dict(
containers=[
dict(
name="containers",
image="busybox",
env=[
dict(name="ENV1", value="env1"),
dict(name="ENV2", value="env2"),
dict(name="ENV3", value="env3"),
],
)
]
),
)
hidden_fields = ["spec.containers[0].env[1].value"]
expected = dict(
kind="Pod",
metadata=dict(name="foo"),
spec=dict(
containers=[
dict(
name="containers",
image="busybox",
env=[
dict(name="ENV1", value="env1"),
dict(name="ENV2"),
dict(name="ENV3", value="env3"),
],
)
]
),
)
assert hide_fields(output, hidden_fields) == expected
def test_hiding_last_list_item():
output = dict(
kind="Pod",
metadata=dict(name="foo"),
spec=dict(
containers=[
dict(
name="containers",
image="busybox",
env=[
dict(name="ENV1", value="env1"),
],
)
]
),
)
hidden_fields = ["spec.containers[0].env[0]"]
expected = dict(
kind="Pod",
metadata=dict(name="foo"),
spec=dict(
containers=[
dict(
name="containers",
image="busybox",
)
]
),
)
assert hide_fields(output, hidden_fields) == expected
def test_hiding_nested_dicts_using_brackets():
output = dict(
kind="Pod",
metadata=dict(name="foo"),
spec=dict(
containers=[
dict(
name="containers",
image="busybox",
securityContext=dict(runAsUser=101),
)
]
),
)
hidden_fields = ["spec.containers[0][securityContext][runAsUser]"]
expected = dict(
kind="Pod",
metadata=dict(name="foo"),
spec=dict(
containers=[
dict(
name="containers",
image="busybox",
)
]
),
)
assert hide_fields(output, hidden_fields) == expected
def test_using_jinja_syntax():
output = dict(
kind="ConfigMap", metadata=dict(name="foo"), data=["0", "1", "2", "3"]
)
hidden_fields = ["data.2"]
expected = dict(kind="ConfigMap", metadata=dict(name="foo"), data=["0", "1", "3"])
assert hide_fields(output, hidden_fields) == expected
def test_remove_multiple_items_from_list():
output = dict(
kind="ConfigMap", metadata=dict(name="foo"), data=["0", "1", "2", "3"]
)
hidden_fields = ["data[0]", "data[2]"]
expected = dict(kind="ConfigMap", metadata=dict(name="foo"), data=["1", "3"])
assert hide_fields(output, hidden_fields) == expected
def test_hide_dict_and_nested_dict():
output = {
"kind": "Pod",
"metadata": {
"labels": {
"control-plane": "controller-manager",
"pod-template-hash": "687b856498",
},
"annotations": {
"kubectl.kubernetes.io/default-container": "awx-manager",
"creationTimestamp": "2025-01-16T12:40:43Z",
},
},
}
hidden_fields = ["metadata.labels.pod-template-hash", "metadata.labels"]
expected = {
"kind": "Pod",
"metadata": {
"annotations": {
"kubectl.kubernetes.io/default-container": "awx-manager",
"creationTimestamp": "2025-01-16T12:40:43Z",
}
},
}
assert hide_fields(output, hidden_fields) == expected
@pytest.mark.parametrize(
"hidden_fields,expected",
[
(
[
"data[0]",
"data[1]",
"metadata.annotation",
"metadata.annotation[0].name",
],
{"data": {"0": None, "1": None}, "metadata": {"annotation": None}},
),
(
[
"data[0]",
"data[1]",
"metadata.annotation[0].name",
"metadata.annotation",
],
{"data": {"0": None, "1": None}, "metadata": {"annotation": None}},
),
(
[
"data[0]",
"data[1]",
"data",
"metadata.annotation[0].name",
"metadata.annotation",
],
{"data": None, "metadata": {"annotation": None}},
),
],
)
def test_build_hidden_field_tree(hidden_fields, expected):
assert build_hidden_field_tree(hidden_fields) == expected

View File

@@ -31,7 +31,7 @@ modified_def["metadata"]["labels"]["environment"] = "testing"
@pytest.mark.parametrize(
"action, params, existing, instance_warnings, expected",
"action, params, existing, instance, expected",
[
(
"delete",
@@ -51,26 +51,14 @@ modified_def["metadata"]["labels"]["environment"] = "testing"
"apply",
{"apply": "yes"},
{},
(definition, []),
definition,
{"changed": True, "method": "apply", "result": definition},
),
(
"apply",
{"apply": "yes"},
{},
(definition, ["test warning"]),
{
"changed": True,
"method": "apply",
"result": definition,
"warnings": ["test warning"],
},
),
(
"create",
{"state": "patched"},
{},
({}, []),
{},
{
"changed": False,
"result": {},
@@ -83,78 +71,42 @@ modified_def["metadata"]["labels"]["environment"] = "testing"
"create",
{},
{},
(definition, []),
definition,
{"changed": True, "method": "create", "result": definition},
),
(
"create",
{},
{},
(definition, ["test warning"]),
{
"changed": True,
"method": "create",
"result": definition,
"warnings": ["test warning"],
},
),
(
"replace",
{"force": "yes"},
definition,
(definition, []),
definition,
{"changed": False, "method": "replace", "result": definition},
),
(
"replace",
{"force": "yes"},
definition,
(modified_def, []),
modified_def,
{"changed": True, "method": "replace", "result": modified_def},
),
(
"replace",
{"force": "yes"},
definition,
(modified_def, ["test warning"]),
{
"changed": True,
"method": "replace",
"result": modified_def,
"warnings": ["test warning"],
},
),
(
"update",
{},
definition,
(definition, []),
definition,
{"changed": False, "method": "update", "result": definition},
),
(
"update",
{},
definition,
(modified_def, []),
modified_def,
{"changed": True, "method": "update", "result": modified_def},
),
(
"update",
{},
definition,
(modified_def, ["test warning"]),
{
"changed": True,
"method": "update",
"result": modified_def,
"warnings": ["test warning"],
},
),
(
"create",
{"label_selectors": ["app=foo"]},
{},
(definition, []),
definition,
{
"changed": False,
"msg": "resource 'kind=Pod,name=foo,namespace=foo' filtered by label_selectors.",
@@ -164,18 +116,18 @@ modified_def["metadata"]["labels"]["environment"] = "testing"
"create",
{"label_selectors": ["app=nginx"]},
{},
(definition, []),
definition,
{"changed": True, "method": "create", "result": definition},
),
],
)
def test_perform_action(action, params, existing, instance_warnings, expected):
def test_perform_action(action, params, existing, instance, expected):
svc = Mock()
svc.find_resource.return_value = Mock(
kind=definition["kind"], group_version=definition["apiVersion"]
)
svc.retrieve.return_value = ResourceInstance(None, existing) if existing else None
spec = {action + ".return_value": instance_warnings}
spec = {action + ".return_value": instance}
svc.configure_mock(**spec)
result = perform_action(svc, definition, params)

View File

@@ -1,11 +1,9 @@
from json import dumps
from unittest.mock import Mock
import pytest
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.service import (
K8sService,
diff_objects,
parse_quoted_string,
)
from kubernetes.dynamic.exceptions import NotFoundError
from kubernetes.dynamic.resource import Resource, ResourceInstance
@@ -59,22 +57,6 @@ def mock_pod_updated_resource_instance():
return ResourceInstance(None, pod_definition_updated)
@pytest.fixture(scope="module")
def mock_pod_response():
resp = Mock()
resp.data.decode.return_value = dumps(pod_definition)
resp.headers = {}
return resp
@pytest.fixture(scope="module")
def mock_pod_warnings_response():
resp = Mock()
resp.data.decode.return_value = dumps(pod_definition)
resp.headers = {"warning": '299 - "test warning 1", 299 - "test warning 2"'}
return resp
def test_diff_objects_no_diff():
match, diff = diff_objects(pod_definition, pod_definition)
@@ -177,33 +159,16 @@ def test_service_delete_existing_resource_check_mode(mock_pod_resource_instance)
client.delete.assert_not_called()
def test_service_create_resource(mock_pod_response, mock_pod_resource_instance):
spec = {"create.side_effect": [mock_pod_response]}
def test_service_create_resource(mock_pod_resource_instance):
spec = {"create.side_effect": [mock_pod_resource_instance]}
client = Mock(**spec)
module = Mock()
module.params = {}
module.check_mode = False
svc = K8sService(client, module)
result, warnings = svc.create(Mock(), pod_definition)
result = svc.create(Mock(), pod_definition)
assert result == mock_pod_resource_instance.to_dict()
assert not warnings
def test_service_create_resource_warnings(
mock_pod_warnings_response, mock_pod_resource_instance
):
spec = {"create.side_effect": [mock_pod_warnings_response]}
client = Mock(**spec)
module = Mock()
module.params = {}
module.check_mode = False
svc = K8sService(client, module)
result, warnings = svc.create(Mock(), pod_definition)
assert result == mock_pod_resource_instance.to_dict()
assert warnings[0] == "test warning 1"
assert warnings[1] == "test warning 2"
def test_service_create_resource_check_mode():
@@ -211,10 +176,9 @@ def test_service_create_resource_check_mode():
client.create.return_value = mock_pod_resource_instance
module = Mock(params={}, check_mode=True)
svc = K8sService(client, module)
result, warnings = svc.create(Mock(), pod_definition)
result = svc.create(Mock(), pod_definition)
assert result == pod_definition
assert not warnings
client.create.assert_not_called()
@@ -260,99 +224,40 @@ def test_create_project_request():
assert results["result"] == project_definition
def test_service_apply_existing_resource(mock_pod_response, mock_pod_resource_instance):
spec = {"apply.side_effect": [mock_pod_response]}
def test_service_apply_existing_resource(mock_pod_resource_instance):
spec = {"apply.side_effect": [mock_pod_resource_instance]}
client = Mock(**spec)
module = Mock()
module.params = {"apply": True}
module.check_mode = False
svc = K8sService(client, module)
result, warnings = svc.apply(
Mock(), pod_definition_updated, mock_pod_resource_instance
)
result = svc.apply(Mock(), pod_definition_updated, mock_pod_resource_instance)
assert result == mock_pod_resource_instance.to_dict()
assert not warnings
def test_service_apply_existing_resource_warnings(
mock_pod_warnings_response, mock_pod_resource_instance
):
spec = {"apply.side_effect": [mock_pod_warnings_response]}
client = Mock(**spec)
module = Mock()
module.params = {"apply": True}
module.check_mode = False
svc = K8sService(client, module)
result, warnings = svc.apply(
Mock(), pod_definition_updated, mock_pod_resource_instance
)
assert result == mock_pod_resource_instance.to_dict()
assert warnings[0] == "test warning 1"
assert warnings[1] == "test warning 2"
def test_service_replace_existing_resource(
mock_pod_response, mock_pod_resource_instance
):
spec = {"replace.side_effect": [mock_pod_response]}
def test_service_replace_existing_resource(mock_pod_resource_instance):
spec = {"replace.side_effect": [mock_pod_resource_instance]}
client = Mock(**spec)
module = Mock()
module.params = {}
module.check_mode = False
svc = K8sService(client, module)
result, warnings = svc.replace(Mock(), pod_definition, mock_pod_resource_instance)
result = svc.replace(Mock(), pod_definition, mock_pod_resource_instance)
assert result == mock_pod_resource_instance.to_dict()
assert not warnings
def test_service_replace_existing_resource_warnings(
mock_pod_warnings_response, mock_pod_resource_instance
):
spec = {"replace.side_effect": [mock_pod_warnings_response]}
def test_service_update_existing_resource(mock_pod_resource_instance):
spec = {"replace.side_effect": [mock_pod_resource_instance]}
client = Mock(**spec)
module = Mock()
module.params = {}
module.check_mode = False
svc = K8sService(client, module)
result, warnings = svc.replace(Mock(), pod_definition, mock_pod_resource_instance)
result = svc.replace(Mock(), pod_definition, mock_pod_resource_instance)
assert result == mock_pod_resource_instance.to_dict()
assert warnings[0] == "test warning 1"
assert warnings[1] == "test warning 2"
def test_service_update_existing_resource(
mock_pod_response, mock_pod_resource_instance
):
spec = {"replace.side_effect": [mock_pod_response]}
client = Mock(**spec)
module = Mock()
module.params = {}
module.check_mode = False
svc = K8sService(client, module)
result, warnings = svc.replace(Mock(), pod_definition, mock_pod_resource_instance)
assert result == mock_pod_resource_instance.to_dict()
assert not warnings
def test_service_update_existing_resource_warnings(
mock_pod_warnings_response, mock_pod_resource_instance
):
spec = {"replace.side_effect": [mock_pod_warnings_response]}
client = Mock(**spec)
module = Mock()
module.params = {}
module.check_mode = False
svc = K8sService(client, module)
result, warnings = svc.replace(Mock(), pod_definition, mock_pod_resource_instance)
assert result == mock_pod_resource_instance.to_dict()
assert warnings[0] == "test warning 1"
assert warnings[1] == "test warning 2"
def test_service_find(mock_pod_resource_instance):
@@ -383,24 +288,3 @@ def test_service_find_error():
assert isinstance(results, dict)
assert results["api_found"] is True
assert results["resources"] == []
@pytest.mark.parametrize(
"quoted_string,expected_val,expected_remainder",
[
(
'"Response is stale" Tue, 15 Nov 1994 12:45:26 GMT',
"Response is stale",
"Tue, 15 Nov 1994 12:45:26 GMT",
),
(
'"unknown field \\"spec.template.spec.disk\\""',
'unknown field "spec.template.spec.disk"',
"",
),
],
)
def test_parse_quoted_string(quoted_string, expected_val, expected_remainder):
val, remainder = parse_quoted_string(quoted_string)
assert val == expected_val
assert remainder == expected_remainder

View File

@@ -9,7 +9,6 @@ from ansible_collections.kubernetes.core.plugins.module_utils.k8s.waiter import
DummyWaiter,
Waiter,
clock,
cluster_operator_ready,
custom_condition,
deployment_ready,
exists,
@@ -30,7 +29,6 @@ def resources(filepath):
RESOURCES = resources("fixtures/definitions.yml")
PODS = resources("fixtures/pods.yml")
DEPLOYMENTS = resources("fixtures/deployments.yml")
CLUSTER_OPERATOR = resources("fixtures/clusteroperator.yml")
def test_clock_times_out():
@@ -121,10 +119,3 @@ def test_get_waiter_returns_correct_waiter():
).predicate.func
== custom_condition
)
@pytest.mark.parametrize(
"clusteroperator,expected", zip(CLUSTER_OPERATOR, [True, False, False, False])
)
def test_cluster_operator(clusteroperator, expected):
assert cluster_operator_ready(clusteroperator) is expected

View File

@@ -51,7 +51,7 @@ class TestDependencyUpdateWithoutChartRepoUrlOption(unittest.TestCase):
with self.assertRaises(AnsibleExitJson) as result:
helm_template.main()
mock_run_command.assert_called_once_with(
"/usr/bin/helm template /tmp/path", environ_update={}, data=None
"/usr/bin/helm template /tmp/path", environ_update={}
)
assert result.exception.args[0]["command"] == "/usr/bin/helm template /tmp/path"
@@ -74,7 +74,6 @@ class TestDependencyUpdateWithoutChartRepoUrlOption(unittest.TestCase):
mock_run_command.assert_called_once_with(
"/usr/bin/helm template test --repo=https://charts.com/test",
environ_update={},
data=None,
)
assert (
result.exception.args[0]["command"]
@@ -96,7 +95,6 @@ class TestDependencyUpdateWithoutChartRepoUrlOption(unittest.TestCase):
mock_run_command.assert_called_once_with(
"/usr/bin/helm template https://charts/example.tgz --dependency-update",
environ_update={},
data=None,
)
assert (
result.exception.args[0]["command"]

View File

@@ -88,7 +88,6 @@ class TestDependencyUpdateWithoutChartRepoUrlOption(unittest.TestCase):
mock_run_command.assert_called_once_with(
"/usr/bin/helm upgrade -i --reset-values test '/tmp/path'",
environ_update={"HELM_NAMESPACE": "test"},
data=None,
)
assert (
result.exception.args[0]["command"]
@@ -119,7 +118,6 @@ class TestDependencyUpdateWithoutChartRepoUrlOption(unittest.TestCase):
mock_run_command.assert_called_once_with(
"/usr/bin/helm upgrade -i --reset-values test '/tmp/path'",
environ_update={"HELM_NAMESPACE": "test"},
data=None,
)
assert (
result.exception.args[0]["command"]
@@ -149,7 +147,6 @@ class TestDependencyUpdateWithoutChartRepoUrlOption(unittest.TestCase):
call(
"/usr/bin/helm upgrade -i --reset-values test '/tmp/path'",
environ_update={"HELM_NAMESPACE": "test"},
data=None,
)
]
)
@@ -184,7 +181,6 @@ class TestDependencyUpdateWithoutChartRepoUrlOption(unittest.TestCase):
call(
"/usr/bin/helm upgrade -i --reset-values test '/tmp/path'",
environ_update={"HELM_NAMESPACE": "test"},
data=None,
)
]
)
@@ -255,7 +251,6 @@ class TestDependencyUpdateWithChartRepoUrlOption(unittest.TestCase):
mock_run_command.assert_called_once_with(
"/usr/bin/helm --repo=http://repo.example/charts upgrade -i --reset-values test 'chart1'",
environ_update={"HELM_NAMESPACE": "test"},
data=None,
)
assert (
result.exception.args[0]["command"]
@@ -285,7 +280,6 @@ class TestDependencyUpdateWithChartRepoUrlOption(unittest.TestCase):
mock_run_command.assert_called_once_with(
"/usr/bin/helm --repo=http://repo.example/charts upgrade -i --reset-values test 'chart1'",
environ_update={"HELM_NAMESPACE": "test"},
data=None,
)
assert (
result.exception.args[0]["command"]
@@ -344,7 +338,6 @@ class TestDependencyUpdateWithChartRepoUrlOption(unittest.TestCase):
mock_run_command.assert_called_once_with(
"/usr/bin/helm --repo=http://repo.example/charts install --dependency-update --replace test 'chart1'",
environ_update={"HELM_NAMESPACE": "test"},
data=None,
)
assert (
result.exception.args[0]["command"]
@@ -412,7 +405,6 @@ class TestDependencyUpdateWithChartRefIsUrl(unittest.TestCase):
mock_run_command.assert_called_once_with(
"/usr/bin/helm upgrade -i --reset-values test 'http://repo.example/charts/application.tgz'",
environ_update={"HELM_NAMESPACE": "test"},
data=None,
)
assert (
result.exception.args[0]["command"]
@@ -441,7 +433,6 @@ class TestDependencyUpdateWithChartRefIsUrl(unittest.TestCase):
mock_run_command.assert_called_once_with(
"/usr/bin/helm upgrade -i --reset-values test 'http://repo.example/charts/application.tgz'",
environ_update={"HELM_NAMESPACE": "test"},
data=None,
)
assert (
result.exception.args[0]["command"]
@@ -498,7 +489,6 @@ class TestDependencyUpdateWithChartRefIsUrl(unittest.TestCase):
mock_run_command.assert_called_once_with(
"/usr/bin/helm install --dependency-update --replace test 'http://repo.example/charts/application.tgz'",
environ_update={"HELM_NAMESPACE": "test"},
data=None,
)
assert (
result.exception.args[0]["command"]