Compare commits

...
95 Commits
Author SHA1 Message Date
Sean MalloyandGitHub a890d14253 Prepare 4.0.1 release (#247) 2024-12-09 18:14:31 +00:00
3833922158 Fix Failed Token Delete with PEP8 Indent (#242) (#243)
Co-authored-by: Carter Hale <44034905+HaleCT2@users.noreply.github.com>
Co-authored-by: carter <me@halecarter.com>
2024-09-02 12:40:16 +00:00
Bikouo AubinandGitHub 97ed9be7d9 Release 4.0.0 (#235)
* Prepare release 4.0.0

* Update kubernetes.core dependency to 5.0.0

* documentation update
2024-06-13 15:35:12 +00:00
Bikouo AubinandGitHub e5b3e5b73e [stable-4] Fix action group documentation issue for downstream build (#232) (#234)
* Fix action group documentation issue for downstream build (#232)

(cherry picked from commit 59e78926ec)

* update Makefile
2024-06-10 15:40:07 +00:00
Bikouo AubinandGitHub 0e884c2341 k8s - Remove support of merge_type=json (#226) 2024-05-28 17:13:25 +00:00
Bikouo AubinandGitHub 050e236aa6 Defer removal of inventory/openshift to 5.0.0 (#224)
* Defer removal of inventory/openshift to 5.0.0

* add pull request number
2024-05-28 17:43:38 +02:00
Bikouo AubinandGitHub 2c394132aa connection/oc - add option oc_local_env_vars (#225)
* add local env vars for connection/oc plugin

* Fix sanity tests
2024-05-28 13:44:03 +00:00
Bharat BabbarandGitHub fcc19da20a Update k8s.py (#218)
docs.ansible.com is managed by Red Hat and I found that the example to create the OCP/OKD project was missing in this hence I have added the below snippet:

    - name: Create an OCP project
      community.okd.k8s:
        state: present
        resource_definition:
          apiVersion: project.openshift.io/v1
          kind: Project
          metadata:
            name: testing

Please add this to the man pages also.
2024-01-18 15:22:39 +00:00
Alina BuzachisandGitHub 31c2df50ed Remove useless tests/sanity/ignore-2.*.txt files lower than 2.14 (#213)
Signed-off-by: Alina Buzachis <abuzachis@redhat.com>
2023-12-12 16:29:00 +00:00
ca8b491f87 Push release 3.0.1 changes into main branch (#211)
* Prepare release 3.0.0 (#206)

* Preapare release 3.0.0

* Added release summary

* Drop ansible 2.9 mentions

* Add .gitignore to downstream build files (#208) (#209)

This is required for ansible-lint.

(cherry picked from commit 7988daff93)

* Release version 3.0.1 (#210)

* Running tests locally (#207)

* Running tests locally

* create temporary directory to run tests in

* clean for molecule target

* Update Makefile

Co-authored-by: Mike Graves <mgraves@redhat.com>

---------

Co-authored-by: Mike Graves <mgraves@redhat.com>

---------

Co-authored-by: GomathiselviS <gomathiselvi@gmail.com>
Co-authored-by: Mike Graves <mgraves@redhat.com>
2023-12-11 18:07:16 +00:00
Bikouo AubinandGitHub b5b2f67015 fix integration unsafe asserts (#212) 2023-12-11 17:57:20 +01:00
Mike GravesandGitHub 7988daff93 Add .gitignore to downstream build files (#208)
This is required for ansible-lint.
2023-11-30 06:11:26 +00:00
Mike GravesandGitHub 408eae11ae Relax the python version in downstream build (#205) 2023-11-17 16:40:25 +00:00
Mike GravesandGitHub 5244611fa5 Update owners file (#197) 2023-11-15 18:39:37 +00:00
a63e5b7b36 Update CI - Continue work from #195 (#202)
* Upgrade Ansible and OKD versions for CI

* Use ubi9 and fix sanity

* Use correct pip install

* Try using quotes

* Ensure python3.9

* Upgrade ansible and molecule versions

* Remove DeploymentConfig

DeploymentConfigs are deprecated and seem to now be causing idempotence
problems. Replacing them with Deployments fixes it.

* Attempt to fix ldap integration tests

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>

* Move sanity and unit tests to GH actions

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>

* Firt round of sanity fixes

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>

* Add kubernetes.core collection as sanity requirement

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>

* Add ignore-2.16.txt

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>

* Attempt to fix units

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>

* Add ignore-2.17

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>

* Attempt to fix unit tests

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>

* Add pytest-ansible to test-requirements.txt

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>

* Add changelog fragment

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>

* Add workflow for ansible-lint

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>

* Apply black

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>

* Fix linters

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>

* Add # fmt: skip

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>

* Yet another round of linting

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>

* Yet another round of linting

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>

* Remove setup.cfg

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>

* Revert #fmt

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>

* Use ansible-core 2.14

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>

* Cleanup ansible-lint ignores

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>

* Try using service instead of pod IP

* Fix typo

* Actually use the correct port

* See if NetworkPolicy is preventing connection

* using Pod internal IP

* fix adm prune auth roles syntax

* adding some retry steps

* fix: openshift_builds target

* add flag --force-with-deps when building downstream collection

* Remove yamllint from tox linters, bump minimum python supported version to 3.9, Remove support for ansible-core < 2.14

---------

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>
Co-authored-by: Mike Graves <mgraves@redhat.com>
Co-authored-by: Alina Buzachis <abuzachis@redhat.com>
2023-11-15 17:00:38 +00:00
Gonéri Le BouderandGitHub cb796e1298 remove myself from OWNERS_ALIASES (#189) 2023-04-12 09:43:11 -04:00
Alina BuzachisandGitHub e9c891c5c2 Deprecate the openshift inventory plugin (#186)
* Deprecate the openshift inventory plugin

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>

* Fix indentation

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>

* Update docs

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>

---------

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>
2023-02-07 10:20:58 -05:00
Bikouo AubinandGitHub 81339235c7 Release 2.3.0 (#184) (#185) 2023-02-03 19:21:03 +01:00
Bikouo AubinandGitHub f94eabffa1 update collection with latest feature from kubernetes.core (#181)
* Rebase code with kubernetes.core stable-2.4
2023-02-03 07:57:24 +01:00
Mike GravesandGitHub 499863fa27 Fix example docs for openshift_auth (#182) 2023-01-26 10:20:49 -05:00
Mike GravesandGitHub 5834e32c73 Add missing default values in docstrings (#180)
* Add missing default values in docstrings

These are needed for milestone (2.15) sanity tests.

* Add changelog fragment
2023-01-24 11:42:15 -05:00
Bikouo AubinandGitHub 5aa63e1b07 openshift_auth - fix discard token (#178)
* openshift_auth: when revoking token, compute the right name of the openshift resource to delete from token name

* conditional check to revoke token
2023-01-12 10:53:42 -05:00
Bikouo AubinandGitHub d7f8aa537a add pytest-forked in test-requirements.txt (#179) 2022-12-01 12:28:01 -05:00
Mike GravesandGitHub 1691951788 Update for Ansible 2.15 sanity tests (#173) 2022-09-22 15:38:20 +02:00
Bikouo AubinandGitHub ed9fb196f9 Openshift Build modules (#134)
* Openshift Build modules: Start, Prune

* add openshift adm prune builds to ansible-test

* fix sanity for downstream

* sanity ignore

* Remove 2.6 sanity ignores for ansible 2.13 and 2.14

* update code review

* update 2 - code review
2022-08-12 13:56:19 +00:00
Bikouo AubinandGitHub 1819975498 Fix sanity tests (#172)
* Fix sanity tests
2022-08-11 18:14:40 +02:00
Mike GravesandGitHub 01c257ce76 Fix sanity failures for docs on Ansible 2.13 (#167) 2022-05-13 15:59:25 +02:00
Mike GravesandGitHub 5545c0f9ae Initialize OpenshiftGroupsSync attributes early (#165)
* Initialize OpenshiftGroupsSync attributes early

The fail_json() method calls close_connection(), but this can fail when
the python-ldap library is not installed as close_connection() gets
called before the __ldap_connection attribute has been defined.

* Use already defined virtualenv_command

* Fix tests

* Add changelog fragment
2022-05-12 21:13:59 +00:00
Mike GravesandGitHub 15fff541b1 Update test dependency (#162) 2022-05-06 09:50:33 -04:00
Mike GravesandGitHub cfbbbb3be1 Release 2.2.0 (#161) 2022-05-06 06:57:01 -04:00
Mike GravesandGitHub ab83a185f5 Fix integration tests for k8s 2.3 (#159)
* Fix integration tests for k8s 2.3

Previous to
https://github.com/ansible-collections/kubernetes.core/pull/408 an
attempt to list resources for which the user was not authorized resulted
in an unhandled exception. The task now does not fail, but instead
reports the error message.

* try to fix sanity

* Fix tests

* fix tests

* fix tests

* Revert change to downstream build
2022-05-05 14:11:35 -04:00
Mike GravesandGitHub e69c88ae30 Upgrade python version on prow container to 3.9 (#156)
* Upgrade python version on prow container to 3.9

* Increase integration time out

* Set build python version

* Fix typo
2022-05-03 15:19:39 -04:00
Mike GravesandGitHub 3381806d39 Add action groups (#152)
* Add action groups

* Add changelog fragment
2022-05-02 15:26:52 -04:00
Bikouo AubinandGitHub b2d9e78b8e add step to prepare downstream collection (#154)
* add step to prepare downstream collection

* fix header generation

* update downstream_fragments.py
2022-04-29 09:22:46 -04:00
Mike GravesandGitHub 0290391446 Copy sanity ignores from 2.13 to 2.14 (#147) 2022-04-13 09:42:53 -04:00
jbprattandGitHub 80e2692db2 fix kubeconfig flag for newer versions (#142)
backwards compatible change:

```
> podman run -it --rm openshift/origin-cli:v3.11.0 oc --kubeconfig
Error: flag needs an argument: --kubeconfig
```

Signed-off-by: Brady Pratt <bpratt@redhat.com>
2022-03-04 11:21:54 -05:00
8aeffa3872 fix ocp auth adding / to oauth discovery url (#140)
* fix ocp auth adding / to oauth discovery url

* fix space after comma

* add changelog fragment

* Convert line endings

Co-authored-by: Mike Graves <mgraves@redhat.com>
2022-02-22 13:28:51 -05:00
abikouoandGitHub fc4a979762 openshift adm prune images (#133) 2022-01-24 09:46:23 -05:00
abikouoandGitHub 0a1a647e37 openshift adm group sync/prune (#125) 2022-01-20 11:23:30 -05:00
abikouoandGitHub eb11821b3c enable unit testing (#135)
* enable unit testing

* Update test-requirements.txt

* Update test-requirements.txt
2022-01-10 17:25:11 +01:00
abikouoandGitHub 39cb9a0981 openshift admin prune deployments (#129)
* openshift admin prune deployments

* update test

* update
2021-11-30 16:39:37 +01:00
abikouoandGitHub 496cdba4e8 openshift admin prune auth (#130)
* openshift admin prune auth

* update change scope
2021-11-30 14:16:22 +01:00
Alina BuzachisandGitHub 6b2efa180f openshift_adm_migrate_template_instances - new module (#126)
* openshift_adm_migrate_template_instances -  new module to update TemplateInstances to point to the latest group-version-kinds.

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>

* update

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>

* Add unit tests

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>

* Address comments

Signed-off-by: Alina Buzachis <abuzachis@redhat.com>
2021-11-17 12:28:35 +01:00
Andrew KlychkovandGitHub f13caaffb9 Remove .github/workflows as tests are run by Zuul (#121) 2021-11-12 13:05:26 +01:00
Alina BuzachisandGitHub 1487d79ac4 Enable unit tests in the CI (#127)
Signed-off-by: Alina Buzachis <abuzachis@redhat.com>
2021-11-11 11:41:41 +01:00
Mike GravesandGitHub d154967c88 Release 2.1.0 (#124) 2021-11-02 13:47:24 +01:00
Gonéri Le BouderandGitHub e0c6713926 relax the dependency with kubernetes.core (#109)
* relax the dependency with kubernetes.core

We can use the collection with the 2.2 branch of kubernetes.core.

* galaxy: use <2.3.0 has the upper version bound

See: https://github.com/ansible/ansible-zuul-jobs/pull/1119
2021-10-20 13:05:10 +00:00
Andrew KlychkovandGitHub 11314f8280 Copy ignore-2.12.txt to ignore-2.13.txt (#119) 2021-09-30 09:35:09 -04:00
Gonéri Le BouderandGitHub c737d44413 improve turbo mode support (#117)
- delay the loading of external modules when possible
- delay the loading of OKDRawModule and OpenShiftProcess classes
- k8s reuse the design of the kubernetes.core modules

We've got a chicken/egg problem that prevent us from properly
reporting if kubernetes.core is missing. We need args_common to create
the module object. And we need the module object to report the missing
dependency. The dependency is declared in the galaxy.yml file anyway,
the problem should not happen.
2021-09-23 11:09:42 -04:00
Gonéri Le BouderandGitHub c340ff6582 pylint: ignore a use-a-generator message (#118)
Follow up to the recent upgrade of pylint in the devel branch, we've
got a new use-a-generator error in k8s.py:

Use a generator instead 'all(desired.get(key, True) == item.get(key, False) for key in keys)'

This commit disables the error until we've got time to rewrite this
part.
Also, since the older branches still use an ancient version of pylint,
we've got another message saying the error does not exist (yet!).
This commit also adds the right entries in the ignore files.
2021-09-23 01:55:47 -04:00
Alina BuzachisandGitHub 9bea36be5c Update links (#111)
Signed-off-by: Alina Buzachis <abuzachis@redhat.com>
2021-09-21 13:06:09 -04:00
Gonéri Le BouderandGitHub 7bb52051da molecule: gives more time to openshift_route (#113)
My set-up is pretty slow and adding a bit of retries help to pass
the test reliably.
2021-09-21 13:05:26 -04:00
Gonéri Le BouderandGitHub ffe6025fe9 gitignore: ansible_collections dir is used by the Makefile (#114)
Ignore the ansible_collections directory. This directory is used to
prepare the collections, before the Makefile call molecule.
2021-09-21 13:05:06 -04:00
Gonéri Le BouderandGitHub f095a4d238 shellcheck: SC2236: Use -n instead of ! -z. (#110)
Address the following warning:

```
ERROR: Found 1 shellcheck issue(s) which need to be resolved:
ERROR: ci/incluster_integration.sh:16:7: SC2236: Use -n instead of ! -z.
```
2021-09-21 13:04:43 -04:00
Alina BuzachisandGitHub b0638ad2a4 Update OWNERS by using OWNERS_ALIASES (#112)
Signed-off-by: Alina Buzachis <abuzachis@redhat.com>
2021-09-21 13:04:13 -04:00
Mike GravesandGitHub bfb2c8904f Fix sanity test errors (#107)
The empty test-requirements.txt file is needed to get Zuul's sanity job
to run.
2021-09-20 11:53:44 -04:00
Mike GravesandGitHub 3d0dfc1ae2 Replace IMAGE_FORMAT env var (#108)
The IMAGE_FORMAT env var has been deprecated and removed. This adds a
new env var that will be set upstream in the openshift CI config.
2021-09-16 15:00:37 -04:00
Alina BuzachisandGitHub c72d17b6ba Add docs for turbo mode (#104)
Signed-off-by: Alina Buzachis <abuzachis@redhat.com>
2021-09-08 15:05:24 +02:00
Mike GravesandGitHub 0838ee48d2 Enable turbo mode (#102)
* Enable turbo mode

This enables turbo mode (default is off) for the modules in this
collection that use the client from the kubernetes.core collection.

* Add changelog fragment
2021-08-25 10:37:56 -04:00
Mike GravesandGitHub e9f8c41ac4 Fix broken links for downstream collection (#101)
* Fix broken links for downstream collection

The links to the repo on Automation Hub are broken for the downstream
collection. This skips the replacement step for galaxy.yml.

* Add changelog fragment
2021-08-10 12:29:51 +00:00
abikouoandGitHub faba4a0812 openshift_route - add support for annotations (#99)
* add support for annotations
2021-07-29 14:36:52 +02:00
Mike GravesandGitHub 6b2f06a157 Release 2.0.1 (#98) 2021-06-24 14:28:28 -04:00
Mike GravesandGitHub bffadb5a55 Bump kubernetes.core version (#97)
* Bump kubernetes.core version

* Add changelog fragment
2021-06-24 14:10:53 -04:00
Mike GravesandGitHub d7a8ba15c7 Release 2.0.0 (#96) 2021-06-23 08:43:56 -04:00
Mike GravesandGitHub 9ff94989ae Update OWNERS file (#95) 2021-06-21 14:43:12 -04:00
Mike GravesandGitHub f60ded17b0 Update to work with k8s 2.0 (#93)
* Update to work with k8s 2.0

This makes the necessary changes to get the collection working with
kubernetes.core 2.0. The biggest changes here will be switching from the
openshift client to the kubernetes client, and dropping Python 2
support.

* Install kubernetes not openshift

* Add changelog fragment
2021-06-21 14:41:56 -04:00
Andrew KlychkovandGitHub 37833d4316 Update README, CONTRIBUTING.md: freenode -> libera.chat (#92) 2021-05-31 16:17:27 +02:00
4609c20a91 openshift_process fails with template does not contains message (#87)
* fix unexpected value

* changelog

* Update pod-template.yaml

* Update openshift_process.py

* Update openshift_process.py

* Update molecule/default/tasks/openshift_process.yml

Co-authored-by: Fabian von Feilitzsch <fabian@fabianism.us>

* Update pod-template.yaml

Co-authored-by: Fabian von Feilitzsch <fabian@fabianism.us>
2021-05-26 10:48:47 -04:00
abikouoandGitHub 63deaeecf0 remove hardcoded host value for molecule test openshift_auth (#90) 2021-05-26 10:42:41 -04:00
Mike GravesandGitHub d696fcaa06 Clean up CI build (#89)
* Clean up CI build

There were a few problems with the existing build process, such as, the
python version not being passed during sanity tests and versions being
hard coded elsewhere. This change ensures that each test scenario gets
the correct parameters passed through. It also generally cleans up the
process for building the test environment to let ansible-galaxy do its
thing. This will make sure the correct version of dependencies get
installed.

* Add changelog fragment
2021-05-26 09:49:10 -04:00
Abhijeet KasurdeandGitHub 7e653aee65 k8s: Remove KubernetesRawModule dependency (#74) 2021-04-20 12:02:14 +05:30
Abhijeet KasurdeandGitHub dd2ed851ab Support FQCN in openshift inventory (#85)
* Added support FQCN ``redhat.openshift`` support for inventory
  plugin

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
2021-04-14 09:18:10 +05:30
Abhijeet KasurdeandGitHub c5f822a0a7 Removed old changelog fragments (#84)
* Removed old changelog fragment files
* Updated configuration to remove old fragment files
  on release

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
2021-04-13 11:08:02 +05:30
Abhijeet KasurdeandGitHub 748d40d244 Added docs for the collection (#83) 2021-04-13 11:07:23 +05:30
Mike GravesandGitHub 152c6e42c5 Release 1.1.2 (#82) 2021-04-08 09:45:39 -04:00
Mike GravesandGitHub 74ce4c31ae Include requirements.txt in downstream build (#81)
* Include requirements.txt in downstream build

* Add changelog fragment
2021-04-07 04:49:37 -04:00
Mike GravesandGitHub ac86a8900c Release 1.1.1 (#79)
* Release 1.1.1

* Add CI fix to changelog
2021-04-06 12:09:53 -04:00
Mike GravesandGitHub fb1912728d Update CI for ansible 2.11 (#80)
* Update CI for ansible 2.11

This copies the ignore-2.11.txt to ignore-2.12.txt and makes sure the CI
build tests against ansible 2.11.

* Add changelog fragment
2021-04-06 16:40:46 +02:00
Mike GravesandGitHub 22f878023a Add missing requirements.txt file (#78)
* Add missing requirements.txt file

This is needed for execution environments.

* Add changelog fragment
2021-04-06 06:14:43 +02:00
Abhijeet KasurdeandGitHub 921c451f0d k8s_auth: Redirect using meta/runtime.yml (#73)
Fixes: #57

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
2021-04-05 18:39:15 +02:00
Mike GravesandGitHub e7e114743c Fix sanity failure (#77)
* Fix sanity failure

This fixes a sanity test failure for newer versions of ansible-test. It
was falsely flagging the key parameter for TLS configuration as
sensitive. This parameter is just the path to a key file.

* Restrict molecule version

This is needed to address a breaking change in molecule 3.3.0.

* Add changelog fragment
2021-04-05 17:15:15 +02:00
Mike GravesandGitHub ef6712c8f6 Release version 1.1.0 (#72) 2021-02-24 10:33:21 -05:00
Mike GravesandGitHub 570a8ccd27 Increase kubernetes.core dependency version number (#71)
* Increase kubernetes.core dependency version number

* Add changelog fragment
2021-02-23 02:43:25 -05:00
Eric GustavssonandGitHub d76430d879 typo: conig -> config (#69) 2021-02-22 11:15:15 -05:00
Mike GravesandGitHub 2b51c229ad Prepare for 1.0.2 release (#70) 2021-02-19 12:03:23 -05:00
Mike GravesandGitHub d197d28cd1 Restrict kubernetes.core dependency version (#66)
* Restrict kubernetes.core dependency version

In order to better coordinate releases between this collection and the
kubernetes.core collection we need to use a more restrictive dependency
version range.

* Add changelog fragment
2021-02-19 10:38:31 -05:00
Mike GravesandGitHub 5361c9322e Remove has_action field from doc fragment (#68)
A recent change in Ansible
(https://github.com/ansible/ansible/commit/42da4807214cd609fd3c1800ab245c025ae044cd)
added a has_action field to the json output of ansible-doc. This started
causing the downstream sanity checks to fail.
2021-02-18 11:35:30 -05:00
Mike GravesandGitHub 6c1dc79c7f Fix doc string (#67)
* Fix doc string

The sanity tests fail due to missing default values on a few options in
the doc string. This change puts the doc string in alignment with the
argument spec.

* Fix case
2021-02-18 08:01:49 -05:00
Abhijeet KasurdeandGitHub 4cfbde3d14 Sanity check fixes for CI (#63)
Fixes: #62 #57

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
2020-11-18 15:52:26 +01:00
Jeff GeerlingandGitHub 56e39540a0 Issue #60: Release version 1.0.1. (#61)
* Issue #60: Release version 1.0.1.

* Fix rstcheck issue by substituting some equals signs with ugly regex.
2020-11-17 17:44:37 -06:00
2d71c469bd doc fragments workaround for downstream (#59)
* doc fragments workaround for downstream

Signed-off-by: Adam Miller <admiller@redhat.com>

* make shellcheck happy

Signed-off-by: Adam Miller <admiller@redhat.com>

* fix collection location for downstream doc fragment resolution

Signed-off-by: Adam Miller <admiller@redhat.com>

* do things in the correct order

Signed-off-by: Adam Miller <admiller@redhat.com>

* add ANSIBLE_COLLECTIONS_PATH to ansible-doc for downstream

Signed-off-by: Adam Miller <admiller@redhat.com>

* remove elements of the json dump that aren't valid for DOCUMENTATION

Signed-off-by: Adam Miller <admiller@redhat.com>

* Add fix for Ansible 2.9

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>

* Update ci/downstream.sh

Co-authored-by: Abhijeet Kasurde <akasurde@redhat.com>
Co-authored-by: Jeff Geerling <geerlingguy@mac.com>
2020-11-17 18:03:00 +01:00
Jeff GeerlingandGitHub 87cd174b96 Issue #57: Switch dependency from community.kubernetes to kubernetes.core. (#58)
* Issue #57: Switch dependency from community.kubernetes to kubernetes.core.

* Issue #57: Rely on kubernetes.core install directly.

* Issue #57: Don't install kubernetes.core from source anymore.
2020-11-16 13:35:18 -06:00
Adam MillerandGitHub 32a6a1fda3 Fix ci/downstream.sh docs "branding" (#55)
* Fix ci/downstream.sh docs "branding"

Signed-off-by: Adam Miller <admiller@redhat.com>

* fix CHANGELOG.rst title overline length

Signed-off-by: Adam Miller <admiller@redhat.com>
2020-11-12 14:04:23 -06:00
Jeff GeerlingandGitHub 775312c037 Issue #51: Update downstream build script so it works on macOS / BSD-sed. (#54) 2020-11-12 10:44:32 -06:00
Jeff GeerlingandGitHub c1c08606e2 Issue #51: Prepare for 1.0.0 release. (#52) 2020-11-12 09:57:41 -06:00
137 changed files with 22518 additions and 1257 deletions
+5
View File
@@ -0,0 +1,5 @@
---
profile: production
exclude_paths:
- molecule
- tests/sanity
+4
View File
@@ -0,0 +1,4 @@
---
backport_branch_prefix: patchback/backports/
backport_label_prefix: backport-
target_branch_prefix: stable-
+6
View File
@@ -0,0 +1,6 @@
---
# DO NOT MODIFY
# Settings: https://probot.github.io/apps/settings/
# Pull settings from https://github.com/ansible-collections/.github/blob/master/.github/settings.yml
_extends: ".github"
+60
View File
@@ -0,0 +1,60 @@
---
# Configuration for probot-stale - https://github.com/probot/stale
# Number of days of inactivity before an Issue or Pull Request becomes stale
daysUntilStale: 90
# Number of days of inactivity before an Issue or Pull Request with the stale
# label is closed. Set to false to disable. If disabled, issues still need to be
# closed manually, but will remain marked as stale.
daysUntilClose: 30
# Only issues or pull requests with all of these labels are check if stale.
# Defaults to `[]` (disabled)
onlyLabels: []
# Issues or Pull Requests with these labels will never be considered stale. Set
# to `[]` to disable
exemptLabels:
- security
- planned
- priority/critical
- lifecycle/frozen
- verified
# Set to true to ignore issues in a project (defaults to false)
exemptProjects: false
# Set to true to ignore issues in a milestone (defaults to false)
exemptMilestones: true
# Set to true to ignore issues with an assignee (defaults to false)
exemptAssignees: false
# Label to use when marking as stale
staleLabel: lifecycle/stale
# Limit the number of actions per hour, from 1-30. Default is 30
limitPerRun: 30
pulls:
markComment: |-
PRs go stale after 90 days of inactivity.
If there is no further activity, the PR will be closed in another 30 days.
unmarkComment: >-
This pull request is no longer stale.
closeComment: >-
This pull request has been closed due to inactivity.
issues:
markComment: |-
Issues go stale after 90 days of inactivity.
If there is no further activity, the issue will be closed in another 30 days.
unmarkComment: >-
This issue is no longer stale.
closeComment: >-
This issue has been closed due to inactivity.
-141
View File
@@ -1,141 +0,0 @@
# README FIRST
# 1. replace "community/okd" with the correct name, ie "community/zabbix"
# 2. If you don't have unit tests remove that section
# 3. If your collection depends on other collections ensure they are installed, see "Install collection dependencies"
# If you need help please ask in #ansible-devel on Freenode IRC
name: CI
on:
# Run CI against all pushes (direct commits) and Pull Requests
- push
- pull_request
jobs:
###
# Sanity tests (REQUIRED)
#
# https://docs.ansible.com/ansible/latest/dev_guide/testing_sanity.html
sanity:
name: Sanity (Ⓐ${{ matrix.ansible }}+py${{ matrix.python }})
strategy:
matrix:
ansible:
- stable-2.9
- stable-2.10
- devel
python:
- 2.7
- 3.7
- 3.8
exclude:
- python: 3.8 # blocked by ansible/ansible#70155
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v2
with:
path: ansible_collections/community/okd
- name: Set up Python ${{ matrix.ansible }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python }}
# Install the head of the given branch (devel, stable-2.10)
- name: Install ansible-base (${{ matrix.ansible }})
run: pip install https://github.com/ansible/ansible/archive/${{ matrix.ansible }}.tar.gz --disable-pip-version-check
# run ansible-test sanity inside of Docker.
# The docker container has all the pinned dependencies that are required.
# Explicity specify the version of Python we want to test
- name: Run sanity tests
run: make upstream-test-sanity TEST_ARGS='--python ${{ matrix.python }}'
working-directory: ./ansible_collections/community/okd
###
# Integration tests (RECOMMENDED)
#
# https://docs.ansible.com/ansible/latest/dev_guide/testing_integration.html
# integration:
# runs-on: ubuntu-latest
# name: Integration (Ⓐ${{ matrix.ansible }}+py${{ matrix.python }}})
# strategy:
# fail-fast: false
# matrix:
# ansible:
# - stable-2.9
# - stable-2.10
# - devel
# python:
# - 2.7
# - 3.7
# - 3.8
# exclude:
# - python: 3.8 # blocked by ansible/ansible#70155
# steps:
# - name: Check out code
# uses: actions/checkout@v2
# with:
# path: ansible_collections/community/okd
# - name: Set up Python ${{ matrix.ansible }}
# uses: actions/setup-python@v2
# with:
# python-version: ${{ matrix.python }}
# - name: Install ansible-base (${{ matrix.ansible }})
# run: pip install https://github.com/ansible/ansible/archive/${{ matrix.ansible }}.tar.gz --disable-pip-version-check
# # OPTIONAL If your integration test requires Python libraries or modules from other collections
# # Install them like this
# - name: Install collection dependencies
# run: ansible-galaxy collection install community.kubernetes -p .
# # Run the integration tests
# - name: Run integration test
# run: ansible-test integration -v --color --retry-on-error --continue-on-error --diff --python ${{ matrix.python }} --docker --coverage
# working-directory: ./ansible_collections/community/okd
# # ansible-test support producing code coverage date
# - name: Generate coverage report
# run: ansible-test coverage xml -v --requirements --group-by command --group-by version
# working-directory: ./ansible_collections/community/okd
# # See the reports at https://codecov.io/gh/ansible_collections/GITHUBORG/REPONAME
# - uses: codecov/codecov-action@v1
# with:
# fail_ci_if_error: false
#
downstream-sanity-29:
name: Sanity (Ⓐ${{ matrix.ansible }}+py${{ matrix.python }})
strategy:
matrix:
ansible:
- stable-2.9
python:
- 3.6
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v2
with:
path: ansible_collections/community/okd
- name: Set up Python ${{ matrix.ansible }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python }}
- name: Install ansible 2.9
run: pip install "ansible>=2.9.0,<2.10.0"
# run ansible-test sanity inside of Docker.
# The docker container has all the pinned dependencies that are required.
# Explicity specify the version of Python we want to test
- name: Run sanity tests
run: make downstream-test-sanity
working-directory: ./ansible_collections/community/okd
+23
View File
@@ -0,0 +1,23 @@
---
name: Changelog
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
on:
pull_request:
types:
- opened
- reopened
- labeled
- unlabeled
- synchronize
branches:
- main
- stable-*
tags:
- '*'
jobs:
changelog:
uses: ansible-network/github_actions/.github/workflows/changelog.yml@main
+29
View File
@@ -0,0 +1,29 @@
---
name: Linters
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
on:
pull_request:
types:
- opened
- reopened
- labeled
- unlabeled
- synchronize
branches:
- main
- stable-*
tags:
- '*'
jobs:
linters:
uses: ansible-network/github_actions/.github/workflows/tox-linters.yml@main
ansible-lint:
runs-on: ubuntu-latest
steps:
- uses: ansible-network/github_actions/.github/actions/checkout_dependency@main
- name: Run ansible-lint
uses: ansible/ansible-lint@v6.21.0
+23
View File
@@ -0,0 +1,23 @@
---
name: Sanity tests
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
on:
pull_request:
types:
- opened
- reopened
- synchronize
branches:
- main
- stable-*
tags:
- '*'
jobs:
sanity:
uses: ansible-network/github_actions/.github/workflows/sanity.yml@main
with:
collection_pre_install: '-r source/tests/sanity/requirements.yml'
+21
View File
@@ -0,0 +1,21 @@
---
name: Unit tests
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
on:
pull_request:
types:
- opened
- reopened
- synchronize
branches:
- main
- stable-*
tags:
- '*'
jobs:
unit-source:
uses: ansible-network/github_actions/.github/workflows/unit_source.yml@main
+3
View File
@@ -16,3 +16,6 @@ changelogs/.plugin-cache.yaml
# Temporary test files. # Temporary test files.
tests/output tests/output
tests/integration/cloud-config-* tests/integration/cloud-config-*
# Ignore the ansible_collections that the Makefile generates.
ansible_collections
+13 -31
View File
@@ -1,33 +1,15 @@
--- ---
# Based on ansible-lint config
extends: default
rules: rules:
braces: indentation:
max-spaces-inside: 1 ignore: &default_ignores |
level: error # automatically generated, we can't control it
brackets: changelogs/changelog.yaml
max-spaces-inside: 1 # Will be gone when we release and automatically reformatted
level: error changelogs/fragments/*
colons: document-start:
max-spaces-after: -1 ignore: *default_ignores
level: error line-length:
commas: ignore: *default_ignores
max-spaces-after: -1 max: 160
level: error
comments: disable ignore-from-file: .gitignore
comments-indentation: disable
document-start: disable
empty-lines:
max: 3
level: error
hyphens:
level: error
indentation: disable
key-duplicates: enable
line-length: disable
new-line-at-end-of-file: disable
new-lines:
type: unix
trailing-spaces: disable
truthy: disable
+189
View File
@@ -4,6 +4,195 @@ OKD Collection Release Notes
.. contents:: Topics .. contents:: Topics
v4.0.1
======
Bugfixes
--------
- openshift_auth - fix issue where openshift_auth module sometimes does not delete the auth token (https://github.com/openshift/community.okd/pull/242)
v4.0.0
======
Release Summary
---------------
In this major release we have removed support for ``ansible-core<2.15``.
Minor Changes
-------------
- connection/oc - added support of local enviroment variable that will be used for ``oc`` and may be requried for establishing connections ifself (https://github.com/openshift/community.okd/pull/225).
- inventory/openshift.py - Defer removal of k8s inventory plugin to version 5.0.0 (https://github.com/openshift/community.okd/pull/224).
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/openshift/community.okd/pull/226).
v3.0.1
======
Release Summary
---------------
This patch release fixes an issue in building the downstream collection.
v3.0.0
======
Release Summary
---------------
This major release drops support for ansible-core versions lower than 2.14 and Python versions lower than 3.9. It also deprecates ``openshift`` inventory plugin.
Breaking Changes / Porting Guide
--------------------------------
- Bump minimum Python suupported version to 3.9 (https://github.com/openshift/community.okd/pull/202).
- Remove support for ansible-core < 2.14 (https://github.com/openshift/community.okd/pull/202).
Deprecated Features
-------------------
- openshift - the ``openshift`` inventory plugin has been deprecated and will be removed in release 4.0.0 (https://github.com/ansible-collections/kubernetes.core/issues/31).
v2.3.0
======
Bugfixes
--------
- openshift_adm_groups_sync - initialize OpenshiftGroupSync attributes early to avoid Attribute error (https://github.com/openshift/community.okd/issues/155).
- openshift_auth - Review the way the discard process is working, add openshift algorithm to convert token to resource object name (https://github.com/openshift/community.okd/issues/176).
New Modules
-----------
- openshift_adm_prune_builds - Prune old completed and failed builds
- openshift_build - Start a new build or Cancel running, pending, or new builds.
v2.2.0
======
Minor Changes
-------------
- add action groups to runtime.yml (https://github.com/openshift/community.okd/issues/41).
Bugfixes
--------
- fix ocp auth failing against cluster api url with trailing slash (https://github.com/openshift/community.okd/issues/139)
New Modules
-----------
- openshift_adm_migrate_template_instances - Update TemplateInstances to point to the latest group-version-kinds
- openshift_adm_prune_auth - Removes references to the specified roles, clusterroles, users, and groups
- openshift_adm_prune_deployments - Remove old completed and failed deployment configs
- openshift_adm_prune_images - Remove unreferenced images
- openshift_import_image - Import the latest image information from a tag in a container image registry.
- openshift_registry_info - Display information about the integrated registry.
v2.1.0
======
Minor Changes
-------------
- add support for turbo mode (https://github.com/openshift/community.okd/pull/102).
- openshift_route - Add support for Route annotations (https://github.com/ansible-collections/community.okd/pull/99).
Bugfixes
--------
- fix broken links in Automation Hub for redhat.openshift (https://github.com/openshift/community.okd/issues/100).
v2.0.1
======
Minor Changes
-------------
- increase kubernetes.core dependency version (https://github.com/openshift/community.okd/pull/97).
v2.0.0
======
Major Changes
-------------
- update to use kubernetes.core 2.0 (https://github.com/openshift/community.okd/pull/93).
Minor Changes
-------------
- Added documentation for the ``community.okd`` collection.
- openshift - inventory plugin supports FQCN ``redhat.openshift``.
Breaking Changes / Porting Guide
--------------------------------
- drop python 2 support (https://github.com/openshift/community.okd/pull/93).
Bugfixes
--------
- fixes test suite to use correct versions of python and dependencies (https://github.com/ansible-collections/community.okd/pull/89).
- openshift_process - fix module execution when template does not include a message (https://github.com/ansible-collections/community.okd/pull/87).
v1.1.2
======
Bugfixes
--------
- include requirements.txt in downstream build process (https://github.com/ansible-collections/community.okd/pull/81).
v1.1.1
======
Bugfixes
--------
- add missing requirements.txt file needed for execution environments (https://github.com/ansible-collections/community.okd/pull/78).
- openshift_route - default to ``no_log=False`` for the ``key`` parameter in TLS configuration to fix sanity failures (https://github.com/ansible-collections/community.okd/pull/77).
- restrict molecule version to <3.3.0 to address breaking change (https://github.com/ansible-collections/community.okd/pull/77).
- update CI to work with ansible 2.11 (https://github.com/ansible-collections/community.okd/pull/80).
v1.1.0
======
Minor Changes
-------------
- increase the kubernetes.core dependency version number (https://github.com/ansible-collections/community.okd/pull/71).
v1.0.2
======
Minor Changes
-------------
- restrict the version of kubernetes.core dependency (https://github.com/ansible-collections/community.okd/pull/66).
v1.0.1
======
Bugfixes
--------
- Generate downstream redhat.openshift documentation (https://github.com/ansible-collections/community.okd/pull/59).
v1.0.0
======
Minor Changes
-------------
- Released version 1 to Automation Hub as redhat.openshift (https://github.com/ansible-collections/community.okd/issues/51).
v0.3.0 v0.3.0
====== ======
+3 -3
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 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), [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. For questions about writing tests the Ansible Kubernetes community can be found on Freenode IRC as detailed below. 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.
### Code of Conduct ### Code of Conduct
@@ -58,8 +58,8 @@ Please read and familiarize yourself with this document.
### IRC ### IRC
Our IRC channels may require you to register your nickname. If you receive an error when you connect, see Our IRC channels may require you to register your nickname. If you receive an error when you connect, see
[Freenode's Nickname Registration guide](https://freenode.net/kb/answer/registration) for instructions. [Libera.Chat's Nickname Registration guide](https://libera.chat/guides/registration) for instructions.
The `#ansible-kubernetes` channel on Freenode IRC is the main and official place to discuss use and development of the `community.okd` collection. The `#ansible-kubernetes` channel on [irc.libera.chat](https://libera.chat/) is the main and official place to discuss use and development of the `community.okd` collection.
For more information about Ansible's Kubernetes and OpenShift integration, browse the resources in the [Kubernetes Working Group](https://github.com/ansible/community/wiki/Kubernetes) Community wiki page. For more information about Ansible's Kubernetes and OpenShift integration, browse the resources in the [Kubernetes Working Group](https://github.com/ansible/community/wiki/Kubernetes) Community wiki page.
+28 -16
View File
@@ -1,41 +1,53 @@
.PHONY: molecule
# Also needs to be updated in galaxy.yml # Also needs to be updated in galaxy.yml
VERSION = 0.3.0 VERSION = 4.0.1
# To run sanity tests in a venv, set SANITY_TEST_ARGS to '--venv'
SANITY_TEST_ARGS ?= --docker --color SANITY_TEST_ARGS ?= --docker --color
UNITS_TEST_ARGS ?= --docker --color
PYTHON_VERSION ?= `python3 -c 'import platform; print("{0}.{1}".format(platform.python_version_tuple()[0], platform.python_version_tuple()[1]))'`
clean: clean:
rm -f community-okd-$(VERSION).tar.gz rm -f community-okd-$(VERSION).tar.gz
rm -f redhat-openshift-$(VERSION).tar.gz
rm -rf ansible_collections rm -rf ansible_collections
build: clean build: clean
ansible-galaxy collection build ansible-galaxy collection build
install-kubernetes-src: install: build
mkdir -p ansible_collections/community/kubernetes ansible-galaxy collection install --force -p ansible_collections community-okd-$(VERSION).tar.gz
rm -rf ansible_collections/community/kubernetes/*
curl -L https://github.com/ansible-collections/community.kubernetes/archive/main.tar.gz | tar -xz -C ansible_collections/community/kubernetes --strip-components 1
# TODO: Once we no longer rely on features in main we should drop the install-kubernetes-src dependency sanity: install
install: build install-kubernetes-src cd ansible_collections/community/okd && ansible-test sanity -v --python $(PYTHON_VERSION) $(SANITY_TEST_ARGS)
ansible-galaxy collection install -p ansible_collections community-okd-$(VERSION).tar.gz
units: install
cd ansible_collections/community/okd && ansible-test units -v --python $(PYTHON_VERSION) $(UNITS_TEST_ARGS)
molecule: install
molecule test
test-integration: upstream-test-integration downstream-test-integration
test-sanity: upstream-test-sanity downstream-test-sanity
test-units: upstream-test-units downstream-test-units
test-integration-incluster: test-integration-incluster:
./ci/incluster_integration.sh ./ci/incluster_integration.sh
test-sanity: upstream-test-sanity downstream-test-sanity upstream-test-sanity: sanity
test-integration: upstream-test-integration downstream-test-integration upstream-test-units: units
upstream-test-integration: install upstream-test-integration: molecule
molecule test
upstream-test-sanity: install
cd ansible_collections/community/okd && ansible-test sanity --exclude ci/ -v $(SANITY_TEST_ARGS)
downstream-test-sanity: downstream-test-sanity:
./ci/downstream.sh -s ./ci/downstream.sh -s
downstream-test-units:
./ci/downstream.sh -u
downstream-test-integration: downstream-test-integration:
./ci/downstream.sh -i ./ci/downstream.sh -i
+4 -10
View File
@@ -1,12 +1,6 @@
# This file just uses aliases defined in OWNERS_ALIASES.
approvers: approvers:
- geerlingguy - community.okd-approvers
- fabianvf
- maxamillion
- akasurde
- tima
reviewers: reviewers:
- geerlingguy - community.okd-reviewers
- fabianvf
- maxamillion
- akasurde
- tima
+11
View File
@@ -0,0 +1,11 @@
aliases:
community.okd-approvers:
- gravesm
- jillr
- alinabuzachis
- abikouo
community.okd-reviewers:
- gravesm
- jillr
- alinabuzachis
- abikouo
+88 -29
View File
@@ -1,26 +1,66 @@
# OKD/OpenShift Collection for Ansible # OKD Collection for Ansible
<!--- STARTREMOVE --->
[![CI](https://github.com/ansible-collections/community.okd/workflows/CI/badge.svg?event=push)](https://github.com/ansible-collections/community.okd/actions) [![Codecov](https://img.shields.io/codecov/c/github/ansible-collections/community.okd)](https://codecov.io/gh/ansible-collections/community.okd) [![CI](https://github.com/ansible-collections/community.okd/workflows/CI/badge.svg?event=push)](https://github.com/ansible-collections/community.okd/actions) [![Codecov](https://img.shields.io/codecov/c/github/ansible-collections/community.okd)](https://codecov.io/gh/ansible-collections/community.okd)
This repo hosts the `community.okd` Ansible Collection. This repo hosts the `community.okd` Ansible Collection.
The collection includes a variety of Ansible content to help automate the management of applications in OKD/OpenShift clusters, as well as the provisioning and maintenance of clusters themselves. The collection includes a variety of Ansible content to help automate the management of applications in OKD clusters, as well as the provisioning and maintenance of clusters themselves.
<!--start requires_ansible-->
## Ansible version compatibility
This collection has been tested against following Ansible versions: **>=2.15.0**.
Please ensure to update the `network_os` to use the fully qualified collection name (for example, `cisco.ios.ios`).
Plugins and modules within a collection may be tested with only specific Ansible versions.
A collection may contain metadata that identifies these versions.
PEP440 is the schema used to describe the versions of Ansible.
<!--end requires_ansible-->
## Python Support
* Collection supports 3.9+
## Kubernetes Version Support
This collection supports Kubernetes versions >=1.24.
## Included content ## Included content
Click on the name of a plugin or module to view that content's documentation: Click on the name of a plugin or module to view that content's documentation:
- **Connection Plugins**: <!--start collection content-->
- [oc](https://docs.ansible.com/ansible/2.10/collections/community/general/oc_connection.html) ### Connection plugins
- **Inventory Plugins**: Name | Description
- [openshift](https://docs.ansible.com/ansible/2.10/collections/community/kubernetes/openshift_inventory.html) --- | ---
- **Modules**: [community.okd.oc](https://github.com/openshift/community.okd/blob/main/docs/community.okd.oc_connection.rst)|Execute tasks in pods running on OpenShift.
- [k8s](https://docs.ansible.com/ansible/2.10/collections/community/kubernetes/k8s_inventory.html)
- [openshift_auth](https://github.com/ansible-collections/community.okd/blob/main/plugins/modules/openshift_auth.py)
- [openshift_process](https://github.com/ansible-collections/community.okd/blob/main/plugins/modules/openshift_process.py)
- [openshift_route](https://github.com/ansible-collections/community.okd/blob/main/plugins/modules/openshift_route.py)
> **Note**: Some of these documentation links currently link to older module versions. For the latest module documentation, please use `ansible-doc` in the CLI. ### Inventory plugins
Name | Description
--- | ---
[community.okd.openshift](https://github.com/openshift/community.okd/blob/main/docs/community.okd.openshift_inventory.rst)|OpenShift inventory source
### Modules
Name | Description
--- | ---
[community.okd.k8s](https://github.com/openshift/community.okd/blob/main/docs/community.okd.k8s_module.rst)|Manage OpenShift objects
[community.okd.openshift_adm_groups_sync](https://github.com/openshift/community.okd/blob/main/docs/community.okd.openshift_adm_groups_sync_module.rst)|Sync OpenShift Groups with records from an external provider.
[community.okd.openshift_adm_migrate_template_instances](https://github.com/openshift/community.okd/blob/main/docs/community.okd.openshift_adm_migrate_template_instances_module.rst)|Update TemplateInstances to point to the latest group-version-kinds
[community.okd.openshift_adm_prune_auth](https://github.com/openshift/community.okd/blob/main/docs/community.okd.openshift_adm_prune_auth_module.rst)|Removes references to the specified roles, clusterroles, users, and groups
[community.okd.openshift_adm_prune_builds](https://github.com/openshift/community.okd/blob/main/docs/community.okd.openshift_adm_prune_builds_module.rst)|Prune old completed and failed builds
[community.okd.openshift_adm_prune_deployments](https://github.com/openshift/community.okd/blob/main/docs/community.okd.openshift_adm_prune_deployments_module.rst)|Remove old completed and failed deployment configs
[community.okd.openshift_adm_prune_images](https://github.com/openshift/community.okd/blob/main/docs/community.okd.openshift_adm_prune_images_module.rst)|Remove unreferenced images
[community.okd.openshift_auth](https://github.com/openshift/community.okd/blob/main/docs/community.okd.openshift_auth_module.rst)|Authenticate to OpenShift clusters which require an explicit login step
[community.okd.openshift_build](https://github.com/openshift/community.okd/blob/main/docs/community.okd.openshift_build_module.rst)|Start a new build or Cancel running, pending, or new builds.
[community.okd.openshift_import_image](https://github.com/openshift/community.okd/blob/main/docs/community.okd.openshift_import_image_module.rst)|Import the latest image information from a tag in a container image registry.
[community.okd.openshift_process](https://github.com/openshift/community.okd/blob/main/docs/community.okd.openshift_process_module.rst)|Process an OpenShift template.openshift.io/v1 Template
[community.okd.openshift_registry_info](https://github.com/openshift/community.okd/blob/main/docs/community.okd.openshift_registry_info_module.rst)|Display information about the integrated registry.
[community.okd.openshift_route](https://github.com/openshift/community.okd/blob/main/docs/community.okd.openshift_route_module.rst)|Expose a Service as an OpenShift Route.
<!--end collection content-->
<!--- ENDREMOVE --->
## Installation and Usage ## Installation and Usage
@@ -36,14 +76,14 @@ You can also include it in a `requirements.yml` file and install it via `ansible
--- ---
collections: collections:
- name: community.okd - name: community.okd
version: 0.3.0 version: 4.0.1
``` ```
### Installing the OpenShift Python Library ### Installing the Kubernetes Python Library
Content in this collection requires the [OpenShift Python client](https://pypi.org/project/openshift/) to interact with Kubernetes' APIs. You can install it with: Content in this collection requires the [Kubernetes Python client](https://pypi.org/project/kubernetes/) to interact with Kubernetes' APIs. You can install it with:
pip3 install openshift pip3 install kubernetes
### Using modules from the OKD Collection in your playbooks ### Using modules from the OKD Collection in your playbooks
@@ -59,6 +99,23 @@ connections:
For documentation on how to use individual plugins included in this collection, please see the links in the 'Included content' section earlier in this README. For documentation on how to use individual plugins included in this collection, please see the links in the 'Included content' section earlier in this README.
## Ansible Turbo mode Tech Preview
The ``community.okd`` collection supports Ansible Turbo mode as a tech preview via the ``cloud.common`` collection. By default, this feature is disabled. To enable Turbo mode, set the environment variable `ENABLE_TURBO_MODE=1` on the managed node. For example:
```yaml
---
- hosts: remote
environment:
ENABLE_TURBO_MODE: 1
tasks:
...
```
Please read more about Ansible Turbo mode - [here](https://github.com/ansible-collections/community.okd/blob/main/docs/ansible_turbo_mode.rst).
<!--- STARTREMOVE --->
## Testing and Development ## Testing and Development
If you want to develop new content for this collection or improve what's already here, the easiest way to work on the collection is to clone it into one of the configured [`COLLECTIONS_PATHS`](https://docs.ansible.com/ansible/latest/reference_appendices/config.html#collections-paths), and work on it there. If you want to develop new content for this collection or improve what's already here, the easiest way to work on the collection is to clone it into one of the configured [`COLLECTIONS_PATHS`](https://docs.ansible.com/ansible/latest/reference_appendices/config.html#collections-paths), and work on it there.
@@ -83,9 +140,9 @@ These commands will create a directory called `ansible_collections` which should
### Prow ### Prow
This repository uses the OpenShift [Prow](https://github.com/kubernetes/test-infra/blob/master/prow/README.md) instance for testing against live OpenShift clusters. This repository uses the OpenShift [Prow](https://github.com/kubernetes/test-infra/blob/master/prow/README.md) instance for testing against live OpenShift clusters.
The configuration for the CI jobs that this repository runs can be found in the [`openshift/release repository`](https://github.com/openshift/release/blob/master/ci-operator/config/ansible-collections/community.okd/ansible-collections-community.okd-main.yaml). The configuration for the CI jobs that this repository runs can be found in the [`openshift/release repository`](https://github.com/openshift/release/blob/master/ci-operator/config/openshift/community.okd/openshift-community.okd-main.yaml).
The [Prow CI integration test job](https://github.com/openshift/release/blob/master/ci-operator/config/ansible-collections/community.okd/ansible-collections-community.okd-main.yaml#L35-L38) The [Prow CI integration test job](https://github.com/openshift/release/blob/master/ci-operator/config/openshift/community.okd/openshift-community.okd-main.yaml#L40-L43)
runs the command: runs the command:
make test-integration-incluster make test-integration-incluster
@@ -103,22 +160,24 @@ where the `IMAGE_FORMAT` environment variable is the full reference to your cont
Releases are automatically built and pushed to Ansible Galaxy for any new tag. Before tagging a release, make sure to do the following: Releases are automatically built and pushed to Ansible Galaxy for any new tag. Before tagging a release, make sure to do the following:
1. Update the version in the following places: 1. Update the version in the following places:
a. The `version` in `galaxy.yml` * a. The `version` in `galaxy.yml`
b. This README's `requirements.yml` example * b. This README's `requirements.yml` example
c. The `DOWNSTREAM_VERSION` in `ci/downstream.sh` * c. The `DOWNSTREAM_VERSION` in `ci/downstream.sh`
d. The `VERSION` in `Makefile` * d. The `VERSION` in `Makefile`
1. Update the CHANGELOG: * e. The version in `requirements.yml`
1. Make sure you have [`antsibull-changelog`](https://pypi.org/project/antsibull-changelog/) installed. 2. Update the CHANGELOG:
1. Make sure there are fragments for all known changes in `changelogs/fragments`. * 1. Make sure you have [`antsibull-changelog`](https://pypi.org/project/antsibull-changelog/) installed.
1. Run `antsibull-changelog release`. * 2. Make sure there are fragments for all known changes in `changelogs/fragments`.
1. Commit the changes and create a PR with the changes. Wait for tests to pass, then merge it once they have. * 3. Run `antsibull-changelog release`.
1. Tag the version in Git and push to GitHub. 3. Commit the changes and create a PR with the changes. Wait for tests to pass, then merge it once they have.
4. Tag the version in Git and push to GitHub.
After the version is published, verify it exists on the [OKD Collection Galaxy page](https://galaxy.ansible.com/community/okd). After the version is published, verify it exists on the [OKD Collection Galaxy page](https://galaxy.ansible.com/community/okd).
<!--- ENDREMOVE --->
## More Information ## More Information
For more information about Ansible's Kubernetes and OpenShift integrations, join the `#ansible-kubernetes` channel on Freenode IRC, and browse the resources in the [Kubernetes Working Group](https://github.com/ansible/community/wiki/Kubernetes) Community wiki page. For more information about Ansible's Kubernetes and OpenShift integrations, 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.
## License ## License
+189
View File
@@ -61,3 +61,192 @@ releases:
name: openshift_route name: openshift_route
namespace: '' namespace: ''
release_date: '2020-10-12' release_date: '2020-10-12'
1.0.0:
changes:
minor_changes:
- Released version 1 to Automation Hub as redhat.openshift (https://github.com/ansible-collections/community.okd/issues/51).
fragments:
- 51-redhat-openshift-ah-release.yml
release_date: '2020-11-12'
1.0.1:
changes:
bugfixes:
- Generate downstream redhat.openshift documentation (https://github.com/ansible-collections/community.okd/pull/59).
fragments:
- 59-downstream-docs.yml
release_date: '2020-11-17'
1.0.2:
changes:
minor_changes:
- restrict the version of kubernetes.core dependency (https://github.com/ansible-collections/community.okd/pull/66).
fragments:
- 66-restrict-kubernetes-core-version.yaml
release_date: '2021-02-19'
1.1.0:
changes:
minor_changes:
- increase the kubernetes.core dependency version number (https://github.com/ansible-collections/community.okd/pull/71).
fragments:
- 71-bump-kubernetes-core-version.yaml
release_date: '2021-02-23'
1.1.1:
changes:
bugfixes:
- add missing requirements.txt file needed for execution environments (https://github.com/ansible-collections/community.okd/pull/78).
- openshift_route - default to ``no_log=False`` for the ``key`` parameter in
TLS configuration to fix sanity failures (https://github.com/ansible-collections/community.okd/pull/77).
- restrict molecule version to <3.3.0 to address breaking change (https://github.com/ansible-collections/community.okd/pull/77).
- update CI to work with ansible 2.11 (https://github.com/ansible-collections/community.okd/pull/80).
fragments:
- 77-fix-ci-failure.yaml
- 78-add-requirements-file.yaml
- 80-update-ci.yaml
release_date: '2021-04-06'
1.1.2:
changes:
bugfixes:
- include requirements.txt in downstream build process (https://github.com/ansible-collections/community.okd/pull/81).
fragments:
- 81-include-requirements.yaml
release_date: '2021-04-08'
2.0.0:
changes:
breaking_changes:
- drop python 2 support (https://github.com/openshift/community.okd/pull/93).
bugfixes:
- fixes test suite to use correct versions of python and dependencies (https://github.com/ansible-collections/community.okd/pull/89).
- openshift_process - fix module execution when template does not include a
message (https://github.com/ansible-collections/community.okd/pull/87).
major_changes:
- update to use kubernetes.core 2.0 (https://github.com/openshift/community.okd/pull/93).
minor_changes:
- Added documentation for the ``community.okd`` collection.
- openshift - inventory plugin supports FQCN ``redhat.openshift``.
fragments:
- 87-openshift_process-fix-template-without-message.yaml
- 89-clean-up-ci.yaml
- 93-update-to-k8s-2.yaml
- add_docs.yml
- fqcn_inventory.yml
release_date: '2021-06-22'
2.0.1:
changes:
minor_changes:
- increase kubernetes.core dependency version (https://github.com/openshift/community.okd/pull/97).
fragments:
- 97-bump-k8s-version.yaml
release_date: '2021-06-24'
2.1.0:
changes:
bugfixes:
- fix broken links in Automation Hub for redhat.openshift (https://github.com/openshift/community.okd/issues/100).
minor_changes:
- add support for turbo mode (https://github.com/openshift/community.okd/pull/102).
- openshift_route - Add support for Route annotations (https://github.com/ansible-collections/community.okd/pull/99).
fragments:
- 0-copy_ignore_txt.yml
- 100-fix-broken-links.yml
- 102-support-turbo-mode.yaml
- 99-openshift_route-add-support-for-annotations.yml
release_date: '2021-10-20'
2.2.0:
changes:
bugfixes:
- fix ocp auth failing against cluster api url with trailing slash (https://github.com/openshift/community.okd/issues/139)
minor_changes:
- add action groups to runtime.yml (https://github.com/openshift/community.okd/issues/41).
fragments:
- 152-add-action-groups.yml
- auth-against-api-with-trailing-slash.yaml
modules:
- description: Update TemplateInstances to point to the latest group-version-kinds
name: openshift_adm_migrate_template_instances
namespace: ''
- description: Removes references to the specified roles, clusterroles, users,
and groups
name: openshift_adm_prune_auth
namespace: ''
- description: Remove old completed and failed deployment configs
name: openshift_adm_prune_deployments
namespace: ''
- description: Remove unreferenced images
name: openshift_adm_prune_images
namespace: ''
- description: Import the latest image information from a tag in a container image
registry.
name: openshift_import_image
namespace: ''
- description: Display information about the integrated registry.
name: openshift_registry_info
namespace: ''
release_date: '2022-05-05'
2.3.0:
changes:
bugfixes:
- openshift_adm_groups_sync - initialize OpenshiftGroupSync attributes early
to avoid Attribute error (https://github.com/openshift/community.okd/issues/155).
- openshift_auth - Review the way the discard process is working, add openshift
algorithm to convert token to resource object name (https://github.com/openshift/community.okd/issues/176).
fragments:
- 165-initialize-attributes-early.yml
- 178-openshift_auth-fix-revoke-token.yml
- 180-default-values-doc.yml
modules:
- description: Prune old completed and failed builds
name: openshift_adm_prune_builds
namespace: ''
- description: Start a new build or Cancel running, pending, or new builds.
name: openshift_build
namespace: ''
release_date: '2023-02-03'
3.0.0:
changes:
breaking_changes:
- Bump minimum Python suupported version to 3.9 (https://github.com/openshift/community.okd/pull/202).
- Remove support for ansible-core < 2.14 (https://github.com/openshift/community.okd/pull/202).
deprecated_features:
- openshift - the ``openshift`` inventory plugin has been deprecated and will
be removed in release 4.0.0 (https://github.com/ansible-collections/kubernetes.core/issues/31).
release_summary: This major release drops support for ansible-core versions
lower than 2.14 and Python versions lower than 3.9. It also deprecates ``openshift``
inventory plugin.
fragments:
- 20230206-deprecate-openshift-inventory.yml
- 20231107-move-sanity-and-units-to-gha.yml
release_date: '2023-11-20'
3.0.1:
changes:
release_summary: 'This patch release fixes an issue in building the downstream
collection.
'
fragments:
- downstream-gitignore.yml
- release_summary.yml
release_date: '2023-11-30'
4.0.0:
changes:
minor_changes:
- connection/oc - added support of local enviroment variable that will be used
for ``oc`` and may be requried for establishing connections ifself (https://github.com/openshift/community.okd/pull/225).
- inventory/openshift.py - Defer removal of k8s inventory plugin to version
5.0.0 (https://github.com/openshift/community.okd/pull/224).
release_summary: In this major release we have removed support for ``ansible-core<2.15``.
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/openshift/community.okd/pull/226).
fragments:
- 20240523-connection-oc-add-support-for-local-env-vars.yml
- 4.0.0.yaml
- defer_removal_of_inventory_plugin.yaml
- k8s-merge_type=json-removed.yml
release_date: '2024-05-29'
4.0.1:
changes:
minor_changes:
- openshift_auth - fix issue where openshift_auth module sometimes does not delete the auth
token. Based on stale PR (https://github.com/openshift/community.okd/pull/194).
release_summary: This is a bug fix release
fragments:
- 242-fix-failed-token-deletion.yml
release_date: '2024-12-03'
+17 -17
View File
@@ -3,28 +3,28 @@ changelog_filename_template: ../CHANGELOG.rst
changelog_filename_version_depth: 0 changelog_filename_version_depth: 0
changes_file: changelog.yaml changes_file: changelog.yaml
changes_format: combined changes_format: combined
keep_fragments: true keep_fragments: false
mention_ancestor: true mention_ancestor: true
new_plugins_after_name: removed_features new_plugins_after_name: removed_features
notesdir: fragments notesdir: fragments
prelude_section_name: release_summary prelude_section_name: release_summary
prelude_section_title: Release Summary prelude_section_title: Release Summary
sections: sections:
- - major_changes - - major_changes
- Major Changes - Major Changes
- - minor_changes - - minor_changes
- Minor Changes - Minor Changes
- - breaking_changes - - breaking_changes
- Breaking Changes / Porting Guide - Breaking Changes / Porting Guide
- - deprecated_features - - deprecated_features
- Deprecated Features - Deprecated Features
- - removed_features - - removed_features
- Removed Features (previously deprecated) - Removed Features (previously deprecated)
- - security_fixes - - security_fixes
- Security Fixes - Security Fixes
- - bugfixes - - bugfixes
- Bugfixes - Bugfixes
- - known_issues - - known_issues
- Known Issues - Known Issues
title: OKD Collection title: OKD Collection
trivial_section_name: trivial trivial_section_name: trivial
@@ -1,3 +0,0 @@
---
major_changes:
- Initial content migration from community.kubernetes (https://github.com/ansible-collections/community.okd/pull/3).
@@ -1,3 +0,0 @@
---
minor_changes:
- Dockerfile now is properly set up to run tests in a rootless container (https://github.com/ansible-collections/community.okd/pull/11).
@@ -1,3 +0,0 @@
---
minor_changes:
- Docker container can run as an arbitrary user (https://github.com/ansible-collections/community.okd/pull/12).
@@ -1,3 +0,0 @@
---
minor_changes:
- Add incluster Makefile target for CI (https://github.com/ansible-collections/community.okd/pull/13).
@@ -1,3 +0,0 @@
---
minor_changes:
- CI Documentation for working with Prow (https://github.com/ansible-collections/community.okd/pull/15).
@@ -1,3 +0,0 @@
---
minor_changes:
- Add tests for inventory plugin (https://github.com/ansible-collections/community.okd/pull/16).
@@ -1,3 +0,0 @@
---
major_changes:
- Add openshift connection plugin, update inventory plugin to use it (https://github.com/ansible-collections/community.okd/pull/18).
@@ -1,3 +0,0 @@
---
major_changes:
- Add downstream build scripts to build redhat.openshift (https://github.com/ansible-collections/community.okd/pull/20).
@@ -0,0 +1,2 @@
bugfixes:
- openshift_auth - fix issue where openshift_auth module sometimes does not delete the auth token. Based on stale PR (https://github.com/openshift/community.okd/pull/194).
@@ -1,3 +0,0 @@
---
minor_changes:
- Use the API Group APIVersion for the `Route` object (https://github.com/ansible-collections/community.okd/pull/27).
-3
View File
@@ -1,3 +0,0 @@
---
major_changes:
- openshift_auth - new module (migrated from k8s_auth in community.kubernetes) (https://github.com/ansible-collections/community.okd/pull/33).
@@ -1,3 +0,0 @@
---
minor_changes:
- Add a contribution guide (https://github.com/ansible-collections/community.okd/pull/37).
@@ -1,3 +0,0 @@
---
major_changes:
- Add openshift_route module for creating routes from services (https://github.com/ansible-collections/community.okd/pull/40).
@@ -1,3 +0,0 @@
---
major_changes:
- Add openshift_process module for template rendering and optional application of rendered resources (https://github.com/ansible-collections/community.okd/pull/44).
@@ -1,3 +0,0 @@
---
major_changes:
- Add custom k8s module, integrate better Molecule tests (https://github.com/ansible-collections/community.okd/pull/7).
-3
View File
@@ -1,3 +0,0 @@
---
minor_changes:
- Integrate stale bot for issue queue maintenance (https://github.com/ansible-collections/community.okd/pull/14).
+11 -8
View File
@@ -1,10 +1,11 @@
FROM registry.access.redhat.com/ubi8/ubi FROM registry.access.redhat.com/ubi9/ubi
ENV OPERATOR=/usr/local/bin/ansible-operator \ ENV OPERATOR=/usr/local/bin/ansible-operator \
USER_UID=1001 \ USER_UID=1001 \
USER_NAME=ansible-operator\ USER_NAME=ansible-operator\
HOME=/opt/ansible \ HOME=/opt/ansible \
ANSIBLE_LOCAL_TMP=/opt/ansible/tmp ANSIBLE_LOCAL_TMP=/opt/ansible/tmp \
DOWNSTREAM_BUILD_PYTHON=python3.9
RUN yum install -y \ RUN yum install -y \
glibc-langpack-en \ glibc-langpack-en \
@@ -14,14 +15,16 @@ RUN yum install -y \
python3-devel \ python3-devel \
python3-pip \ python3-pip \
python3-setuptools \ python3-setuptools \
&& pip3 install --no-cache-dir --upgrade setuptools pip \ gcc \
&& pip3 install --no-cache-dir \ openldap-devel \
openshift \ && python3.9 -m pip install --no-cache-dir --upgrade setuptools pip \
ansible==2.9.* \ && python3.9 -m pip install --no-cache-dir \
molecule \ kubernetes \
"ansible-core" \
"molecule" \
&& yum clean all \ && yum clean all \
&& rm -rf $HOME/.cache \ && rm -rf $HOME/.cache \
&& curl -L https://github.com/openshift/okd/releases/download/4.5.0-0.okd-2020-08-12-020541/openshift-client-linux-4.5.0-0.okd-2020-08-12-020541.tar.gz | tar -xz -C /usr/local/bin && curl -L https://github.com/openshift/okd/releases/download/4.12.0-0.okd-2023-04-16-041331/openshift-client-linux-4.12.0-0.okd-2023-04-16-041331.tar.gz | tar -xz -C /usr/local/bin
# TODO: Is there a better way to install this client in ubi8? # TODO: Is there a better way to install this client in ubi8?
COPY . /opt/ansible COPY . /opt/ansible
+97
View File
@@ -0,0 +1,97 @@
#!/usr/bin/env python
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import ast
from pathlib import PosixPath
import yaml
import argparse
import os
def read_docstring(filename):
"""
Search for assignment of the DOCUMENTATION and EXAMPLES variables in the given file.
Parse DOCUMENTATION from YAML and return the YAML doc or None together with EXAMPLES, as plain text.
"""
data = {
'doc': None,
'plainexamples': None,
'returndocs': None,
'metadata': None, # NOTE: not used anymore, kept for compat
'seealso': None,
}
string_to_vars = {
'DOCUMENTATION': 'doc',
'EXAMPLES': 'plainexamples',
'RETURN': 'returndocs',
'ANSIBLE_METADATA': 'metadata', # NOTE: now unused, but kept for backwards compat
}
try:
with open(filename, 'rb') as b_module_data:
M = ast.parse(b_module_data.read())
for child in M.body:
if isinstance(child, ast.Assign):
for t in child.targets:
try:
theid = t.id
except AttributeError:
# skip errors can happen when trying to use the normal code
# sys.stderr.write("Failed to assign id for %s on %s, skipping\n" % (t, filename))
continue
if theid in string_to_vars:
varkey = string_to_vars[theid]
if isinstance(child.value, ast.Dict):
data[varkey] = ast.literal_eval(child.value)
else:
if theid != 'EXAMPLES':
# string should be yaml if already not a dict
data[varkey] = child.value.s
# sys.stderr.write('assigned: %s\n' % varkey)
except Exception:
# sys.stderr.write("unable to parse %s" % filename)
return
return yaml.safe_load(data["doc"]) if data["doc"] is not None else None
def is_extending_collection(result, col_fqcn):
if result:
for x in result.get("extends_documentation_fragment", []):
if x.startswith(col_fqcn):
return True
return False
def main():
parser = argparse.ArgumentParser(
description="list modules with inherited doc fragments from kubernetes.core that need rendering to deal with Galaxy/AH lack of functionality."
)
parser.add_argument(
"-c", "--collection-path", type=str, default=os.getcwd(), help="path to the collection"
)
args = parser.parse_args()
path = PosixPath(args.collection_path) / PosixPath("plugins/modules")
output = []
for d in path.iterdir():
if d.is_file():
result = read_docstring(str(d))
if is_extending_collection(result, "kubernetes.core."):
output.append(d.stem.replace(".py", ""))
print("\n".join(output))
if __name__ == '__main__':
main()
+123 -68
View File
@@ -9,8 +9,9 @@
# - All functions are prefixed with f_ so it's obvious where they come # - All functions are prefixed with f_ so it's obvious where they come
# from when in use throughout the script # from when in use throughout the script
DOWNSTREAM_VERSION="0.3.0" DOWNSTREAM_VERSION="4.0.1"
KEEP_DOWNSTREAM_TMPDIR="${KEEP_DOWNSTREAM_TMPDIR:-''}" KEEP_DOWNSTREAM_TMPDIR="${KEEP_DOWNSTREAM_TMPDIR:-''}"
INSTALL_DOWNSTREAM_COLLECTION_PATH="${INSTALL_DOWNSTREAM_COLLECTION_PATH:-}"
_build_dir="" _build_dir=""
f_log_info() f_log_info()
@@ -22,6 +23,7 @@ f_show_help()
{ {
printf "Usage: downstream.sh [OPTION]\n" printf "Usage: downstream.sh [OPTION]\n"
printf "\t-s\t\tCreate a temporary downstream release and perform sanity tests.\n" printf "\t-s\t\tCreate a temporary downstream release and perform sanity tests.\n"
printf "\t-u\t\tCreate a temporary downstream release and perform units tests.\n"
printf "\t-i\t\tCreate a temporary downstream release and perform integration tests.\n" printf "\t-i\t\tCreate a temporary downstream release and perform integration tests.\n"
printf "\t-m\t\tCreate a temporary downstream release and perform molecule tests.\n" printf "\t-m\t\tCreate a temporary downstream release and perform molecule tests.\n"
printf "\t-b\t\tCreate a downstream release and stage for release.\n" printf "\t-b\t\tCreate a downstream release and stage for release.\n"
@@ -31,15 +33,25 @@ f_show_help()
f_text_sub() f_text_sub()
{ {
# Switch FQCN and dependent components # Switch FQCN and dependent components
sed -i "s/community-okd/redhat-openshift/" "${_build_dir}/Makefile" OKD_sed_files="${_build_dir}/README.md ${_build_dir}/CHANGELOG.rst ${_build_dir}/changelogs/config.yaml ${_build_dir}/ci/downstream.sh ${_build_dir}/galaxy.yml"
sed -i "s/community\/okd/redhat\/openshift/" "${_build_dir}/Makefile" # shellcheck disable=SC2068
sed -i "s/^VERSION\:/VERSION: ${DOWNSTREAM_VERSION}/" "${_build_dir}/Makefile" for okd_file in ${OKD_sed_files[@]}; do sed -i.bak "s/OKD/OpenShift/g" "${okd_file}"; done
sed -i "s/name\:.*$/name: openshift/" "${_build_dir}/galaxy.yml"
sed -i "s/namespace\:.*$/namespace: redhat/" "${_build_dir}/galaxy.yml" sed -i.bak "s/============================/==================================/" "${_build_dir}/CHANGELOG.rst"
sed -i "s/Kubernetes/OpenShift/g" "${_build_dir}/galaxy.yml" sed -i.bak "s/Ansible Galaxy/Automation Hub/" "${_build_dir}/README.md"
sed -i "s/^version\:.*$/version: ${DOWNSTREAM_VERSION}/" "${_build_dir}/galaxy.yml" sed -i.bak "s/community-okd/redhat-openshift/" "${_build_dir}/Makefile"
find ${_build_dir} -type f -exec sed -i "s/community\.kubernetes/kubernetes\.core/g" {} \; sed -i.bak "s/community\/okd/redhat\/openshift/" "${_build_dir}/Makefile"
find ${_build_dir} -type f -exec sed -i "s/community\.okd/redhat\.openshift/g" {} \; sed -i.bak "s/^VERSION\:/VERSION: ${DOWNSTREAM_VERSION}/" "${_build_dir}/Makefile"
sed -i.bak "s/name\:.*$/name: openshift/" "${_build_dir}/galaxy.yml"
sed -i.bak "s/namespace\:.*$/namespace: redhat/" "${_build_dir}/galaxy.yml"
sed -i.bak "s/Kubernetes/OpenShift/g" "${_build_dir}/galaxy.yml"
sed -i.bak "s/^version\:.*$/version: ${DOWNSTREAM_VERSION}/" "${_build_dir}/galaxy.yml"
sed -i.bak "/STARTREMOVE/,/ENDREMOVE/d" "${_build_dir}/README.md"
sed -i.bak "s/[[:space:]]okd:$/ openshift:/" "${_build_dir}/meta/runtime.yml"
find "${_build_dir}" -type f ! -name galaxy.yml -exec sed -i.bak "s/community\.okd/redhat\.openshift/g" {} \;
find "${_build_dir}" -type f ! -name galaxy.yml -exec sed -i.bak "s/group\/redhat\.openshift\.okd/redhat\.openshift\.openshift/g" {} \;
find "${_build_dir}" -type f -name "*.bak" -delete
} }
f_prep() f_prep()
@@ -51,17 +63,21 @@ f_prep()
# Files to copy downstream (relative repo root dir path) # Files to copy downstream (relative repo root dir path)
_file_manifest=( _file_manifest=(
.gitignore
CHANGELOG.rst CHANGELOG.rst
galaxy.yml galaxy.yml
LICENSE LICENSE
README.md README.md
Makefile Makefile
setup.cfg
.yamllint .yamllint
requirements.txt
requirements.yml
test-requirements.txt
) )
# Directories to recursively copy downstream (relative repo root dir path) # Directories to recursively copy downstream (relative repo root dir path)
_dir_manifest=( _dir_manifest=(
.config
changelogs changelogs
ci ci
meta meta
@@ -70,9 +86,9 @@ f_prep()
tests tests
) )
# Temp build dir
# Temp build dir
_tmp_dir=$(mktemp -d) _tmp_dir=$(mktemp -d)
_start_dir="${PWD}"
_build_dir="${_tmp_dir}/ansible_collections/redhat/openshift" _build_dir="${_tmp_dir}/ansible_collections/redhat/openshift"
mkdir -p "${_build_dir}" mkdir -p "${_build_dir}"
} }
@@ -111,42 +127,71 @@ f_create_collection_dir_structure()
do do
cp -r "./${d_name}" "${_build_dir}/${d_name}" cp -r "./${d_name}" "${_build_dir}/${d_name}"
done done
for exclude_file in "${_file_exclude[@]}"; if [ -n "${_file_exclude:-}" ]; then
do for exclude_file in "${_file_exclude[@]}";
if [[ -f "${_build_dir}/${exclude_file}" ]]; then do
rm -f "${_build_dir}/${exclude_file}" if [[ -f "${_build_dir}/${exclude_file}" ]]; then
fi rm -f "${_build_dir}/${exclude_file}"
done fi
done
fi
} }
f_install_kubernetes_core_from_src() f_handle_doc_fragments_workaround()
{ {
local community_k8s_tmpdir="${_tmp_dir}/community.kubernetes" f_log_info "${FUNCNAME[0]}"
local install_collections_dir="${_tmp_dir}/ansible_collections" local install_collections_dir="${_build_dir}/collections/"
mkdir -p "${community_k8s_tmpdir}" local temp_fragments_json="${_tmp_dir}/fragments.json"
pushd "${_tmp_dir}" local temp_start="${_tmp_dir}/startfile.txt"
# curl -L \ local temp_end="${_tmp_dir}/endfile.txt"
# https://github.com/ansible-collections/community.kubernetes/archive/main.tar.gz \ local rendered_fragments="./rendereddocfragments.txt"
# | tar -xz -C "${community_k8s_tmpdir}" --strip-components 1
# pushd "${community_k8s_tmpdir}"
# make downstream-build
# ansible-galaxy collection install -p "${install_collections_dir}" "${community_k8s_tmpdir}"/kubernetes-core-*.tar.gz
# popd
#popd
git clone https://github.com/ansible-collections/community.kubernetes "${community_k8s_tmpdir}"
pushd "${community_k8s_tmpdir}"
make downstream-build
ansible-galaxy collection install -p "${install_collections_dir}" "${community_k8s_tmpdir}"/kubernetes-core-*.tar.gz
popd
popd
}
# FIXME: Check Python interpreter from environment variable to work with prow
PYTHON=${DOWNSTREAM_BUILD_PYTHON:-/usr/bin/python3}
f_log_info "Using Python interpreter: ${PYTHON}"
# Modules with inherited doc fragments from kubernetes.core that need
# rendering to deal with Galaxy/AH lack of functionality.
# shellcheck disable=SC2207
_doc_fragment_modules=($("${PYTHON}" "${_start_dir}/ci/doc_fragment_modules.py" -c "${_start_dir}"))
# Build the collection, export docs, render them, stitch it all back together
pushd "${_build_dir}" || return
ansible-galaxy collection build
ansible-galaxy collection install --force-with-deps -p "${install_collections_dir}" ./*.tar.gz
rm ./*.tar.gz
for doc_fragment_mod in "${_doc_fragment_modules[@]}"
do
local module_py="plugins/modules/${doc_fragment_mod}.py"
f_log_info "Processing doc fragments for ${module_py}"
# We need following variable for ansible-doc only
# shellcheck disable=SC2097,SC2098
ANSIBLE_COLLECTIONS_PATH="${install_collections_dir}" \
ANSIBLE_COLLECTIONS_PATHS="${ANSIBLE_COLLECTIONS_PATH}:${install_collections_dir}" \
ansible-doc -j "redhat.openshift.${doc_fragment_mod}" > "${temp_fragments_json}"
"${PYTHON}" "${_start_dir}/ci/downstream_fragments.py" "redhat.openshift.${doc_fragment_mod}" "${temp_fragments_json}"
sed -n '/STARTREMOVE/q;p' "${module_py}" > "${temp_start}"
sed '1,/ENDREMOVE/d' "${module_py}" > "${temp_end}"
cat "${temp_start}" "${rendered_fragments}" "${temp_end}" > "${module_py}"
done
rm -f "${rendered_fragments}"
rm -fr "${install_collections_dir}"
popd
}
f_copy_collection_to_working_dir() f_copy_collection_to_working_dir()
{ {
f_log_info "${FUNCNAME[0]}" f_log_info "${FUNCNAME[0]}"
# Copy the Collection build result into original working dir # Copy the Collection build result into original working dir
f_log_info "copying built collection *.tar.gz into ./"
cp "${_build_dir}"/*.tar.gz ./ cp "${_build_dir}"/*.tar.gz ./
# Install downstream collection into provided path
if [[ -n ${INSTALL_DOWNSTREAM_COLLECTION_PATH} ]]; then
f_log_info "Install built collection *.tar.gz into ${INSTALL_DOWNSTREAM_COLLECTION_PATH}"
ansible-galaxy collection install -p "${INSTALL_DOWNSTREAM_COLLECTION_PATH}" "${_build_dir}"/*.tar.gz
fi
rm -f "${_build_dir}"/*.tar.gz
} }
f_common_steps() f_common_steps()
@@ -155,6 +200,7 @@ f_common_steps()
f_prep f_prep
f_create_collection_dir_structure f_create_collection_dir_structure
f_text_sub f_text_sub
f_handle_doc_fragments_workaround
} }
# Run the test sanity scanerio # Run the test sanity scanerio
@@ -162,20 +208,15 @@ f_test_sanity_option()
{ {
f_log_info "${FUNCNAME[0]}" f_log_info "${FUNCNAME[0]}"
f_common_steps f_common_steps
f_install_kubernetes_core_from_src
pushd "${_build_dir}" || return pushd "${_build_dir}" || return
ansible-galaxy collection build
f_log_info "SANITY TEST PWD: ${PWD}"
## Can't do this because the upstream community.kubernetes dependency logic
## is bound as a Makefile dep to the test-sanity target
#SANITY_TEST_ARGS="--docker --color --python 3.6" make test-sanity
# Run tests in docker if available, venv otherwise
if command -v docker &> /dev/null if command -v docker &> /dev/null
then then
ansible-test sanity --docker -v --exclude ci/ --color --python 3.6 make sanity
else else
ansible-test sanity --venv -v --exclude ci/ --color --python 3.6 SANITY_TEST_ARGS="--venv --color" make sanity
fi fi
f_log_info "SANITY TEST PWD: ${PWD}"
make sanity
popd || return popd || return
f_cleanup f_cleanup
} }
@@ -185,10 +226,27 @@ f_test_integration_option()
{ {
f_log_info "${FUNCNAME[0]}" f_log_info "${FUNCNAME[0]}"
f_common_steps f_common_steps
f_install_kubernetes_core_from_src
pushd "${_build_dir}" || return pushd "${_build_dir}" || return
f_log_info "INTEGRATION TEST WD: ${PWD}" f_log_info "INTEGRATION TEST WD: ${PWD}"
OVERRIDE_COLLECTION_PATH="${_tmp_dir}" molecule test make molecule
popd || return
f_cleanup
}
# Run the test units
f_test_units_option()
{
f_log_info "${FUNCNAME[0]}"
f_common_steps
pushd "${_build_dir}" || return
if command -v docker &> /dev/null
then
make units
else
UNITS_TEST_ARGS="--venv --color" make units
fi
f_log_info "UNITS TEST PWD: ${PWD}"
make units
popd || return popd || return
f_cleanup f_cleanup
} }
@@ -198,16 +256,10 @@ f_build_option()
{ {
f_log_info "${FUNCNAME[0]}" f_log_info "${FUNCNAME[0]}"
f_common_steps f_common_steps
pushd "${_build_dir}" || return pushd "${_build_dir}" || return
f_log_info "BUILD WD: ${PWD}" f_log_info "BUILD WD: ${PWD}"
# FIXME make build
# This doesn't work because we end up either recursively curl'ing popd || return
# community.kubernetes and redoing the text replacement over and over
#
# make build
ansible-galaxy collection build
popd || return
f_copy_collection_to_working_dir f_copy_collection_to_working_dir
f_cleanup f_cleanup
} }
@@ -219,22 +271,25 @@ if [[ "${#}" -eq "0" ]]; then
fi fi
# Handle options # Handle options
while getopts ":sirb" option while getopts ":siurb" option
do do
case $option in case $option in
s) s)
f_test_sanity_option f_test_sanity_option
;; ;;
i) i)
f_test_integration_option f_test_integration_option
;; ;;
r) u)
f_test_units_option
;;
r)
f_release_option f_release_option
;; ;;
b) b)
f_build_option f_build_option
;; ;;
*) *)
printf "ERROR: Unimplemented option chosen.\n" printf "ERROR: Unimplemented option chosen.\n"
f_show_help f_show_help
f_exit 1 f_exit 1
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env python
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
import sys
import yaml
with open("./rendereddocfragments.txt", 'w') as df_fd:
with open(sys.argv[2], 'r') as fd:
json_docs = json.load(fd)
# ansible-doc has introduced a 'doc.plugin_name' on branch 'stable-2.17'
# This change generated the following sanity tests error.
# invalid-documentation: DOCUMENTATION.plugin_name: extra keys not allowed @ data['plugin_name'].
# This will be removed from the module documentation
json_docs[sys.argv[1]]['doc'].pop('plugin_name', '')
json_docs[sys.argv[1]]['doc'].pop('collection', '')
json_docs[sys.argv[1]]['doc'].pop('filename', '')
json_docs[sys.argv[1]]['doc'].pop('has_action', '')
df_fd.write('DOCUMENTATION = """\n')
df_fd.write(yaml.dump(json_docs[sys.argv[1]]['doc'], default_flow_style=False))
df_fd.write('"""\n\n')
df_fd.write('EXAMPLES = """')
df_fd.write(json_docs[sys.argv[1]]['examples'])
df_fd.write('"""\n\n')
df_fd.write('RETURN = r"""')
data = json_docs[sys.argv[1]]['return']
if isinstance(data, dict):
df_fd.write(yaml.dump(data, default_flow_style=False))
else:
df_fd.write(data)
df_fd.write('"""\n\n')
+14 -8
View File
@@ -1,4 +1,4 @@
#!/bin/bash #!/bin/bash -eu
set -x set -x
@@ -11,17 +11,22 @@ NAMESPACE=${NAMESPACE:-default}
# and set the IMAGE_FORMAT environment variable so that it properly # and set the IMAGE_FORMAT environment variable so that it properly
# resolves to your image. For example, quay.io/mynamespace/$component # resolves to your image. For example, quay.io/mynamespace/$component
# would resolve to quay.io/mynamespace/molecule-test-runner # would resolve to quay.io/mynamespace/molecule-test-runner
# shellcheck disable=SC2034
component='molecule-test-runner' component='molecule-test-runner'
eval IMAGE=$IMAGE_FORMAT if [[ -n "${MOLECULE_IMAGE}" ]]; then
IMAGE="${MOLECULE_IMAGE}"
else
IMAGE="${IMAGE_FORMAT}"
fi
PULL_POLICY=${PULL_POLICY:-IfNotPresent} PULL_POLICY=${PULL_POLICY:-IfNotPresent}
if ! oc get namespace $NAMESPACE if ! oc get namespace "$NAMESPACE"
then then
oc create namespace $NAMESPACE oc create namespace "$NAMESPACE"
fi fi
oc project $NAMESPACE oc project "$NAMESPACE"
oc adm policy add-cluster-role-to-user cluster-admin -z default oc adm policy add-cluster-role-to-user cluster-admin -z default
oc adm policy who-can create projectrequests oc adm policy who-can create projectrequests
@@ -52,7 +57,7 @@ spec:
EOF EOF
function check_success { function check_success {
oc wait --for=condition=complete job/molecule-integration-test --timeout 5s -n $NAMESPACE \ oc wait --for=condition=complete job/molecule-integration-test --timeout 5s -n "$NAMESPACE" \
&& oc logs job/molecule-integration-test \ && oc logs job/molecule-integration-test \
&& echo "Molecule integration tests ran successfully" \ && echo "Molecule integration tests ran successfully" \
&& return 0 && return 0
@@ -60,14 +65,14 @@ function check_success {
} }
function check_failure { function check_failure {
oc wait --for=condition=failed job/molecule-integration-test --timeout 5s -n $NAMESPACE \ oc wait --for=condition=failed job/molecule-integration-test --timeout 5s -n "$NAMESPACE" \
&& oc logs job/molecule-integration-test \ && oc logs job/molecule-integration-test \
&& echo "Molecule integration tests failed, see logs for more information..." \ && echo "Molecule integration tests failed, see logs for more information..." \
&& return 0 && return 0
return 1 return 1
} }
runtime="15 minute" runtime="30 minute"
endtime=$(date -ud "$runtime" +%s) endtime=$(date -ud "$runtime" +%s)
echo "Waiting for test job to complete" echo "Waiting for test job to complete"
@@ -83,4 +88,5 @@ do
sleep 10 sleep 10
done done
oc logs job/molecule-integration-test
exit 1 exit 1
+147
View File
@@ -0,0 +1,147 @@
.. _ansible_turbo_mode:
******************
Ansible Turbo mode
******************
Following document provides overview of Ansible Turbo mode in ``community.okd`` collection.
.. contents::
:local:
:depth: 1
Synopsis
--------
- A brief introduction about Ansible Turbo mode in ``community.okd`` collection.
- Ansible Turbo mode is an optional performance optimization. It can be enabled by installing the cloud.common collection and setting the ``ENABLE_TURBO_MODE`` environment variable.
Requirements
------------
The following requirement is needed on the host that executes this module.
- The ``cloud.common`` collection (https://github.com/ansible-collections/cloud.common)
You will also need to set the environment variable ``ENABLE_TURBO_MODE=1`` on the managed host. This can be done in the same ways you would usually do so, for example::
---
- hosts: remote
environment:
ENABLE_TURBO_MODE: 1
tasks:
...
Installation
------------
You can install ``cloud.common`` collection using following command::
# ansible-galaxy collection install cloud.common
Current situation without Ansible Turbo mode
============================================
The traditional execution flow of an Ansible module includes the following steps:
- Upload of a ZIP archive with the module and its dependencies
- Execution of the module
- Ansible collects the results once the script is finished
These steps happen for each task of a playbook, and on every host.
Most of the time, the execution of a module is fast enough for
the user. However, sometime the module requires significant amount of time,
just to initialize itself. This is a common situation with the API based modules.
A classic initialization involves the following steps:
- Load a Python library to access the remote resource (via SDK)
- Open a client
- Load a bunch of Python modules.
- Request a new TCP connection.
- Create a session.
- Authenticate the client.
All these steps are time consuming and the same operations will be running again and again.
For instance, here:
- ``import openstack``: takes 0.569s
- ``client = openstack.connect()``: takes 0.065s
- ``client.authorize()``: takes 1.360s,
These numbers are from test running against VexxHost public cloud.
In this case, it's a 2s-ish overhead per task. If the playbook
comes with 10 tasks, the execution time cannot go below 20s.
How Ansible Turbo Module improve the situation
==============================================
``AnsibleTurboModule`` is actually a class that inherites from
the standard ``AnsibleModule`` class that your modules probably
already use.
The big difference is that when a module starts, it also spawns
a little Python daemon. If a daemon already exists, it will just
reuse it.
All the module logic is run inside this Python daemon. This means:
- Python modules are actually loaded one time
- Ansible module can reuse an existing authenticated session.
The background service
======================
The daemon kills itself after 15s, and communication are done
through an Unix socket.
It runs in one single process and uses ``asyncio`` internally.
Consequently you can use the ``async`` keyword in your Ansible module.
This will be handy if you interact with a lot of remote systems
at the same time.
Security impact
===============
``ansible_module.turbo`` open an Unix socket to interact with the background service.
We use this service to open the connection toward the different target systems.
This is similar to what SSH does with the sockets.
Keep in mind that:
- All the modules can access the same cache. Soon an isolation will be done at the collection level (https://github.com/ansible-collections/cloud.common/pull/17)
- A task can load a different version of a library and impact the next tasks.
- If the same user runs two ``ansible-playbook`` at the same time, they will have access to the same cache.
When a module stores a session in a cache, it's a good idea to use a hash of the authentication information to identify the session.
Error management
================
``ansible_module.turbo`` uses exceptions to communicate a result back to the module.
- ``EmbeddedModuleFailure`` is raised when ``json_fail()`` is called.
- ``EmbeddedModuleSuccess`` is raised in case of success and returns the result to the origin module process.
These exceptions are defined in ``ansible_collections.cloud.common.plugins.module_utils.turbo.exceptions``.
You can raise ``EmbeddedModuleFailure`` exception yourself, for instance from a module in ``module_utils``.
.. note:: Be careful with the ``except Exception:`` blocks.
Not only they are bad practice, but also may interface with this
mechanism.
Troubleshooting
===============
You may want to manually start the server. This can be done with the following command:
.. code-block:: shell
PYTHONPATH=$HOME/.ansible/collections python -m ansible_collections.cloud.common.plugins.module_utils.turbo.server --socket-path $HOME/.ansible/tmp/turbo_mode.kubernetes.core.socket
You can use the ``--help`` argument to get a list of the optional parameters.
File diff suppressed because it is too large Load Diff
+336
View File
@@ -0,0 +1,336 @@
.. _community.okd.oc_connection:
****************
community.okd.oc
****************
**Execute tasks in pods running on OpenShift.**
.. contents::
:local:
:depth: 1
Synopsis
--------
- Use the oc exec command to run tasks in, or put/fetch files to, pods running on the OpenShift container platform.
Requirements
------------
The below requirements are needed on the local Ansible controller node that executes this connection.
- oc (go binary)
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>Configuration</th>
<th width="100%">Comments</th>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>ca_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">""</div>
</td>
<td>
<div>env:K8S_AUTH_SSL_CA_CERT</div>
<div>var: ansible_oc_ssl_ca_cert</div>
<div>var: ansible_oc_ca_cert</div>
</td>
<td>
<div>Path to a CA certificate used to authenticate with the API.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: oc_ssl_ca_cert</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">""</div>
</td>
<td>
<div>env:K8S_AUTH_CERT_FILE</div>
<div>var: ansible_oc_cert_file</div>
<div>var: ansible_oc_client_cert</div>
</td>
<td>
<div>Path to a certificate used to authenticate with the API.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: oc_cert_file</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">""</div>
</td>
<td>
<div>env:K8S_AUTH_KEY_FILE</div>
<div>var: ansible_oc_key_file</div>
<div>var: ansible_oc_client_key</div>
</td>
<td>
<div>Path to a key file used to authenticate with the API.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: oc_key_file</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>oc_container</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">""</div>
</td>
<td>
<div>env:K8S_AUTH_CONTAINER</div>
<div>var: ansible_oc_container</div>
</td>
<td>
<div>Container name. Required when a pod contains more than one container.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>oc_context</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">""</div>
</td>
<td>
<div>env:K8S_AUTH_CONTEXT</div>
<div>var: ansible_oc_context</div>
</td>
<td>
<div>The name of a context found in the K8s config file.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>oc_extra_args</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">""</div>
</td>
<td>
<div>env:K8S_AUTH_EXTRA_ARGS</div>
<div>var: ansible_oc_extra_args</div>
</td>
<td>
<div>Extra arguments to pass to the oc command line.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>oc_host</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">""</div>
</td>
<td>
<div>env:K8S_AUTH_HOST</div>
<div>env:K8S_AUTH_SERVER</div>
<div>var: ansible_oc_host</div>
<div>var: ansible_oc_server</div>
</td>
<td>
<div>URL for accessing the API.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>oc_kubeconfig</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">""</div>
</td>
<td>
<div>env:K8S_AUTH_KUBECONFIG</div>
<div>var: ansible_oc_kubeconfig</div>
<div>var: ansible_oc_config</div>
</td>
<td>
<div>Path to a oc config file. Defaults to <em>~/.kube/config</em></div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>oc_local_env_vars</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 4.0.0</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">{}</div>
</td>
<td>
<div>var: ansible_oc_local_env_vars</div>
</td>
<td>
<div>Local environment variable to be passed locally to the oc command line.</div>
<div>Please be aware that this passes information directly on the command line and it could expose sensitive data.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>oc_namespace</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">""</div>
</td>
<td>
<div>env:K8S_AUTH_NAMESPACE</div>
<div>var: ansible_oc_namespace</div>
</td>
<td>
<div>The namespace of the pod</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>oc_pod</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">""</div>
</td>
<td>
<div>env:K8S_AUTH_POD</div>
<div>var: ansible_oc_pod</div>
</td>
<td>
<div>Pod name. Required when the host name does not match pod name.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>oc_token</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
<div>env:K8S_AUTH_TOKEN</div>
<div>env:K8S_AUTH_API_KEY</div>
<div>var: ansible_oc_token</div>
<div>var: ansible_oc_api_key</div>
</td>
<td>
<div>API authentication bearer token.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>validate_certs</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">""</div>
</td>
<td>
<div>env:K8S_AUTH_VERIFY_SSL</div>
<div>var: ansible_oc_verify_ssl</div>
<div>var: ansible_oc_validate_certs</div>
</td>
<td>
<div>Whether or not to verify the API server&#x27;s SSL certificate. Defaults to <em>true</em>.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: oc_verify_ssl</div>
</td>
</tr>
</table>
<br/>
Status
------
Authors
~~~~~~~
- xuxinkun (@xuxinkun)
.. hint::
Configuration entries for each entry type have a low to high priority order. For example, a variable that is lower in the list will override a variable that is higher up.
@@ -0,0 +1,582 @@
.. _community.okd.openshift_adm_groups_sync_module:
***************************************
community.okd.openshift_adm_groups_sync
***************************************
**Sync OpenShift Groups with records from an external provider.**
Version added: 2.1.0
.. contents::
:local:
:depth: 1
Synopsis
--------
- In order to sync/prune OpenShift Group records with those from an external provider, determine which Groups you wish to sync and where their records live.
- Analogous to `oc adm prune groups` and `oc adm group sync`.
- LDAP sync configuration file syntax can be found here https://docs.openshift.com/container-platform/4.9/authentication/ldap-syncing.html.
- The bindPassword attribute of the LDAP sync configuration is expected to be a string, please use ansible-vault encryption to secure this information.
Requirements
------------
The below requirements are needed on the host that executes this module.
- python >= 3.6
- kubernetes >= 12.0.0
- python-ldap
Parameters
----------
.. raw:: html
<table border=0 cellpadding=0 class="documentation-table">
<tr>
<th colspan="2">Parameter</th>
<th>Choices/<font color="blue">Defaults</font></th>
<th width="100%">Comments</th>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>allow_groups</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
/ <span style="color: purple">elements=string</span>
</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">[]</div>
</td>
<td>
<div>Allowed groups, could be openshift group name or LDAP group dn value.</div>
<div>When parameter <code>type</code> is set to <em>ldap</em> this should contains only LDAP group definition like <em>cn=developers,ou=groups,ou=rfc2307,dc=ansible,dc=redhat</em>.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>api_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Token used to authenticate with the API. Can also be specified via K8S_AUTH_API_KEY environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>ca_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to a CA certificate used to authenticate with the API. The full certificate chain must be provided to avoid certificate validation errors. Can also be specified via K8S_AUTH_SSL_CA_CERT environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: ssl_ca_cert</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to a certificate used to authenticate with the API. Can also be specified via K8S_AUTH_CERT_FILE environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: cert_file</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to a key file used to authenticate with the API. Can also be specified via K8S_AUTH_KEY_FILE environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: key_file</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>context</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>The name of a context found in the config file. Can also be specified via K8S_AUTH_CONTEXT environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>deny_groups</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
/ <span style="color: purple">elements=string</span>
</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">[]</div>
</td>
<td>
<div>Denied groups, could be openshift group name or LDAP group dn value.</div>
<div>When parameter <code>type</code> is set to <em>ldap</em> this should contains only LDAP group definition like <em>cn=developers,ou=groups,ou=rfc2307,dc=ansible,dc=redhat</em>.</div>
<div>The elements specified in this list will override the ones specified in <code>allow_groups</code>.</div>
</td>
</tr>
<tr>
<td colspan="2">
<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>
</div>
</td>
<td>
</td>
<td>
<div>Provide a URL for accessing the API. Can also be specified via K8S_AUTH_HOST environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>impersonate_groups</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
/ <span style="color: purple">elements=string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.3.0</div>
</td>
<td>
</td>
<td>
<div>Group(s) to impersonate for the operation.</div>
<div>Can also be specified via K8S_AUTH_IMPERSONATE_GROUPS environment. Example: Group1,Group2</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>impersonate_user</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.3.0</div>
</td>
<td>
</td>
<td>
<div>Username to impersonate for the operation.</div>
<div>Can also be specified via K8S_AUTH_IMPERSONATE_USER environment.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>kubeconfig</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">raw</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to an existing Kubernetes config file. If not provided, and no other connection options are provided, the Kubernetes client will attempt to load the default configuration file from <em>~/.kube/config</em>. Can also be specified via K8S_AUTH_KUBECONFIG environment variable.</div>
<div>Multiple Kubernetes config file can be provided using separator &#x27;;&#x27; for Windows platform or &#x27;:&#x27; for others platforms.</div>
<div>The kubernetes configuration can be provided as dictionary. This feature requires a python kubernetes client version &gt;= 17.17.0. Added in version 2.2.0.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>no_proxy</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.3.0</div>
</td>
<td>
</td>
<td>
<div>The comma separated list of hosts/domains/IP/CIDR that shouldn&#x27;t go through proxy. Can also be specified via K8S_AUTH_NO_PROXY environment variable.</div>
<div>Please note that this module does not pick up typical proxy settings from the environment (e.g. NO_PROXY).</div>
<div>This feature requires kubernetes&gt;=19.15.0. When kubernetes library is less than 19.15.0, it fails even no_proxy set in correct.</div>
<div>example value is &quot;localhost,.local,.example.com,127.0.0.1,127.0.0.0/8,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16&quot;</div>
</td>
</tr>
<tr>
<td colspan="2">
<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>Provide a password for authenticating with the API. Can also be specified via K8S_AUTH_PASSWORD environment variable.</div>
<div>Please read the description of the <code>username</code> option for a discussion of when this option is applicable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>persist_config</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>no</li>
<li>yes</li>
</ul>
</td>
<td>
<div>Whether or not to save the kube config refresh tokens. Can also be specified via K8S_AUTH_PERSIST_CONFIG environment variable.</div>
<div>When the k8s context is using a user credentials with refresh tokens (like oidc or gke/gcloud auth), the token is refreshed by the k8s python client library but not saved by default. So the old refresh token can expire and the next auth might fail. Setting this flag to true will tell the k8s python client to save the new refresh token to the kube config file.</div>
<div>Default to false.</div>
<div>Please note that the current version of the k8s python client library does not support setting this flag to True yet.</div>
<div>The fix for this k8s python library is here: https://github.com/kubernetes-client/python-base/pull/169</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>The URL of an HTTP proxy to use for the connection. Can also be specified via K8S_AUTH_PROXY environment variable.</div>
<div>Please note that this module does not pick up typical proxy settings from the environment (e.g. HTTP_PROXY).</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy_headers</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.0.0</div>
</td>
<td>
</td>
<td>
<div>The Header used for the HTTP proxy.</div>
<div>Documentation can be found here <a href='https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html?highlight=proxy_headers#urllib3.util.make_headers'>https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html?highlight=proxy_headers#urllib3.util.make_headers</a>.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>basic_auth</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Colon-separated username:password for basic authentication header.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_BASIC_AUTH environment.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy_basic_auth</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Colon-separated username:password for proxy basic authentication header.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_PROXY_BASIC_AUTH environment.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>user_agent</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>String representing the user-agent you want, such as foo/1.0.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_USER_AGENT environment.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<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>absent</li>
<li><div style="color: blue"><b>present</b>&nbsp;&larr;</div></li>
</ul>
</td>
<td>
<div>Determines if the group should be sync when set to <code>present</code> or pruned when set to <code>absent</code>.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>sync_config</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
/ <span style="color: red">required</span>
</div>
</td>
<td>
</td>
<td>
<div>Provide a valid YAML definition of an LDAP sync configuration.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: config, src</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>type</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>ldap</b>&nbsp;&larr;</div></li>
<li>openshift</li>
</ul>
</td>
<td>
<div>which groups allow and deny list entries refer to.</div>
</td>
</tr>
<tr>
<td colspan="2">
<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>Provide a username for authenticating with the API. Can also be specified via K8S_AUTH_USERNAME environment variable.</div>
<div>Please note that this only works with clusters configured to use HTTP Basic Auth. If your cluster has a different form of authentication (e.g. OAuth2 in OpenShift), this option will not work as expected and you should look into the <span class='module'>community.okd.k8s_auth</span> module, as that might do what you need.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>validate_certs</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>no</li>
<li>yes</li>
</ul>
</td>
<td>
<div>Whether or not to verify the API server&#x27;s SSL certificates. Can also be specified via K8S_AUTH_VERIFY_SSL environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: verify_ssl</div>
</td>
</tr>
</table>
<br/>
Notes
-----
.. note::
- To avoid SSL certificate validation errors when ``validate_certs`` is *True*, the full certificate chain for the API server must be provided via ``ca_cert`` or in the kubeconfig file.
Examples
--------
.. code-block:: yaml
# Prune all orphaned groups
- name: Prune all orphan groups
openshift_adm_groups_sync:
state: absent
src: "{{ lookup('file', '/path/to/ldap-sync-config.yaml') | from_yaml }}"
# Prune all orphaned groups from a list of specific groups specified in allow_groups
- name: Prune all orphan groups from a list of specific groups specified in allow_groups
openshift_adm_groups_sync:
state: absent
src: "{{ lookup('file', '/path/to/ldap-sync-config.yaml') | from_yaml }}"
allow_groups:
- cn=developers,ou=groups,ou=rfc2307,dc=ansible,dc=redhat
- cn=developers,ou=groups,ou=rfc2307,dc=ansible,dc=redhat
# Sync all groups from an LDAP server
- name: Sync all groups from an LDAP server
openshift_adm_groups_sync:
src:
kind: LDAPSyncConfig
apiVersion: v1
url: ldap://localhost:1390
insecure: true
bindDN: cn=admin,dc=example,dc=org
bindPassword: adminpassword
rfc2307:
groupsQuery:
baseDN: "cn=admins,ou=groups,dc=example,dc=org"
scope: sub
derefAliases: never
filter: (objectClass=*)
pageSize: 0
groupUIDAttribute: dn
groupNameAttributes: [cn]
groupMembershipAttributes: [member]
usersQuery:
baseDN: "ou=users,dc=example,dc=org"
scope: sub
derefAliases: never
pageSize: 0
userUIDAttribute: dn
userNameAttributes: [mail]
tolerateMemberNotFoundErrors: true
tolerateMemberOutOfScopeErrors: true
# Sync all groups except the ones from the deny_groups from an LDAP server
- name: Sync all groups from an LDAP server using deny_groups
openshift_adm_groups_sync:
src: "{{ lookup('file', '/path/to/ldap-sync-config.yaml') | from_yaml }}"
deny_groups:
- cn=developers,ou=groups,ou=rfc2307,dc=ansible,dc=redhat
- cn=developers,ou=groups,ou=rfc2307,dc=ansible,dc=redhat
# Sync all OpenShift Groups that have been synced previously with an LDAP server
- name: Sync all OpenShift Groups that have been synced previously with an LDAP server
openshift_adm_groups_sync:
src: "{{ lookup('file', '/path/to/ldap-sync-config.yaml') | from_yaml }}"
type: openshift
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>builds</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
/ <span style="color: purple">elements=dictionary</span>
</div>
</td>
<td>success</td>
<td>
<div>The groups that were created, updated or deleted</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;">[{&#x27;apiVersion&#x27;: &#x27;user.openshift.io/v1&#x27;, &#x27;kind&#x27;: &#x27;Group&#x27;, &#x27;metadata&#x27;: {&#x27;annotations&#x27;: {&#x27;openshift.io/ldap.sync-time&#x27;: &#x27;2021-12-17T12:20:28.125282&#x27;, &#x27;openshift.io/ldap.uid&#x27;: &#x27;cn=developers,ou=groups,ou=rfc2307,dc=ansible,dc=redhat&#x27;, &#x27;openshift.io/ldap.url&#x27;: &#x27;localhost:1390&#x27;}, &#x27;creationTimestamp&#x27;: &#x27;2021-12-17T11:09:49Z&#x27;, &#x27;labels&#x27;: {&#x27;openshift.io/ldap.host&#x27;: &#x27;localhost&#x27;}, &#x27;managedFields&#x27;: [{&#x27;apiVersion&#x27;: &#x27;user.openshift.io/v1&#x27;, &#x27;fieldsType&#x27;: &#x27;FieldsV1&#x27;, &#x27;fieldsV1&#x27;: {&#x27;f:metadata&#x27;: {&#x27;f:annotations&#x27;: {&#x27;.&#x27;: {}, &#x27;f:openshift.io/ldap.sync-time&#x27;: {}, &#x27;f:openshift.io/ldap.uid&#x27;: {}, &#x27;f:openshift.io/ldap.url&#x27;: {}}, &#x27;f:labels&#x27;: {&#x27;.&#x27;: {}, &#x27;f:openshift.io/ldap.host&#x27;: {}}}, &#x27;f:users&#x27;: {}}, &#x27;manager&#x27;: &#x27;OpenAPI-Generator&#x27;, &#x27;operation&#x27;: &#x27;Update&#x27;, &#x27;time&#x27;: &#x27;2021-12-17T11:09:49Z&#x27;}], &#x27;name&#x27;: &#x27;developers&#x27;, &#x27;resourceVersion&#x27;: &#x27;2014696&#x27;, &#x27;uid&#x27;: &#x27;8dc211cb-1544-41e1-96b1-efffeed2d7d7&#x27;}, &#x27;users&#x27;: [&#x27;jordanbulls@ansible.org&#x27;]}]</div>
</td>
</tr>
</table>
<br/><br/>
Status
------
Authors
~~~~~~~
- Aubin Bikouo (@abikouo)
@@ -0,0 +1,587 @@
.. _community.okd.openshift_adm_migrate_template_instances_module:
******************************************************
community.okd.openshift_adm_migrate_template_instances
******************************************************
**Update TemplateInstances to point to the latest group-version-kinds**
Version added: 2.2.0
.. contents::
:local:
:depth: 1
Synopsis
--------
- Update TemplateInstances to point to the latest group-version-kinds.
- Analogous to ``oc adm migrate template-instances``.
Requirements
------------
The below requirements are needed on the host that executes this module.
- python >= 3.6
- kubernetes >= 12.0.0
Parameters
----------
.. raw:: html
<table border=0 cellpadding=0 class="documentation-table">
<tr>
<th colspan="2">Parameter</th>
<th>Choices/<font color="blue">Defaults</font></th>
<th width="100%">Comments</th>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>api_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Token used to authenticate with the API. Can also be specified via K8S_AUTH_API_KEY environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>ca_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to a CA certificate used to authenticate with the API. The full certificate chain must be provided to avoid certificate validation errors. Can also be specified via K8S_AUTH_SSL_CA_CERT environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: ssl_ca_cert</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to a certificate used to authenticate with the API. Can also be specified via K8S_AUTH_CERT_FILE environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: cert_file</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to a key file used to authenticate with the API. Can also be specified via K8S_AUTH_KEY_FILE environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: key_file</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>context</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>The name of a context found in the config file. Can also be specified via K8S_AUTH_CONTEXT environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<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>
</div>
</td>
<td>
</td>
<td>
<div>Provide a URL for accessing the API. Can also be specified via K8S_AUTH_HOST environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>impersonate_groups</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
/ <span style="color: purple">elements=string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.3.0</div>
</td>
<td>
</td>
<td>
<div>Group(s) to impersonate for the operation.</div>
<div>Can also be specified via K8S_AUTH_IMPERSONATE_GROUPS environment. Example: Group1,Group2</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>impersonate_user</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.3.0</div>
</td>
<td>
</td>
<td>
<div>Username to impersonate for the operation.</div>
<div>Can also be specified via K8S_AUTH_IMPERSONATE_USER environment.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>kubeconfig</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">raw</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to an existing Kubernetes config file. If not provided, and no other connection options are provided, the Kubernetes client will attempt to load the default configuration file from <em>~/.kube/config</em>. Can also be specified via K8S_AUTH_KUBECONFIG environment variable.</div>
<div>Multiple Kubernetes config file can be provided using separator &#x27;;&#x27; for Windows platform or &#x27;:&#x27; for others platforms.</div>
<div>The kubernetes configuration can be provided as dictionary. This feature requires a python kubernetes client version &gt;= 17.17.0. Added in version 2.2.0.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>namespace</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>The namespace that the template can be found in.</div>
<div>If no namespace if specified, migrate objects in all namespaces.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>no_proxy</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.3.0</div>
</td>
<td>
</td>
<td>
<div>The comma separated list of hosts/domains/IP/CIDR that shouldn&#x27;t go through proxy. Can also be specified via K8S_AUTH_NO_PROXY environment variable.</div>
<div>Please note that this module does not pick up typical proxy settings from the environment (e.g. NO_PROXY).</div>
<div>This feature requires kubernetes&gt;=19.15.0. When kubernetes library is less than 19.15.0, it fails even no_proxy set in correct.</div>
<div>example value is &quot;localhost,.local,.example.com,127.0.0.1,127.0.0.0/8,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16&quot;</div>
</td>
</tr>
<tr>
<td colspan="2">
<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>Provide a password for authenticating with the API. Can also be specified via K8S_AUTH_PASSWORD environment variable.</div>
<div>Please read the description of the <code>username</code> option for a discussion of when this option is applicable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>persist_config</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>no</li>
<li>yes</li>
</ul>
</td>
<td>
<div>Whether or not to save the kube config refresh tokens. Can also be specified via K8S_AUTH_PERSIST_CONFIG environment variable.</div>
<div>When the k8s context is using a user credentials with refresh tokens (like oidc or gke/gcloud auth), the token is refreshed by the k8s python client library but not saved by default. So the old refresh token can expire and the next auth might fail. Setting this flag to true will tell the k8s python client to save the new refresh token to the kube config file.</div>
<div>Default to false.</div>
<div>Please note that the current version of the k8s python client library does not support setting this flag to True yet.</div>
<div>The fix for this k8s python library is here: https://github.com/kubernetes-client/python-base/pull/169</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>The URL of an HTTP proxy to use for the connection. Can also be specified via K8S_AUTH_PROXY environment variable.</div>
<div>Please note that this module does not pick up typical proxy settings from the environment (e.g. HTTP_PROXY).</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy_headers</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.0.0</div>
</td>
<td>
</td>
<td>
<div>The Header used for the HTTP proxy.</div>
<div>Documentation can be found here <a href='https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html?highlight=proxy_headers#urllib3.util.make_headers'>https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html?highlight=proxy_headers#urllib3.util.make_headers</a>.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>basic_auth</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Colon-separated username:password for basic authentication header.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_BASIC_AUTH environment.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy_basic_auth</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Colon-separated username:password for proxy basic authentication header.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_PROXY_BASIC_AUTH environment.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>user_agent</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>String representing the user-agent you want, such as foo/1.0.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_USER_AGENT environment.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<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>Provide a username for authenticating with the API. Can also be specified via K8S_AUTH_USERNAME environment variable.</div>
<div>Please note that this only works with clusters configured to use HTTP Basic Auth. If your cluster has a different form of authentication (e.g. OAuth2 in OpenShift), this option will not work as expected and you should look into the <span class='module'>community.okd.k8s_auth</span> module, as that might do what you need.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>validate_certs</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>no</li>
<li>yes</li>
</ul>
</td>
<td>
<div>Whether or not to verify the API server&#x27;s SSL certificates. Can also be specified via K8S_AUTH_VERIFY_SSL environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: verify_ssl</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>wait</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>Whether to wait for certain resource kinds to end up in the desired state.</div>
<div>By default the module exits once Kubernetes has received the request.</div>
<div>Implemented for <code>state=present</code> for <code>Deployment</code>, <code>DaemonSet</code> and <code>Pod</code>, and for <code>state=absent</code> for all resource kinds.</div>
<div>For resource kinds without an implementation, <code>wait</code> returns immediately unless <code>wait_condition</code> is set.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>wait_condition</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
</td>
<td>
</td>
<td>
<div>Specifies a custom condition on the status to wait for.</div>
<div>Ignored if <code>wait</code> is not set or is set to False.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>reason</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>The value of the reason field in your desired condition</div>
<div>For example, if a <code>Deployment</code> is paused, The <code>Progressing</code> <code>type</code> will have the <code>DeploymentPaused</code> reason.</div>
<div>The possible reasons in a condition are specific to each resource type in Kubernetes.</div>
<div>See the API documentation of the status field for a given resource to see possible choices.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>status</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>True</b>&nbsp;&larr;</div></li>
<li>False</li>
<li>Unknown</li>
</ul>
</td>
<td>
<div>The value of the status field in your desired condition.</div>
<div>For example, if a <code>Deployment</code> is paused, the <code>Progressing</code> <code>type</code> will have the <code>Unknown</code> status.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>type</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>The type of condition to wait for.</div>
<div>For example, the <code>Pod</code> resource will set the <code>Ready</code> condition (among others).</div>
<div>Required if you are specifying a <code>wait_condition</code>.</div>
<div>If left empty, the <code>wait_condition</code> field will be ignored.</div>
<div>The possible types for a condition are specific to each resource type in Kubernetes.</div>
<div>See the API documentation of the status field for a given resource to see possible choices.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>wait_sleep</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">integer</span>
</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">5</div>
</td>
<td>
<div>Number of seconds to sleep between checks.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>wait_timeout</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">integer</span>
</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">120</div>
</td>
<td>
<div>How long in seconds to wait for the resource to end up in the desired state.</div>
<div>Ignored if <code>wait</code> is not set.</div>
</td>
</tr>
</table>
<br/>
Notes
-----
.. note::
- To avoid SSL certificate validation errors when ``validate_certs`` is *True*, the full certificate chain for the API server must be provided via ``ca_cert`` or in the kubeconfig file.
Examples
--------
.. code-block:: yaml
- name: Migrate TemplateInstances in namespace=test
community.okd.openshift_adm_migrate_template_instances:
namespace: test
register: _result
- name: Migrate TemplateInstances in all namespaces
community.okd.openshift_adm_migrate_template_instances:
register: _result
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>result</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
/ <span style="color: purple">elements=dictionary</span>
</div>
</td>
<td>success</td>
<td>
<div>List with all TemplateInstances that have been migrated.</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;">[{&#x27;apiVersion&#x27;: &#x27;template.openshift.io/v1&#x27;, &#x27;kind&#x27;: &#x27;TemplateInstance&#x27;, &#x27;metadata&#x27;: {&#x27;creationTimestamp&#x27;: &#x27;2021-11-10T11:12:09Z&#x27;, &#x27;finalizers&#x27;: [&#x27;template.openshift.io/finalizer&#x27;], &#x27;managedFields&#x27;: [{&#x27;apiVersion&#x27;: &#x27;template.openshift.io/v1&#x27;, &#x27;fieldsType&#x27;: &#x27;FieldsV1&#x27;, &#x27;fieldsV1&#x27;: {&#x27;f:spec&#x27;: {&#x27;f:template&#x27;: {&#x27;f:metadata&#x27;: {&#x27;f:name&#x27;: {}}, &#x27;f:objects&#x27;: {}, &#x27;f:parameters&#x27;: {}}}}, &#x27;manager&#x27;: &#x27;kubectl-create&#x27;, &#x27;operation&#x27;: &#x27;Update&#x27;, &#x27;time&#x27;: &#x27;2021-11-10T11:12:09Z&#x27;}, {&#x27;apiVersion&#x27;: &#x27;template.openshift.io/v1&#x27;, &#x27;fieldsType&#x27;: &#x27;FieldsV1&#x27;, &#x27;fieldsV1&#x27;: {&#x27;f:metadata&#x27;: {&#x27;f:finalizers&#x27;: {&#x27;.&#x27;: {}, &#x27;v:&quot;template.openshift.io/finalizer&quot;&#x27;: {}}}, &#x27;f:status&#x27;: {&#x27;f:conditions&#x27;: {}}}, &#x27;manager&#x27;: &#x27;openshift-controller-manager&#x27;, &#x27;operation&#x27;: &#x27;Update&#x27;, &#x27;time&#x27;: &#x27;2021-11-10T11:12:09Z&#x27;}, {&#x27;apiVersion&#x27;: &#x27;template.openshift.io/v1&#x27;, &#x27;fieldsType&#x27;: &#x27;FieldsV1&#x27;, &#x27;fieldsV1&#x27;: {&#x27;f:status&#x27;: {&#x27;f:objects&#x27;: {}}}, &#x27;manager&#x27;: &#x27;OpenAPI-Generator&#x27;, &#x27;operation&#x27;: &#x27;Update&#x27;, &#x27;time&#x27;: &#x27;2021-11-10T11:12:33Z&#x27;}], &#x27;name&#x27;: &#x27;demo&#x27;, &#x27;namespace&#x27;: &#x27;test&#x27;, &#x27;resourceVersion&#x27;: &#x27;545370&#x27;, &#x27;uid&#x27;: &#x27;09b795d7-7f07-4d94-bf0f-2150ee66f88d&#x27;}, &#x27;spec&#x27;: {&#x27;requester&#x27;: {&#x27;groups&#x27;: [&#x27;system:masters&#x27;, &#x27;system:authenticated&#x27;], &#x27;username&#x27;: &#x27;system:admin&#x27;}, &#x27;template&#x27;: {&#x27;metadata&#x27;: {&#x27;creationTimestamp&#x27;: None, &#x27;name&#x27;: &#x27;template&#x27;}, &#x27;objects&#x27;: [{&#x27;apiVersion&#x27;: &#x27;v1&#x27;, &#x27;kind&#x27;: &#x27;Secret&#x27;, &#x27;metadata&#x27;: {&#x27;labels&#x27;: {&#x27;foo&#x27;: &#x27;bar&#x27;}, &#x27;name&#x27;: &#x27;secret&#x27;}}, {&#x27;apiVersion&#x27;: &#x27;apps/v1&#x27;, &#x27;kind&#x27;: &#x27;Deployment&#x27;, &#x27;metadata&#x27;: {&#x27;name&#x27;: &#x27;deployment&#x27;}, &#x27;spec&#x27;: {&#x27;replicas&#x27;: 0, &#x27;selector&#x27;: {&#x27;matchLabels&#x27;: {&#x27;key&#x27;: &#x27;value&#x27;}}, &#x27;template&#x27;: {&#x27;metadata&#x27;: {&#x27;labels&#x27;: {&#x27;key&#x27;: &#x27;value&#x27;}}, &#x27;spec&#x27;: {&#x27;containers&#x27;: [{&#x27;image&#x27;: &#x27;k8s.gcr.io/e2e-test-images/agnhost:2.32&#x27;, &#x27;name&#x27;: &#x27;hello-openshift&#x27;}]}}}}, {&#x27;apiVersion&#x27;: &#x27;v1&#x27;, &#x27;kind&#x27;: &#x27;Route&#x27;, &#x27;metadata&#x27;: {&#x27;name&#x27;: &#x27;route&#x27;}, &#x27;spec&#x27;: {&#x27;to&#x27;: {&#x27;name&#x27;: &#x27;foo&#x27;}}}], &#x27;parameters&#x27;: [{&#x27;name&#x27;: &#x27;NAME&#x27;, &#x27;value&#x27;: &#x27;${NAME}&#x27;}]}}, &#x27;status&#x27;: {&#x27;conditions&#x27;: [{&#x27;lastTransitionTime&#x27;: &#x27;2021-11-10T11:12:09Z&#x27;, &#x27;message&#x27;: &#x27;&#x27;, &#x27;reason&#x27;: &#x27;Created&#x27;, &#x27;status&#x27;: &#x27;True&#x27;, &#x27;type&#x27;: &#x27;Ready&#x27;}], &#x27;objects&#x27;: [{&#x27;ref&#x27;: {&#x27;apiVersion&#x27;: &#x27;v1&#x27;, &#x27;kind&#x27;: &#x27;Secret&#x27;, &#x27;name&#x27;: &#x27;secret&#x27;, &#x27;namespace&#x27;: &#x27;test&#x27;, &#x27;uid&#x27;: &#x27;33fad364-6d47-4f9c-9e51-92cba5602a57&#x27;}}, {&#x27;ref&#x27;: {&#x27;apiVersion&#x27;: &#x27;apps/v1&#x27;, &#x27;kind&#x27;: &#x27;Deployment&#x27;, &#x27;name&#x27;: &#x27;deployment&#x27;, &#x27;namespace&#x27;: &#x27;test&#x27;, &#x27;uid&#x27;: &#x27;3b527f88-42a1-4811-9e2f-baad4e4d8807&#x27;}}, {&#x27;ref&#x27;: {&#x27;apiVersion&#x27;: &#x27;route.openshift.io/v1.Route&#x27;, &#x27;kind&#x27;: &#x27;Route&#x27;, &#x27;name&#x27;: &#x27;route&#x27;, &#x27;namespace&#x27;: &#x27;test&#x27;, &#x27;uid&#x27;: &#x27;5b5411de-8769-4e27-ba52-6781630e4008&#x27;}}]}}, &#x27;...&#x27;]</div>
</td>
</tr>
</table>
<br/><br/>
Status
------
Authors
~~~~~~~
- Alina Buzachis (@alinabuzachis)
@@ -0,0 +1,569 @@
.. _community.okd.openshift_adm_prune_auth_module:
**************************************
community.okd.openshift_adm_prune_auth
**************************************
**Removes references to the specified roles, clusterroles, users, and groups**
Version added: 2.2.0
.. contents::
:local:
:depth: 1
Synopsis
--------
- This module allow administrators to remove references to the specified roles, clusterroles, users, and groups.
- Analogous to ``oc adm prune auth``.
Requirements
------------
The below requirements are needed on the host that executes this module.
- python >= 3.6
- kubernetes >= 12.0.0
Parameters
----------
.. raw:: html
<table border=0 cellpadding=0 class="documentation-table">
<tr>
<th colspan="2">Parameter</th>
<th>Choices/<font color="blue">Defaults</font></th>
<th width="100%">Comments</th>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>api_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Token used to authenticate with the API. Can also be specified via K8S_AUTH_API_KEY environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>ca_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to a CA certificate used to authenticate with the API. The full certificate chain must be provided to avoid certificate validation errors. Can also be specified via K8S_AUTH_SSL_CA_CERT environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: ssl_ca_cert</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to a certificate used to authenticate with the API. Can also be specified via K8S_AUTH_CERT_FILE environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: cert_file</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to a key file used to authenticate with the API. Can also be specified via K8S_AUTH_KEY_FILE environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: key_file</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>context</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>The name of a context found in the config file. Can also be specified via K8S_AUTH_CONTEXT environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<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>
</div>
</td>
<td>
</td>
<td>
<div>Provide a URL for accessing the API. Can also be specified via K8S_AUTH_HOST environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>impersonate_groups</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
/ <span style="color: purple">elements=string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.3.0</div>
</td>
<td>
</td>
<td>
<div>Group(s) to impersonate for the operation.</div>
<div>Can also be specified via K8S_AUTH_IMPERSONATE_GROUPS environment. Example: Group1,Group2</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>impersonate_user</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.3.0</div>
</td>
<td>
</td>
<td>
<div>Username to impersonate for the operation.</div>
<div>Can also be specified via K8S_AUTH_IMPERSONATE_USER environment.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>kubeconfig</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">raw</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to an existing Kubernetes config file. If not provided, and no other connection options are provided, the Kubernetes client will attempt to load the default configuration file from <em>~/.kube/config</em>. Can also be specified via K8S_AUTH_KUBECONFIG environment variable.</div>
<div>Multiple Kubernetes config file can be provided using separator &#x27;;&#x27; for Windows platform or &#x27;:&#x27; for others platforms.</div>
<div>The kubernetes configuration can be provided as dictionary. This feature requires a python kubernetes client version &gt;= 17.17.0. Added in version 2.2.0.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>label_selectors</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
/ <span style="color: purple">elements=string</span>
</div>
</td>
<td>
</td>
<td>
<div>Selector (label query) to filter on.</div>
<div>Mutually exclusive with option <em>name</em>.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>name</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Use to specify an object name to remove.</div>
<div>Mutually exclusive with option <em>label_selectors</em>.</div>
<div>If neither <em>name</em> nor <em>label_selectors</em> are specified, prune all resources in the namespace.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>namespace</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Use to specify an object namespace.</div>
<div>Ignored when <em>resource</em> is set to <code>clusterroles</code>.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>no_proxy</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.3.0</div>
</td>
<td>
</td>
<td>
<div>The comma separated list of hosts/domains/IP/CIDR that shouldn&#x27;t go through proxy. Can also be specified via K8S_AUTH_NO_PROXY environment variable.</div>
<div>Please note that this module does not pick up typical proxy settings from the environment (e.g. NO_PROXY).</div>
<div>This feature requires kubernetes&gt;=19.15.0. When kubernetes library is less than 19.15.0, it fails even no_proxy set in correct.</div>
<div>example value is &quot;localhost,.local,.example.com,127.0.0.1,127.0.0.0/8,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16&quot;</div>
</td>
</tr>
<tr>
<td colspan="2">
<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>Provide a password for authenticating with the API. Can also be specified via K8S_AUTH_PASSWORD environment variable.</div>
<div>Please read the description of the <code>username</code> option for a discussion of when this option is applicable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>persist_config</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>no</li>
<li>yes</li>
</ul>
</td>
<td>
<div>Whether or not to save the kube config refresh tokens. Can also be specified via K8S_AUTH_PERSIST_CONFIG environment variable.</div>
<div>When the k8s context is using a user credentials with refresh tokens (like oidc or gke/gcloud auth), the token is refreshed by the k8s python client library but not saved by default. So the old refresh token can expire and the next auth might fail. Setting this flag to true will tell the k8s python client to save the new refresh token to the kube config file.</div>
<div>Default to false.</div>
<div>Please note that the current version of the k8s python client library does not support setting this flag to True yet.</div>
<div>The fix for this k8s python library is here: https://github.com/kubernetes-client/python-base/pull/169</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>The URL of an HTTP proxy to use for the connection. Can also be specified via K8S_AUTH_PROXY environment variable.</div>
<div>Please note that this module does not pick up typical proxy settings from the environment (e.g. HTTP_PROXY).</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy_headers</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.0.0</div>
</td>
<td>
</td>
<td>
<div>The Header used for the HTTP proxy.</div>
<div>Documentation can be found here <a href='https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html?highlight=proxy_headers#urllib3.util.make_headers'>https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html?highlight=proxy_headers#urllib3.util.make_headers</a>.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>basic_auth</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Colon-separated username:password for basic authentication header.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_BASIC_AUTH environment.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy_basic_auth</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Colon-separated username:password for proxy basic authentication header.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_PROXY_BASIC_AUTH environment.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>user_agent</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>String representing the user-agent you want, such as foo/1.0.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_USER_AGENT environment.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>resource</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>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>roles</li>
<li>clusterroles</li>
<li>users</li>
<li>groups</li>
</ul>
</td>
<td>
<div>The specified resource to remove.</div>
</td>
</tr>
<tr>
<td colspan="2">
<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>Provide a username for authenticating with the API. Can also be specified via K8S_AUTH_USERNAME environment variable.</div>
<div>Please note that this only works with clusters configured to use HTTP Basic Auth. If your cluster has a different form of authentication (e.g. OAuth2 in OpenShift), this option will not work as expected and you should look into the <span class='module'>community.okd.k8s_auth</span> module, as that might do what you need.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>validate_certs</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>no</li>
<li>yes</li>
</ul>
</td>
<td>
<div>Whether or not to verify the API server&#x27;s SSL certificates. Can also be specified via K8S_AUTH_VERIFY_SSL environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: verify_ssl</div>
</td>
</tr>
</table>
<br/>
Notes
-----
.. note::
- To avoid SSL certificate validation errors when ``validate_certs`` is *True*, the full certificate chain for the API server must be provided via ``ca_cert`` or in the kubeconfig file.
Examples
--------
.. code-block:: yaml
- name: Prune all roles from default namespace
openshift_adm_prune_auth:
resource: roles
namespace: testing
- name: Prune clusterroles using label selectors
openshift_adm_prune_auth:
resource: roles
namespace: testing
label_selectors:
- phase=production
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>authorization</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><em>resource=users</em></td>
<td>
<div>list of OAuthClientAuthorization deleted.</div>
<br/>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>cluster_role_binding</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>list of cluster role binding deleted.</div>
<br/>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>group</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><em>resource=users</em></td>
<td>
<div>list of Security Context Constraints deleted.</div>
<br/>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>role_binding</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><em>resource=users</em> or <em>resource=groups</em> or <em>resource=clusterroles</em></td>
<td>
<div>list of role binding deleted.</div>
<br/>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>security_context_constraints</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><em>resource=users</em> or <em>resource=groups</em></td>
<td>
<div>list of Security Context Constraints deleted.</div>
<br/>
</td>
</tr>
</table>
<br/><br/>
Status
------
Authors
~~~~~~~
- Aubin Bikouo (@abikouo)
@@ -0,0 +1,571 @@
.. _community.okd.openshift_adm_prune_builds_module:
****************************************
community.okd.openshift_adm_prune_builds
****************************************
**Prune old completed and failed builds**
Version added: 2.3.0
.. contents::
:local:
:depth: 1
Synopsis
--------
- This module allow administrators to delete old completed and failed builds.
- Analogous to ``oc adm prune builds``.
Requirements
------------
The below requirements are needed on the host that executes this module.
- python >= 3.6
- kubernetes >= 12.0.0
Parameters
----------
.. raw:: html
<table border=0 cellpadding=0 class="documentation-table">
<tr>
<th colspan="2">Parameter</th>
<th>Choices/<font color="blue">Defaults</font></th>
<th width="100%">Comments</th>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>api_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Token used to authenticate with the API. Can also be specified via K8S_AUTH_API_KEY environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>ca_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to a CA certificate used to authenticate with the API. The full certificate chain must be provided to avoid certificate validation errors. Can also be specified via K8S_AUTH_SSL_CA_CERT environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: ssl_ca_cert</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to a certificate used to authenticate with the API. Can also be specified via K8S_AUTH_CERT_FILE environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: cert_file</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to a key file used to authenticate with the API. Can also be specified via K8S_AUTH_KEY_FILE environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: key_file</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>context</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>The name of a context found in the config file. Can also be specified via K8S_AUTH_CONTEXT environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<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>
</div>
</td>
<td>
</td>
<td>
<div>Provide a URL for accessing the API. Can also be specified via K8S_AUTH_HOST environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>impersonate_groups</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
/ <span style="color: purple">elements=string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.3.0</div>
</td>
<td>
</td>
<td>
<div>Group(s) to impersonate for the operation.</div>
<div>Can also be specified via K8S_AUTH_IMPERSONATE_GROUPS environment. Example: Group1,Group2</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>impersonate_user</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.3.0</div>
</td>
<td>
</td>
<td>
<div>Username to impersonate for the operation.</div>
<div>Can also be specified via K8S_AUTH_IMPERSONATE_USER environment.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>keep_younger_than</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">integer</span>
</div>
</td>
<td>
</td>
<td>
<div>Specify the minimum age (in minutes) of a Build for it to be considered a candidate for pruning.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>kubeconfig</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">raw</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to an existing Kubernetes config file. If not provided, and no other connection options are provided, the Kubernetes client will attempt to load the default configuration file from <em>~/.kube/config</em>. Can also be specified via K8S_AUTH_KUBECONFIG environment variable.</div>
<div>Multiple Kubernetes config file can be provided using separator &#x27;;&#x27; for Windows platform or &#x27;:&#x27; for others platforms.</div>
<div>The kubernetes configuration can be provided as dictionary. This feature requires a python kubernetes client version &gt;= 17.17.0. Added in version 2.2.0.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>namespace</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Use to specify namespace for builds to be deleted.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>no_proxy</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.3.0</div>
</td>
<td>
</td>
<td>
<div>The comma separated list of hosts/domains/IP/CIDR that shouldn&#x27;t go through proxy. Can also be specified via K8S_AUTH_NO_PROXY environment variable.</div>
<div>Please note that this module does not pick up typical proxy settings from the environment (e.g. NO_PROXY).</div>
<div>This feature requires kubernetes&gt;=19.15.0. When kubernetes library is less than 19.15.0, it fails even no_proxy set in correct.</div>
<div>example value is &quot;localhost,.local,.example.com,127.0.0.1,127.0.0.0/8,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16&quot;</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>orphans</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>If <code>true</code>, prune all builds whose associated BuildConfig no longer exists and whose status is complete, failed, error, or cancelled.</div>
</td>
</tr>
<tr>
<td colspan="2">
<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>Provide a password for authenticating with the API. Can also be specified via K8S_AUTH_PASSWORD environment variable.</div>
<div>Please read the description of the <code>username</code> option for a discussion of when this option is applicable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>persist_config</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>no</li>
<li>yes</li>
</ul>
</td>
<td>
<div>Whether or not to save the kube config refresh tokens. Can also be specified via K8S_AUTH_PERSIST_CONFIG environment variable.</div>
<div>When the k8s context is using a user credentials with refresh tokens (like oidc or gke/gcloud auth), the token is refreshed by the k8s python client library but not saved by default. So the old refresh token can expire and the next auth might fail. Setting this flag to true will tell the k8s python client to save the new refresh token to the kube config file.</div>
<div>Default to false.</div>
<div>Please note that the current version of the k8s python client library does not support setting this flag to True yet.</div>
<div>The fix for this k8s python library is here: https://github.com/kubernetes-client/python-base/pull/169</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>The URL of an HTTP proxy to use for the connection. Can also be specified via K8S_AUTH_PROXY environment variable.</div>
<div>Please note that this module does not pick up typical proxy settings from the environment (e.g. HTTP_PROXY).</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy_headers</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.0.0</div>
</td>
<td>
</td>
<td>
<div>The Header used for the HTTP proxy.</div>
<div>Documentation can be found here <a href='https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html?highlight=proxy_headers#urllib3.util.make_headers'>https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html?highlight=proxy_headers#urllib3.util.make_headers</a>.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>basic_auth</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Colon-separated username:password for basic authentication header.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_BASIC_AUTH environment.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy_basic_auth</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Colon-separated username:password for proxy basic authentication header.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_PROXY_BASIC_AUTH environment.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>user_agent</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>String representing the user-agent you want, such as foo/1.0.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_USER_AGENT environment.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<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>Provide a username for authenticating with the API. Can also be specified via K8S_AUTH_USERNAME environment variable.</div>
<div>Please note that this only works with clusters configured to use HTTP Basic Auth. If your cluster has a different form of authentication (e.g. OAuth2 in OpenShift), this option will not work as expected and you should look into the <span class='module'>community.okd.k8s_auth</span> module, as that might do what you need.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>validate_certs</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>no</li>
<li>yes</li>
</ul>
</td>
<td>
<div>Whether or not to verify the API server&#x27;s SSL certificates. Can also be specified via K8S_AUTH_VERIFY_SSL environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: verify_ssl</div>
</td>
</tr>
</table>
<br/>
Notes
-----
.. note::
- To avoid SSL certificate validation errors when ``validate_certs`` is *True*, the full certificate chain for the API server must be provided via ``ca_cert`` or in the kubeconfig file.
Examples
--------
.. code-block:: yaml
# Run deleting older completed and failed builds and also including
# all builds whose associated BuildConfig no longer exists
- name: Run delete orphan Builds
community.okd.openshift_adm_prune_builds:
orphans: true
# Run deleting older completed and failed builds keep younger than 2hours
- name: Run delete builds, keep younger than 2h
community.okd.openshift_adm_prune_builds:
keep_younger_than: 120
# Run deleting builds from specific namespace
- name: Run delete builds from namespace
community.okd.openshift_adm_prune_builds:
namespace: testing_namespace
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="2">Key</th>
<th>Returned</th>
<th width="100%">Description</th>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>builds</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">complex</span>
</div>
</td>
<td>success</td>
<td>
<div>The builds that were deleted</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>api_version</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>success</td>
<td>
<div>The versioned schema of this representation of an object.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>kind</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>success</td>
<td>
<div>Represents the REST resource this object represents.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>metadata</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
</td>
<td>success</td>
<td>
<div>Standard object metadata. Includes name, namespace, annotations, labels, etc.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>spec</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
</td>
<td>success</td>
<td>
<div>Specific attributes of the object. Will vary based on the <em>api_version</em> and <em>kind</em>.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>status</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
</td>
<td>success</td>
<td>
<div>Current status details for the object.</div>
<br/>
</td>
</tr>
</table>
<br/><br/>
Status
------
Authors
~~~~~~~
- Aubin Bikouo (@abikouo)
@@ -0,0 +1,483 @@
.. _community.okd.openshift_adm_prune_deployments_module:
*********************************************
community.okd.openshift_adm_prune_deployments
*********************************************
**Remove old completed and failed deployment configs**
Version added: 2.2.0
.. contents::
:local:
:depth: 1
Synopsis
--------
- This module allow administrators to remove old completed and failed deployment configs.
- Analogous to ``oc adm prune deployments``.
Requirements
------------
The below requirements are needed on the host that executes this module.
- python >= 3.6
- kubernetes >= 12.0.0
Parameters
----------
.. raw:: html
<table border=0 cellpadding=0 class="documentation-table">
<tr>
<th colspan="2">Parameter</th>
<th>Choices/<font color="blue">Defaults</font></th>
<th width="100%">Comments</th>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>api_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Token used to authenticate with the API. Can also be specified via K8S_AUTH_API_KEY environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>ca_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to a CA certificate used to authenticate with the API. The full certificate chain must be provided to avoid certificate validation errors. Can also be specified via K8S_AUTH_SSL_CA_CERT environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: ssl_ca_cert</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to a certificate used to authenticate with the API. Can also be specified via K8S_AUTH_CERT_FILE environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: cert_file</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to a key file used to authenticate with the API. Can also be specified via K8S_AUTH_KEY_FILE environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: key_file</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>context</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>The name of a context found in the config file. Can also be specified via K8S_AUTH_CONTEXT environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<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>
</div>
</td>
<td>
</td>
<td>
<div>Provide a URL for accessing the API. Can also be specified via K8S_AUTH_HOST environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>impersonate_groups</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
/ <span style="color: purple">elements=string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.3.0</div>
</td>
<td>
</td>
<td>
<div>Group(s) to impersonate for the operation.</div>
<div>Can also be specified via K8S_AUTH_IMPERSONATE_GROUPS environment. Example: Group1,Group2</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>impersonate_user</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.3.0</div>
</td>
<td>
</td>
<td>
<div>Username to impersonate for the operation.</div>
<div>Can also be specified via K8S_AUTH_IMPERSONATE_USER environment.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>keep_younger_than</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">integer</span>
</div>
</td>
<td>
</td>
<td>
<div>Specify the minimum age (in minutes) of a deployment for it to be considered a candidate for pruning.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>kubeconfig</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">raw</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to an existing Kubernetes config file. If not provided, and no other connection options are provided, the Kubernetes client will attempt to load the default configuration file from <em>~/.kube/config</em>. Can also be specified via K8S_AUTH_KUBECONFIG environment variable.</div>
<div>Multiple Kubernetes config file can be provided using separator &#x27;;&#x27; for Windows platform or &#x27;:&#x27; for others platforms.</div>
<div>The kubernetes configuration can be provided as dictionary. This feature requires a python kubernetes client version &gt;= 17.17.0. Added in version 2.2.0.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>namespace</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Use to specify namespace for deployments to be deleted.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>no_proxy</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.3.0</div>
</td>
<td>
</td>
<td>
<div>The comma separated list of hosts/domains/IP/CIDR that shouldn&#x27;t go through proxy. Can also be specified via K8S_AUTH_NO_PROXY environment variable.</div>
<div>Please note that this module does not pick up typical proxy settings from the environment (e.g. NO_PROXY).</div>
<div>This feature requires kubernetes&gt;=19.15.0. When kubernetes library is less than 19.15.0, it fails even no_proxy set in correct.</div>
<div>example value is &quot;localhost,.local,.example.com,127.0.0.1,127.0.0.0/8,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16&quot;</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>orphans</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>If <code>true</code>, prune all deployments where the associated DeploymentConfig no longer exists, the status is complete or failed, and the replica size is <code>0</code>.</div>
</td>
</tr>
<tr>
<td colspan="2">
<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>Provide a password for authenticating with the API. Can also be specified via K8S_AUTH_PASSWORD environment variable.</div>
<div>Please read the description of the <code>username</code> option for a discussion of when this option is applicable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>persist_config</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>no</li>
<li>yes</li>
</ul>
</td>
<td>
<div>Whether or not to save the kube config refresh tokens. Can also be specified via K8S_AUTH_PERSIST_CONFIG environment variable.</div>
<div>When the k8s context is using a user credentials with refresh tokens (like oidc or gke/gcloud auth), the token is refreshed by the k8s python client library but not saved by default. So the old refresh token can expire and the next auth might fail. Setting this flag to true will tell the k8s python client to save the new refresh token to the kube config file.</div>
<div>Default to false.</div>
<div>Please note that the current version of the k8s python client library does not support setting this flag to True yet.</div>
<div>The fix for this k8s python library is here: https://github.com/kubernetes-client/python-base/pull/169</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>The URL of an HTTP proxy to use for the connection. Can also be specified via K8S_AUTH_PROXY environment variable.</div>
<div>Please note that this module does not pick up typical proxy settings from the environment (e.g. HTTP_PROXY).</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy_headers</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.0.0</div>
</td>
<td>
</td>
<td>
<div>The Header used for the HTTP proxy.</div>
<div>Documentation can be found here <a href='https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html?highlight=proxy_headers#urllib3.util.make_headers'>https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html?highlight=proxy_headers#urllib3.util.make_headers</a>.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>basic_auth</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Colon-separated username:password for basic authentication header.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_BASIC_AUTH environment.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy_basic_auth</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Colon-separated username:password for proxy basic authentication header.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_PROXY_BASIC_AUTH environment.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>user_agent</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>String representing the user-agent you want, such as foo/1.0.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_USER_AGENT environment.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<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>Provide a username for authenticating with the API. Can also be specified via K8S_AUTH_USERNAME environment variable.</div>
<div>Please note that this only works with clusters configured to use HTTP Basic Auth. If your cluster has a different form of authentication (e.g. OAuth2 in OpenShift), this option will not work as expected and you should look into the <span class='module'>community.okd.k8s_auth</span> module, as that might do what you need.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>validate_certs</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>no</li>
<li>yes</li>
</ul>
</td>
<td>
<div>Whether or not to verify the API server&#x27;s SSL certificates. Can also be specified via K8S_AUTH_VERIFY_SSL environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: verify_ssl</div>
</td>
</tr>
</table>
<br/>
Notes
-----
.. note::
- To avoid SSL certificate validation errors when ``validate_certs`` is *True*, the full certificate chain for the API server must be provided via ``ca_cert`` or in the kubeconfig file.
Examples
--------
.. code-block:: yaml
- name: Prune Deployments from testing namespace
community.okd.openshift_adm_prune_deployments:
namespace: testing
- name: Prune orphans deployments, keep younger than 2hours
community.okd.openshift_adm_prune_deployments:
orphans: true
keep_younger_than: 120
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>replication_controllers</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>list of replication controllers candidate for pruning.</div>
<br/>
</td>
</tr>
</table>
<br/><br/>
Status
------
Authors
~~~~~~~
- Aubin Bikouo (@abikouo)
File diff suppressed because one or more lines are too long
@@ -0,0 +1,427 @@
.. _community.okd.openshift_auth_module:
****************************
community.okd.openshift_auth
****************************
**Authenticate to OpenShift clusters which require an explicit login step**
Version added: 0.2.0
.. contents::
:local:
:depth: 1
Synopsis
--------
- This module handles authenticating to OpenShift clusters requiring *explicit* authentication procedures, meaning ones where a client logs in (obtains an authentication token), performs API operations using said token and then logs out (revokes the token).
- On the other hand a popular configuration for username+password authentication is one utilizing HTTP Basic Auth, which does not involve any additional login/logout steps (instead login credentials can be attached to each and every API call performed) and as such is handled directly by the ``k8s`` module (and other resource–specific modules) by utilizing the ``host``, ``username`` and ``password`` parameters. Please consult your preferred module's documentation for more details.
Requirements
------------
The below requirements are needed on the host that executes this module.
- python >= 3.6
- urllib3
- requests
- requests-oauthlib
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>api_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>When <code>state</code> is set to <em>absent</em>, this specifies the token to revoke.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>ca_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to a CA certificate file used to verify connection to the API server. The full certificate chain must be provided to avoid certificate validation errors.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: ssl_ca_cert</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 API server.</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>Provide a password for authenticating with the API server.</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>If set to <em>present</em> connect to the API server using the URL specified in <code>host</code> and attempt to log in.</div>
<div>If set to <em>absent</em> attempt to log out by revoking the authentication token specified in <code>api_key</code>.</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>Provide a username for authenticating with the API server.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>validate_certs</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>no</li>
<li><div style="color: blue"><b>yes</b>&nbsp;&larr;</div></li>
</ul>
</td>
<td>
<div>Whether or not to verify the API server&#x27;s SSL certificates.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: verify_ssl</div>
</td>
</tr>
</table>
<br/>
Examples
--------
.. code-block:: yaml
- name: Example Playbook
hosts: localhost
module_defaults:
group/community.okd.okd:
host: https://k8s.example.com/
ca_cert: ca.pem
tasks:
- name: Authenticate to OpenShift cluster and gell a list of all pods from any namespace
block:
# It's good practice to store login credentials in a secure vault and not
# directly in playbooks.
- name: Include 'openshift_passwords.yml'
ansible.builtin.include_vars: openshift_passwords.yml
- name: Log in (obtain access token)
community.okd.openshift_auth:
username: admin
password: "{{ openshift_admin_password }}"
register: openshift_auth_results
# Previous task provides the token/api_key, while all other parameters
# are taken from module_defaults
- name: Get a list of all pods from any namespace
kubernetes.core.k8s_info:
api_key: "{{ openshift_auth_results.openshift_auth.api_key }}"
kind: Pod
register: pod_list
always:
- name: If login succeeded, try to log out (revoke access token)
when: openshift_auth_results.openshift_auth.api_key is defined
community.okd.openshift_auth:
state: absent
api_key: "{{ openshift_auth_results.openshift_auth.api_key }}"
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="2">Key</th>
<th>Returned</th>
<th width="100%">Description</th>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>k8s_auth</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">complex</span>
</div>
</td>
<td>success</td>
<td>
<div>Same as returned openshift_auth. Kept only for backwards compatibility</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>api_key</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>success</td>
<td>
<div>Authentication token.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>ca_cert</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>success</td>
<td>
<div>Path to a CA certificate file used to verify connection to the API server.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>host</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>success</td>
<td>
<div>URL for accessing the API server.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>username</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>success</td>
<td>
<div>Username for authenticating with the API server.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>validate_certs</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>success</td>
<td>
<div>Whether or not to verify the API server&#x27;s SSL certificates.</div>
<br/>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>openshift_auth</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">complex</span>
</div>
</td>
<td>success</td>
<td>
<div>OpenShift authentication facts.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>api_key</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>success</td>
<td>
<div>Authentication token.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>ca_cert</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>success</td>
<td>
<div>Path to a CA certificate file used to verify connection to the API server.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>host</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>success</td>
<td>
<div>URL for accessing the API server.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>username</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>success</td>
<td>
<div>Username for authenticating with the API server.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>validate_certs</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>success</td>
<td>
<div>Whether or not to verify the API server&#x27;s SSL certificates.</div>
<br/>
</td>
</tr>
</table>
<br/><br/>
Status
------
Authors
~~~~~~~
- KubeVirt Team (@kubevirt)
- Fabian von Feilitzsch (@fabianvf)
@@ -0,0 +1,844 @@
.. _community.okd.openshift_build_module:
*****************************
community.okd.openshift_build
*****************************
**Start a new build or Cancel running, pending, or new builds.**
Version added: 2.3.0
.. contents::
:local:
:depth: 1
Synopsis
--------
- This module starts a new build from the provided build config or build name.
- This module also cancel a new, pending or running build by requesting a graceful shutdown of the build. There may be a delay between requesting the build and the time the build is terminated.
- This can also restart a new build when the current is cancelled.
- Analogous to ``oc cancel-build`` and ``oc start-build``.
Requirements
------------
The below requirements are needed on the host that executes this module.
- python >= 3.6
- kubernetes >= 12.0.0
Parameters
----------
.. raw:: html
<table border=0 cellpadding=0 class="documentation-table">
<tr>
<th colspan="2">Parameter</th>
<th>Choices/<font color="blue">Defaults</font></th>
<th width="100%">Comments</th>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>api_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Token used to authenticate with the API. Can also be specified via K8S_AUTH_API_KEY environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>build_args</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
/ <span style="color: purple">elements=dictionary</span>
</div>
</td>
<td>
</td>
<td>
<div>Specify a list of key-value pair to pass to Docker during the build.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>name</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
/ <span style="color: red">required</span>
</div>
</td>
<td>
</td>
<td>
<div>docker build argument name.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>value</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>docker build argument value.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>build_config_name</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Specify the name of a build config from which a new build will be run.</div>
<div>Mutually exclusive with parameter <em>build_name</em>.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>build_name</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Specify the name of a build which should be re-run.</div>
<div>Mutually exclusive with parameter <em>build_config_name</em>.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>build_phases</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
/ <span style="color: purple">elements=string</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>New</li>
<li>Pending</li>
<li>Running</li>
</ul>
<b>Default:</b><br/><div style="color: blue">[]</div>
</td>
<td>
<div>List of state for build to cancel.</div>
<div>Ignored when <code>state=started</code>.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>ca_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to a CA certificate used to authenticate with the API. The full certificate chain must be provided to avoid certificate validation errors. Can also be specified via K8S_AUTH_SSL_CA_CERT environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: ssl_ca_cert</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to a certificate used to authenticate with the API. Can also be specified via K8S_AUTH_CERT_FILE environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: cert_file</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to a key file used to authenticate with the API. Can also be specified via K8S_AUTH_KEY_FILE environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: key_file</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>commit</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>Specify the source code commit identifier the build should use; requires a build based on a Git repository.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>context</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>The name of a context found in the config file. Can also be specified via K8S_AUTH_CONTEXT environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>env_vars</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
/ <span style="color: purple">elements=dictionary</span>
</div>
</td>
<td>
</td>
<td>
<div>Specify a list of key-value pair for an environment variable to set for the build container.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>name</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
/ <span style="color: red">required</span>
</div>
</td>
<td>
</td>
<td>
<div>Environment variable name.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>value</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>Environment variable value.</div>
</td>
</tr>
<tr>
<td colspan="2">
<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>
</div>
</td>
<td>
</td>
<td>
<div>Provide a URL for accessing the API. Can also be specified via K8S_AUTH_HOST environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>impersonate_groups</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
/ <span style="color: purple">elements=string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.3.0</div>
</td>
<td>
</td>
<td>
<div>Group(s) to impersonate for the operation.</div>
<div>Can also be specified via K8S_AUTH_IMPERSONATE_GROUPS environment. Example: Group1,Group2</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>impersonate_user</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.3.0</div>
</td>
<td>
</td>
<td>
<div>Username to impersonate for the operation.</div>
<div>Can also be specified via K8S_AUTH_IMPERSONATE_USER environment.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>incremental</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>no</li>
<li>yes</li>
</ul>
</td>
<td>
<div>Overrides the incremental setting in a source-strategy build, ignored if not specified.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>kubeconfig</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">raw</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to an existing Kubernetes config file. If not provided, and no other connection options are provided, the Kubernetes client will attempt to load the default configuration file from <em>~/.kube/config</em>. Can also be specified via K8S_AUTH_KUBECONFIG environment variable.</div>
<div>Multiple Kubernetes config file can be provided using separator &#x27;;&#x27; for Windows platform or &#x27;:&#x27; for others platforms.</div>
<div>The kubernetes configuration can be provided as dictionary. This feature requires a python kubernetes client version &gt;= 17.17.0. Added in version 2.2.0.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>namespace</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
/ <span style="color: red">required</span>
</div>
</td>
<td>
</td>
<td>
<div>Specify the namespace for the build or the build config.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>no_cache</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>no</li>
<li>yes</li>
</ul>
</td>
<td>
<div>Overrides the noCache setting in a docker-strategy build, ignored if not specified.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>no_proxy</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.3.0</div>
</td>
<td>
</td>
<td>
<div>The comma separated list of hosts/domains/IP/CIDR that shouldn&#x27;t go through proxy. Can also be specified via K8S_AUTH_NO_PROXY environment variable.</div>
<div>Please note that this module does not pick up typical proxy settings from the environment (e.g. NO_PROXY).</div>
<div>This feature requires kubernetes&gt;=19.15.0. When kubernetes library is less than 19.15.0, it fails even no_proxy set in correct.</div>
<div>example value is &quot;localhost,.local,.example.com,127.0.0.1,127.0.0.0/8,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16&quot;</div>
</td>
</tr>
<tr>
<td colspan="2">
<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>Provide a password for authenticating with the API. Can also be specified via K8S_AUTH_PASSWORD environment variable.</div>
<div>Please read the description of the <code>username</code> option for a discussion of when this option is applicable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>persist_config</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>no</li>
<li>yes</li>
</ul>
</td>
<td>
<div>Whether or not to save the kube config refresh tokens. Can also be specified via K8S_AUTH_PERSIST_CONFIG environment variable.</div>
<div>When the k8s context is using a user credentials with refresh tokens (like oidc or gke/gcloud auth), the token is refreshed by the k8s python client library but not saved by default. So the old refresh token can expire and the next auth might fail. Setting this flag to true will tell the k8s python client to save the new refresh token to the kube config file.</div>
<div>Default to false.</div>
<div>Please note that the current version of the k8s python client library does not support setting this flag to True yet.</div>
<div>The fix for this k8s python library is here: https://github.com/kubernetes-client/python-base/pull/169</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>The URL of an HTTP proxy to use for the connection. Can also be specified via K8S_AUTH_PROXY environment variable.</div>
<div>Please note that this module does not pick up typical proxy settings from the environment (e.g. HTTP_PROXY).</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy_headers</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.0.0</div>
</td>
<td>
</td>
<td>
<div>The Header used for the HTTP proxy.</div>
<div>Documentation can be found here <a href='https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html?highlight=proxy_headers#urllib3.util.make_headers'>https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html?highlight=proxy_headers#urllib3.util.make_headers</a>.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>basic_auth</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Colon-separated username:password for basic authentication header.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_BASIC_AUTH environment.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy_basic_auth</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Colon-separated username:password for proxy basic authentication header.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_PROXY_BASIC_AUTH environment.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>user_agent</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>String representing the user-agent you want, such as foo/1.0.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_USER_AGENT environment.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<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>started</b>&nbsp;&larr;</div></li>
<li>cancelled</li>
<li>restarted</li>
</ul>
</td>
<td>
<div>Determines if a Build should be started ,cancelled or restarted.</div>
<div>When set to <code>restarted</code> a new build will be created after the current build is cancelled.</div>
</td>
</tr>
<tr>
<td colspan="2">
<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>Provide a username for authenticating with the API. Can also be specified via K8S_AUTH_USERNAME environment variable.</div>
<div>Please note that this only works with clusters configured to use HTTP Basic Auth. If your cluster has a different form of authentication (e.g. OAuth2 in OpenShift), this option will not work as expected and you should look into the <span class='module'>community.okd.k8s_auth</span> module, as that might do what you need.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>validate_certs</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>no</li>
<li>yes</li>
</ul>
</td>
<td>
<div>Whether or not to verify the API server&#x27;s SSL certificates. Can also be specified via K8S_AUTH_VERIFY_SSL environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: verify_ssl</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>wait</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>When <code>state=started</code>, specify whether to wait for a build to complete and exit with a non-zero return code if the build fails.</div>
<div>When <em>state=cancelled</em>, specify whether to wait for a build phase to be Cancelled.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>wait_sleep</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">integer</span>
</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">5</div>
</td>
<td>
<div>Number of seconds to sleep between checks.</div>
<div>Ignored if <code>wait=false</code>.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>wait_timeout</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">integer</span>
</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">120</div>
</td>
<td>
<div>How long in seconds to wait for a build to complete.</div>
<div>Ignored if <code>wait=false</code>.</div>
</td>
</tr>
</table>
<br/>
Notes
-----
.. note::
- To avoid SSL certificate validation errors when ``validate_certs`` is *True*, the full certificate chain for the API server must be provided via ``ca_cert`` or in the kubeconfig file.
Examples
--------
.. code-block:: yaml
# Starts build from build config default/hello-world
- name: Starts build from build config
community.okd.openshift_build:
namespace: default
build_config_name: hello-world
# Starts build from a previous build "default/hello-world-1"
- name: Starts build from a previous build
community.okd.openshift_build:
namespace: default
build_name: hello-world-1
# Cancel the build with the given name
- name: Cancel build from default namespace
community.okd.openshift_build:
namespace: "default"
build_name: ruby-build-1
state: cancelled
# Cancel the named build and create a new one with the same parameters
- name: Cancel build from default namespace and create a new one
community.okd.openshift_build:
namespace: "default"
build_name: ruby-build-1
state: restarted
# Cancel all builds created from 'ruby-build' build configuration that are in 'new' state
- name: Cancel build from default namespace and create a new one
community.okd.openshift_build:
namespace: "default"
build_config_name: ruby-build
build_phases:
- New
state: cancelled
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="2">Key</th>
<th>Returned</th>
<th width="100%">Description</th>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>builds</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">complex</span>
</div>
</td>
<td>success</td>
<td>
<div>The builds that were started/cancelled.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>api_version</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>success</td>
<td>
<div>The versioned schema of this representation of an object.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>kind</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>success</td>
<td>
<div>Represents the REST resource this object represents.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>metadata</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
</td>
<td>success</td>
<td>
<div>Standard object metadata. Includes name, namespace, annotations, labels, etc.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>spec</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
</td>
<td>success</td>
<td>
<div>Specific attributes of the build.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>status</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
</td>
<td>success</td>
<td>
<div>Current status details for the object.</div>
<br/>
</td>
</tr>
</table>
<br/><br/>
Status
------
Authors
~~~~~~~
- Aubin Bikouo (@abikouo)
@@ -0,0 +1,681 @@
.. _community.okd.openshift_import_image_module:
************************************
community.okd.openshift_import_image
************************************
**Import the latest image information from a tag in a container image registry.**
Version added: 2.2.0
.. contents::
:local:
:depth: 1
Synopsis
--------
- Image streams allow you to control which images are rolled out to your builds and applications.
- This module fetches the latest version of an image from a remote repository and updates the image stream tag if it does not match the previous value.
- Running the module multiple times will not create duplicate entries.
- When importing an image, only the image metadata is copied, not the image contents.
- Analogous to ``oc import-image``.
Requirements
------------
The below requirements are needed on the host that executes this module.
- python >= 3.6
- kubernetes >= 12.0.0
- docker-image-py
Parameters
----------
.. raw:: html
<table border=0 cellpadding=0 class="documentation-table">
<tr>
<th colspan="2">Parameter</th>
<th>Choices/<font color="blue">Defaults</font></th>
<th width="100%">Comments</th>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>all</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>If set to <em>true</em>, import all tags from the provided source on creation or if <code>source</code> is specified.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>api_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Token used to authenticate with the API. Can also be specified via K8S_AUTH_API_KEY environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>ca_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to a CA certificate used to authenticate with the API. The full certificate chain must be provided to avoid certificate validation errors. Can also be specified via K8S_AUTH_SSL_CA_CERT environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: ssl_ca_cert</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to a certificate used to authenticate with the API. Can also be specified via K8S_AUTH_CERT_FILE environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: cert_file</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to a key file used to authenticate with the API. Can also be specified via K8S_AUTH_KEY_FILE environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: key_file</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>context</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>The name of a context found in the config file. Can also be specified via K8S_AUTH_CONTEXT environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<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>
</div>
</td>
<td>
</td>
<td>
<div>Provide a URL for accessing the API. Can also be specified via K8S_AUTH_HOST environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>impersonate_groups</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
/ <span style="color: purple">elements=string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.3.0</div>
</td>
<td>
</td>
<td>
<div>Group(s) to impersonate for the operation.</div>
<div>Can also be specified via K8S_AUTH_IMPERSONATE_GROUPS environment. Example: Group1,Group2</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>impersonate_user</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.3.0</div>
</td>
<td>
</td>
<td>
<div>Username to impersonate for the operation.</div>
<div>Can also be specified via K8S_AUTH_IMPERSONATE_USER environment.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>kubeconfig</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">raw</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to an existing Kubernetes config file. If not provided, and no other connection options are provided, the Kubernetes client will attempt to load the default configuration file from <em>~/.kube/config</em>. Can also be specified via K8S_AUTH_KUBECONFIG environment variable.</div>
<div>Multiple Kubernetes config file can be provided using separator &#x27;;&#x27; for Windows platform or &#x27;:&#x27; for others platforms.</div>
<div>The kubernetes configuration can be provided as dictionary. This feature requires a python kubernetes client version &gt;= 17.17.0. Added in version 2.2.0.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>name</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">raw</span>
/ <span style="color: red">required</span>
</div>
</td>
<td>
</td>
<td>
<div>Image stream to import tag into.</div>
<div>This can be provided as a list of images streams or a single value.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>namespace</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
/ <span style="color: red">required</span>
</div>
</td>
<td>
</td>
<td>
<div>Use to specify namespace for image stream to create/update.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>no_proxy</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.3.0</div>
</td>
<td>
</td>
<td>
<div>The comma separated list of hosts/domains/IP/CIDR that shouldn&#x27;t go through proxy. Can also be specified via K8S_AUTH_NO_PROXY environment variable.</div>
<div>Please note that this module does not pick up typical proxy settings from the environment (e.g. NO_PROXY).</div>
<div>This feature requires kubernetes&gt;=19.15.0. When kubernetes library is less than 19.15.0, it fails even no_proxy set in correct.</div>
<div>example value is &quot;localhost,.local,.example.com,127.0.0.1,127.0.0.0/8,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16&quot;</div>
</td>
</tr>
<tr>
<td colspan="2">
<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>Provide a password for authenticating with the API. Can also be specified via K8S_AUTH_PASSWORD environment variable.</div>
<div>Please read the description of the <code>username</code> option for a discussion of when this option is applicable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>persist_config</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>no</li>
<li>yes</li>
</ul>
</td>
<td>
<div>Whether or not to save the kube config refresh tokens. Can also be specified via K8S_AUTH_PERSIST_CONFIG environment variable.</div>
<div>When the k8s context is using a user credentials with refresh tokens (like oidc or gke/gcloud auth), the token is refreshed by the k8s python client library but not saved by default. So the old refresh token can expire and the next auth might fail. Setting this flag to true will tell the k8s python client to save the new refresh token to the kube config file.</div>
<div>Default to false.</div>
<div>Please note that the current version of the k8s python client library does not support setting this flag to True yet.</div>
<div>The fix for this k8s python library is here: https://github.com/kubernetes-client/python-base/pull/169</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>The URL of an HTTP proxy to use for the connection. Can also be specified via K8S_AUTH_PROXY environment variable.</div>
<div>Please note that this module does not pick up typical proxy settings from the environment (e.g. HTTP_PROXY).</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy_headers</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.0.0</div>
</td>
<td>
</td>
<td>
<div>The Header used for the HTTP proxy.</div>
<div>Documentation can be found here <a href='https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html?highlight=proxy_headers#urllib3.util.make_headers'>https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html?highlight=proxy_headers#urllib3.util.make_headers</a>.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>basic_auth</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Colon-separated username:password for basic authentication header.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_BASIC_AUTH environment.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy_basic_auth</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Colon-separated username:password for proxy basic authentication header.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_PROXY_BASIC_AUTH environment.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>user_agent</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>String representing the user-agent you want, such as foo/1.0.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_USER_AGENT environment.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>reference_policy</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>source</b>&nbsp;&larr;</div></li>
<li>local</li>
</ul>
</td>
<td>
<div>Allow to request pullthrough for external image when set to <em>local</em>.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>scheduled</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>Set each imported Docker image to be periodically imported from a remote repository.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>source</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>A Docker image repository to import images from.</div>
<div>Should be provided as &#x27;registry.io/repo/image&#x27;</div>
</td>
</tr>
<tr>
<td colspan="2">
<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>Provide a username for authenticating with the API. Can also be specified via K8S_AUTH_USERNAME environment variable.</div>
<div>Please note that this only works with clusters configured to use HTTP Basic Auth. If your cluster has a different form of authentication (e.g. OAuth2 in OpenShift), this option will not work as expected and you should look into the <span class='module'>community.okd.k8s_auth</span> module, as that might do what you need.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>validate_certs</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>no</li>
<li>yes</li>
</ul>
</td>
<td>
<div>Whether or not to verify the API server&#x27;s SSL certificates. Can also be specified via K8S_AUTH_VERIFY_SSL environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: verify_ssl</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>validate_registry_certs</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>no</li>
<li>yes</li>
</ul>
</td>
<td>
<div>If set to <em>true</em>, allow importing from registries that have invalid HTTPS certificates. or are hosted via HTTP. This parameter will take precedence over the insecure annotation.</div>
</td>
</tr>
</table>
<br/>
Notes
-----
.. note::
- To avoid SSL certificate validation errors when ``validate_certs`` is *True*, the full certificate chain for the API server must be provided via ``ca_cert`` or in the kubeconfig file.
Examples
--------
.. code-block:: yaml
# Import tag latest into a new image stream.
- name: Import tag latest into new image stream
community.okd.openshift_import_image:
namespace: testing
name: mystream
source: registry.io/repo/image:latest
# Update imported data for tag latest in an already existing image stream.
- name: Update imported data for tag latest
community.okd.openshift_import_image:
namespace: testing
name: mystream
# Update imported data for tag 'stable' in an already existing image stream.
- name: Update imported data for tag latest
community.okd.openshift_import_image:
namespace: testing
name: mystream:stable
# Update imported data for all tags in an existing image stream.
- name: Update imported data for all tags
community.okd.openshift_import_image:
namespace: testing
name: mystream
all: true
# Import all tags into a new image stream.
- name: Import all tags into a new image stream.
community.okd.openshift_import_image:
namespace: testing
name: mystream
source: registry.io/repo/image:latest
all: true
# Import all tags into a new image stream for a list of image streams
- name: Import all tags into a new image stream.
community.okd.openshift_import_image:
namespace: testing
name:
- mystream1
- mystream2
- mystream3
source: registry.io/repo/image:latest
all: true
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="2">Key</th>
<th>Returned</th>
<th width="100%">Description</th>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>result</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
/ <span style="color: purple">elements=dictionary</span>
</div>
</td>
<td>success</td>
<td>
<div>List with all ImageStreamImport that have been created.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>api_version</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>success</td>
<td>
<div>The versioned schema of this representation of an object.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>kind</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>success</td>
<td>
<div>Represents the REST resource this object represents.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>metadata</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
</td>
<td>success</td>
<td>
<div>Standard object metadata. Includes name, namespace, annotations, labels, etc.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>spec</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
</td>
<td>success</td>
<td>
<div>Specific attributes of the object. Will vary based on the <em>api_version</em> and <em>kind</em>.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>status</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
</td>
<td>success</td>
<td>
<div>Current status details for the object.</div>
<br/>
</td>
</tr>
</table>
<br/><br/>
Status
------
Authors
~~~~~~~
- Aubin Bikouo (@abikouo)
+369
View File
@@ -0,0 +1,369 @@
.. _community.okd.openshift_inventory:
***********************
community.okd.openshift
***********************
**OpenShift inventory source**
.. contents::
:local:
:depth: 1
DEPRECATED
----------
:Removed in collection release after
:Why: As discussed in https://github.com/ansible-collections/kubernetes.core/issues/31, we decided to
remove the openshift inventory plugin in release 5.0.0.
:Alternative: Use :ref:`kubernetes.core.k8s_info <kubernetes.core.k8s_info_module>` and :ref:`ansible.builtin.add_host <ansible.builtin.add_host_module>` instead.
Synopsis
--------
- Fetch containers, services and routes for one or more clusters
- Groups by cluster name, namespace, namespace_services, namespace_pods, namespace_routes, and labels
- Uses openshift.(yml|yaml) YAML configuration file to set parameter values.
Requirements
------------
The below requirements are needed on the local Ansible controller node that executes this inventory.
- python >= 3.6
- kubernetes >= 12.0.0
- PyYAML >= 3.11
Parameters
----------
.. raw:: html
<table border=0 cellpadding=0 class="documentation-table">
<tr>
<th colspan="2">Parameter</th>
<th>Choices/<font color="blue">Defaults</font></th>
<th>Configuration</th>
<th width="100%">Comments</th>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>connections</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Optional list of cluster connection settings. If no connections are provided, the default <em>~/.kube/config</em> and active context will be used, and objects will be returned for all namespaces the active user is authorized to access.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>api_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Token used to authenticate with the API. Can also be specified via K8S_AUTH_API_KEY environment variable.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>ca_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Path to a CA certificate used to authenticate with the API. Can also be specified via K8S_AUTH_SSL_CA_CERT environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: ssl_ca_cert</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Path to a certificate used to authenticate with the API. Can also be specified via K8S_AUTH_CERT_FILE environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: cert_file</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Path to a key file used to authenticate with the API. Can also be specified via K8S_AUTH_KEY_FILE environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: key_file</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>context</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>The name of a context found in the config file. Can also be specified via K8S_AUTH_CONTEXT environment variable.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>host</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Provide a URL for accessing the API. Can also be specified via K8S_AUTH_HOST environment variable.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>kubeconfig</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Path to an existing Kubernetes config file. If not provided, and no other connection options are provided, the Kubernetes client will attempt to load the default configuration file from <em>~/.kube/config</em>. Can also be specified via K8S_AUTH_KUBECONFIG environment variable.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>name</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Optional name to assign to the cluster. If not provided, a name is constructed from the server and port.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>namespaces</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>List of namespaces. If not specified, will fetch all containers for all namespaces user is authorized to access.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>password</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Provide a password for authenticating with the API. Can also be specified via K8S_AUTH_PASSWORD environment variable.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>username</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Provide a username for authenticating with the API. Can also be specified via K8S_AUTH_USERNAME environment variable.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>validate_certs</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>no</li>
<li>yes</li>
</ul>
</td>
<td>
</td>
<td>
<div>Whether or not to verify the API server&#x27;s SSL certificates. Can also be specified via K8S_AUTH_VERIFY_SSL environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: verify_ssl</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>plugin</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
/ <span style="color: red">required</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>openshift</li>
<li>community.okd.openshift</li>
</ul>
</td>
<td>
</td>
<td>
<div>token that ensures this is a source file for the &#x27;openshift&#x27; plugin.</div>
</td>
</tr>
</table>
<br/>
Examples
--------
.. code-block:: yaml
# File must be named openshift.yaml or openshift.yml
- name: Authenticate with token, and return all pods and services for all namespaces
plugin: community.okd.openshift
connections:
- host: https://192.168.64.4:8443
api_key: xxxxxxxxxxxxxxxx
verify_ssl: false
- name: Use default config (~/.kube/config) file and active context, and return objects for a specific namespace
plugin: community.okd.openshift
connections:
- namespaces:
- testing
- name: Use a custom config file, and a specific context.
plugin: community.okd.openshift
connections:
- kubeconfig: /path/to/config
context: 'awx/192-168-64-4:8443/developer'
Status
------
- This inventory will be removed in version 5.0.0. *[deprecated]*
- For more information see `DEPRECATED`_.
Authors
~~~~~~~
- Chris Houseknecht (@chouseknecht)
.. hint::
Configuration entries for each entry type have a low to high priority order. For example, a variable that is lower in the list will override a variable that is higher up.
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,519 @@
.. _community.okd.openshift_registry_info_module:
*************************************
community.okd.openshift_registry_info
*************************************
**Display information about the integrated registry.**
Version added: 2.2.0
.. contents::
:local:
:depth: 1
Synopsis
--------
- This module exposes information about the integrated registry.
- Use ``check`` to verify your local client can access the registry.
- If the adminstrator has not configured a public hostname for the registry then this command may fail when run outside of the server.
- Analogous to ``oc registry info``.
Requirements
------------
The below requirements are needed on the host that executes this module.
- python >= 3.6
- kubernetes >= 12.0.0
- docker-image-py
Parameters
----------
.. raw:: html
<table border=0 cellpadding=0 class="documentation-table">
<tr>
<th colspan="2">Parameter</th>
<th>Choices/<font color="blue">Defaults</font></th>
<th width="100%">Comments</th>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>api_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Token used to authenticate with the API. Can also be specified via K8S_AUTH_API_KEY environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>ca_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to a CA certificate used to authenticate with the API. The full certificate chain must be provided to avoid certificate validation errors. Can also be specified via K8S_AUTH_SSL_CA_CERT environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: ssl_ca_cert</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>check</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>Attempt to contact the integrated registry using local client.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to a certificate used to authenticate with the API. Can also be specified via K8S_AUTH_CERT_FILE environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: cert_file</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to a key file used to authenticate with the API. Can also be specified via K8S_AUTH_KEY_FILE environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: key_file</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>context</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>The name of a context found in the config file. Can also be specified via K8S_AUTH_CONTEXT environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<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>
</div>
</td>
<td>
</td>
<td>
<div>Provide a URL for accessing the API. Can also be specified via K8S_AUTH_HOST environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>impersonate_groups</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
/ <span style="color: purple">elements=string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.3.0</div>
</td>
<td>
</td>
<td>
<div>Group(s) to impersonate for the operation.</div>
<div>Can also be specified via K8S_AUTH_IMPERSONATE_GROUPS environment. Example: Group1,Group2</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>impersonate_user</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.3.0</div>
</td>
<td>
</td>
<td>
<div>Username to impersonate for the operation.</div>
<div>Can also be specified via K8S_AUTH_IMPERSONATE_USER environment.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>kubeconfig</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">raw</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to an existing Kubernetes config file. If not provided, and no other connection options are provided, the Kubernetes client will attempt to load the default configuration file from <em>~/.kube/config</em>. Can also be specified via K8S_AUTH_KUBECONFIG environment variable.</div>
<div>Multiple Kubernetes config file can be provided using separator &#x27;;&#x27; for Windows platform or &#x27;:&#x27; for others platforms.</div>
<div>The kubernetes configuration can be provided as dictionary. This feature requires a python kubernetes client version &gt;= 17.17.0. Added in version 2.2.0.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>no_proxy</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.3.0</div>
</td>
<td>
</td>
<td>
<div>The comma separated list of hosts/domains/IP/CIDR that shouldn&#x27;t go through proxy. Can also be specified via K8S_AUTH_NO_PROXY environment variable.</div>
<div>Please note that this module does not pick up typical proxy settings from the environment (e.g. NO_PROXY).</div>
<div>This feature requires kubernetes&gt;=19.15.0. When kubernetes library is less than 19.15.0, it fails even no_proxy set in correct.</div>
<div>example value is &quot;localhost,.local,.example.com,127.0.0.1,127.0.0.0/8,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16&quot;</div>
</td>
</tr>
<tr>
<td colspan="2">
<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>Provide a password for authenticating with the API. Can also be specified via K8S_AUTH_PASSWORD environment variable.</div>
<div>Please read the description of the <code>username</code> option for a discussion of when this option is applicable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>persist_config</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>no</li>
<li>yes</li>
</ul>
</td>
<td>
<div>Whether or not to save the kube config refresh tokens. Can also be specified via K8S_AUTH_PERSIST_CONFIG environment variable.</div>
<div>When the k8s context is using a user credentials with refresh tokens (like oidc or gke/gcloud auth), the token is refreshed by the k8s python client library but not saved by default. So the old refresh token can expire and the next auth might fail. Setting this flag to true will tell the k8s python client to save the new refresh token to the kube config file.</div>
<div>Default to false.</div>
<div>Please note that the current version of the k8s python client library does not support setting this flag to True yet.</div>
<div>The fix for this k8s python library is here: https://github.com/kubernetes-client/python-base/pull/169</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>The URL of an HTTP proxy to use for the connection. Can also be specified via K8S_AUTH_PROXY environment variable.</div>
<div>Please note that this module does not pick up typical proxy settings from the environment (e.g. HTTP_PROXY).</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy_headers</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.0.0</div>
</td>
<td>
</td>
<td>
<div>The Header used for the HTTP proxy.</div>
<div>Documentation can be found here <a href='https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html?highlight=proxy_headers#urllib3.util.make_headers'>https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html?highlight=proxy_headers#urllib3.util.make_headers</a>.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>basic_auth</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Colon-separated username:password for basic authentication header.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_BASIC_AUTH environment.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy_basic_auth</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Colon-separated username:password for proxy basic authentication header.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_PROXY_BASIC_AUTH environment.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>user_agent</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>String representing the user-agent you want, such as foo/1.0.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_USER_AGENT environment.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<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>Provide a username for authenticating with the API. Can also be specified via K8S_AUTH_USERNAME environment variable.</div>
<div>Please note that this only works with clusters configured to use HTTP Basic Auth. If your cluster has a different form of authentication (e.g. OAuth2 in OpenShift), this option will not work as expected and you should look into the <span class='module'>community.okd.k8s_auth</span> module, as that might do what you need.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>validate_certs</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>no</li>
<li>yes</li>
</ul>
</td>
<td>
<div>Whether or not to verify the API server&#x27;s SSL certificates. Can also be specified via K8S_AUTH_VERIFY_SSL environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: verify_ssl</div>
</td>
</tr>
</table>
<br/>
Notes
-----
.. note::
- To avoid SSL certificate validation errors when ``validate_certs`` is *True*, the full certificate chain for the API server must be provided via ``ca_cert`` or in the kubeconfig file.
Examples
--------
.. code-block:: yaml
# Get registry information
- name: Read integrated registry information
community.okd.openshift_registry_info:
# Read registry integrated information and attempt to contact using local client.
- name: Attempt to contact integrated registry using local client
community.okd.openshift_registry_info:
check: true
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="2">Key</th>
<th>Returned</th>
<th width="100%">Description</th>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>check</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
</td>
<td>success</td>
<td>
<div>Whether the local client can contact or not the registry.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>msg</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>message describing the ping operation.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>reached</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>success</td>
<td>
<div>Whether the registry has been reached or not.</div>
<br/>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>internal_hostname</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>success</td>
<td>
<div>The internal registry hostname.</div>
<br/>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>public_hostname</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>success</td>
<td>
<div>The public registry hostname.</div>
<br/>
</td>
</tr>
</table>
<br/><br/>
Status
------
Authors
~~~~~~~
- Aubin Bikouo (@abikouo)
File diff suppressed because it is too large Load Diff
+4 -4
View File
@@ -5,16 +5,16 @@ authors:
- willthames (https://github.com/willthames) - willthames (https://github.com/willthames)
- Akasurde (https://github.com/akasurde) - Akasurde (https://github.com/akasurde)
dependencies: dependencies:
community.kubernetes: '>=1.0.0' kubernetes.core: '>=5.0.0'
description: OKD Collection for Ansible. description: OKD Collection for Ansible.
documentation: '' documentation: ''
homepage: '' homepage: ''
issues: https://github.com/ansible-collections/community.okd/issues issues: https://github.com/openshift/community.okd/issues
license_file: LICENSE license_file: LICENSE
name: okd name: okd
namespace: community namespace: community
readme: README.md readme: README.md
repository: https://github.com/ansible-collections/community.okd repository: https://github.com/openshift/community.okd
tags: tags:
- kubernetes - kubernetes
- k8s - k8s
@@ -24,4 +24,4 @@ tags:
- okd - okd
- cluster - cluster
# Also needs to be updated in the Makefile # Also needs to be updated in the Makefile
version: 0.3.0 version: 4.0.1
+30 -1
View File
@@ -1,2 +1,31 @@
--- ---
requires_ansible: '>=2.9' requires_ansible: '>=2.15.0'
action_groups:
okd:
- k8s
- openshift_adm_groups_sync
- openshift_adm_migrate_template_instances
- openshift_adm_prune_auth
- openshift_adm_prune_deployments
- openshift_adm_prune_images
- openshift_auth
- openshift_import_image
- openshift_process
- openshift_registry_info
- openshift_route
plugin_routing:
modules:
k8s_auth:
redirect: community.okd.openshift_auth
inventory:
openshift:
deprecation:
removal_version: 5.0.0
warning_text: >-
The openshift inventory plugin has been deprecated and
will be removed in release 5.0.0.
action:
k8s:
redirect: kubernetes.core.k8s_info
openshift_adm_groups_sync:
redirect: kubernetes.core.k8s_info
+2 -12
View File
@@ -21,16 +21,13 @@
debug: debug:
var: output var: output
- name: Create deployment config - name: Create deployment
community.okd.k8s: community.okd.k8s:
state: present state: present
name: hello-world name: hello-world
namespace: testing namespace: testing
definition: '{{ okd_dc_template }}' definition: '{{ okd_dc_template }}'
wait: yes wait: yes
wait_condition:
type: Available
status: True
vars: vars:
k8s_pod_name: hello-world k8s_pod_name: hello-world
k8s_pod_image: python k8s_pod_image: python
@@ -71,19 +68,12 @@
namespace: '{{ namespace }}' namespace: '{{ namespace }}'
definition: '{{ okd_imagestream_template }}' definition: '{{ okd_imagestream_template }}'
- name: Create DeploymentConfig to reference ImageStream
community.okd.k8s:
name: '{{ k8s_pod_name }}'
namespace: '{{ namespace }}'
definition: '{{ okd_dc_template }}'
vars:
k8s_pod_name: is-idempotent-dc
- name: Create Deployment to reference ImageStream - name: Create Deployment to reference ImageStream
community.okd.k8s: community.okd.k8s:
name: '{{ k8s_pod_name }}' name: '{{ k8s_pod_name }}'
namespace: '{{ namespace }}' namespace: '{{ namespace }}'
definition: '{{ k8s_deployment_template | combine(metadata) }}' definition: '{{ k8s_deployment_template | combine(metadata) }}'
wait: true
vars: vars:
k8s_pod_annotations: k8s_pod_annotations:
"alpha.image.policy.openshift.io/resolve-names": "*" "alpha.image.policy.openshift.io/resolve-names": "*"
+23
View File
@@ -0,0 +1,23 @@
---
kind: Template
apiVersion: template.openshift.io/v1
metadata:
name: pod-template
objects:
- apiVersion: v1
kind: Pod
metadata:
name: "Pod-${{ NAME }}"
spec:
containers:
- args:
- /bin/sh
- -c
- while true; do echo $(date); sleep 15; done
image: python:3.7-alpine
imagePullPolicy: Always
name: python
parameters:
- name: NAME
description: trailing name of the pod
required: true
+40 -2
View File
@@ -1,11 +1,49 @@
--- ---
apiVersion: apiextensions.k8s.io/v1beta1 apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition kind: CustomResourceDefinition
metadata: metadata:
name: certificates.certmanager.k8s.io name: certificates.certmanager.k8s.io
annotations:
"api-approved.kubernetes.io": "https://github.com/kubernetes/kubernetes/pull/78458"
spec: spec:
group: certmanager.k8s.io group: certmanager.k8s.io
version: v1alpha1 versions:
- name: v1alpha1
served: true
storage: true
schema:
openAPIV3Schema:
type: object
properties:
certificate:
type: string
secretName:
type: string
dnsNames:
type: array
items:
type: string
acme:
type: object
properties:
config:
type: array
items:
type: object
properties:
ingressClass:
type: string
domains:
type: array
items:
type: string
issuerRef:
type: object
properties:
name:
type: string
kind:
type: string
scope: Namespaced scope: Namespaced
names: names:
kind: Certificate kind: Certificate
+18 -18
View File
@@ -13,22 +13,22 @@ metadata:
tags: quickstart,examples tags: quickstart,examples
name: simple-example name: simple-example
objects: objects:
- apiVersion: v1 - apiVersion: v1
kind: ConfigMap kind: ConfigMap
metadata: metadata:
annotations: annotations:
description: Big example description: Big example
name: ${NAME} name: ${NAME}
data: data:
content: "${CONTENT}" content: "${CONTENT}"
parameters: parameters:
- description: The name assigned to the ConfigMap - description: The name assigned to the ConfigMap
displayName: Name displayName: Name
name: NAME name: NAME
required: true required: true
value: example value: example
- description: The value for the content key of the configmap - description: The value for the content key of the configmap
displayName: Content displayName: Content
name: CONTENT name: CONTENT
required: true required: true
value: '' value: ''
+4 -8
View File
@@ -1,8 +1,10 @@
--- ---
dependency: dependency:
name: galaxy name: galaxy
options:
requirements-file: requirements.yml
driver: driver:
name: delegated name: default
platforms: platforms:
- name: cluster - name: cluster
groups: groups:
@@ -15,9 +17,6 @@ provisioner:
config_options: config_options:
inventory: inventory:
enable_plugins: community.okd.openshift enable_plugins: community.okd.openshift
lint: |
set -e
ansible-lint
inventory: inventory:
hosts: hosts:
plugin: community.okd.openshift plugin: community.okd.openshift
@@ -32,13 +31,10 @@ provisioner:
ANSIBLE_COLLECTIONS_PATHS: ${OVERRIDE_COLLECTION_PATH:-$MOLECULE_PROJECT_DIRECTORY} ANSIBLE_COLLECTIONS_PATHS: ${OVERRIDE_COLLECTION_PATH:-$MOLECULE_PROJECT_DIRECTORY}
verifier: verifier:
name: ansible name: ansible
lint: |
set -e
ansible-lint
scenario: scenario:
name: default name: default
test_sequence: test_sequence:
- lint - dependency
- syntax - syntax
- prepare - prepare
- converge - converge
+9 -8
View File
@@ -10,8 +10,9 @@
- pip: - pip:
name: name:
- openshift>=0.9.2 - kubernetes>=12.0.0
- coverage - coverage
- python-ldap
virtualenv: "{{ virtualenv }}" virtualenv: "{{ virtualenv }}"
virtualenv_command: "{{ virtualenv_command }}" virtualenv_command: "{{ virtualenv_command }}"
virtualenv_site_packages: no virtualenv_site_packages: no
@@ -36,12 +37,12 @@
name: cluster name: cluster
spec: spec:
identityProviders: identityProviders:
- name: htpasswd_provider - name: htpasswd_provider
mappingMethod: claim mappingMethod: claim
type: HTPasswd type: HTPasswd
htpasswd: htpasswd:
fileData: fileData:
name: htpass-secret name: htpass-secret
- name: Create ClusterRoleBinding for test user - name: Create ClusterRoleBinding for test user
community.okd.k8s: community.okd.k8s:
@@ -53,7 +54,7 @@
roleRef: roleRef:
apiGroup: rbac.authorization.k8s.io apiGroup: rbac.authorization.k8s.io
kind: ClusterRole kind: ClusterRole
name: cluster-reader name: cluster-admin
subjects: subjects:
- apiGroup: rbac.authorization.k8s.io - apiGroup: rbac.authorization.k8s.io
kind: User kind: User
@@ -0,0 +1,4 @@
---
ldap_admin_user: "admin"
ldap_admin_password: "testing123!"
ldap_root: "dc=ansible,dc=redhat"
@@ -0,0 +1,186 @@
# 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: openshift_ldap_entry
short_description: add/remove entry to LDAP Server.
author:
- Aubin Bikouo (@abikouo)
description:
- This module perform basic operations on the LDAP Server (add/remove entries).
- Similar to `community.general.ldap_entry` this has been created to avoid dependency with this collection for the test.
- This module is not supported outside of testing this collection.
options:
attributes:
description:
- If I(state=present), attributes necessary to create an entry. Existing
entries are never modified. To assert specific attribute values on an
existing entry, use M(community.general.ldap_attrs) module instead.
type: dict
objectClass:
description:
- If I(state=present), value or list of values to use when creating
the entry. It can either be a string or an actual list of
strings.
type: list
elements: str
state:
description:
- The target state of the entry.
choices: [present, absent]
default: present
type: str
bind_dn:
description:
- A DN to bind with. If this is omitted, we'll try a SASL bind with the EXTERNAL mechanism as default.
- If this is blank, we'll use an anonymous bind.
type: str
required: true
bind_pw:
description:
- The password to use with I(bind_dn).
type: str
dn:
required: true
description:
- The DN of the entry to add or remove.
type: str
server_uri:
description:
- A URI to the LDAP server.
- The default value lets the underlying LDAP client library look for a UNIX domain socket in its default location.
type: str
default: ldapi:///
requirements:
- python-ldap
'''
EXAMPLES = r'''
'''
RETURN = r'''
# Default return values
'''
import traceback
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.common.text.converters import to_native, to_bytes
LDAP_IMP_ERR = None
try:
import ldap
import ldap.modlist
HAS_LDAP = True
except ImportError:
LDAP_IMP_ERR = traceback.format_exc()
HAS_LDAP = False
def argument_spec():
args = {}
args['attributes'] = dict(default={}, type='dict')
args['objectClass'] = dict(type='list', elements='str')
args['state'] = dict(default='present', choices=['present', 'absent'])
args['bind_dn'] = dict(required=True)
args['bind_pw'] = dict(default='', no_log=True)
args['dn'] = dict(required=True)
args['server_uri'] = dict(default='ldapi:///')
return args
class LdapEntry(AnsibleModule):
def __init__(self):
AnsibleModule.__init__(
self,
argument_spec=argument_spec(),
required_if=[('state', 'present', ['objectClass'])],
)
if not HAS_LDAP:
self.fail_json(msg=missing_required_lib('python-ldap'), exception=LDAP_IMP_ERR)
self.__connection = None
# Add the objectClass into the list of attributes
self.params['attributes']['objectClass'] = (self.params['objectClass'])
# Load attributes
if self.params['state'] == 'present':
self.attrs = {}
for name, value in self.params['attributes'].items():
if isinstance(value, list):
self.attrs[name] = list(map(to_bytes, value))
else:
self.attrs[name] = [to_bytes(value)]
@property
def connection(self):
if not self.__connection:
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
self.__connection = ldap.initialize(self.params['server_uri'])
try:
self.__connection.simple_bind_s(self.params['bind_dn'], self.params['bind_pw'])
except ldap.LDAPError as e:
self.fail_json(msg="Cannot bind to the server due to: %s" % e)
return self.__connection
def add(self):
""" If self.dn does not exist, returns a callable that will add it. """
changed = False
msg = "LDAP Entry '%s' already exist." % self.params["dn"]
if not self._is_entry_present():
modlist = ldap.modlist.addModlist(self.attrs)
self.connection.add_s(self.params['dn'], modlist)
changed = True
msg = "LDAP Entry '%s' successfully created." % self.params["dn"]
self.exit_json(changed=changed, msg=msg)
def delete(self):
""" If self.dn exists, returns a callable that will delete it. """
changed = False
msg = "LDAP Entry '%s' does not exist." % self.params["dn"]
if self._is_entry_present():
self.connection.delete_s(self.params['dn'])
changed = True
msg = "LDAP Entry '%s' successfully deleted." % self.params["dn"]
self.exit_json(changed=changed, msg=msg)
def _is_entry_present(self):
try:
self.connection.search_s(self.params['dn'], ldap.SCOPE_BASE)
except ldap.NO_SUCH_OBJECT:
is_present = False
else:
is_present = True
return is_present
def execute(self):
try:
if self.params['state'] == 'present':
self.add()
else:
self.delete()
except Exception as e:
self.fail_json(msg="Entry action failed.", details=to_native(e), exception=traceback.format_exc())
def main():
module = LdapEntry()
module.execute()
if __name__ == '__main__':
main()
@@ -0,0 +1,110 @@
# 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: openshift_ldap_entry_info
short_description: Validate entry from LDAP server.
author:
- Aubin Bikouo (@abikouo)
description:
- This module connect to a ldap server and search for entry.
- This module is not supported outside of testing this collection.
options:
bind_dn:
description:
- A DN to bind with. If this is omitted, we'll try a SASL bind with the EXTERNAL mechanism as default.
- If this is blank, we'll use an anonymous bind.
type: str
required: true
bind_pw:
description:
- The password to use with I(bind_dn).
type: str
required: True
dn:
description:
- The DN of the entry to test.
type: str
required: True
server_uri:
description:
- A URI to the LDAP server.
- The default value lets the underlying LDAP client library look for a UNIX domain socket in its default location.
type: str
default: ldapi:///
required: True
requirements:
- python-ldap
'''
EXAMPLES = r'''
'''
RETURN = r'''
# Default return values
'''
import traceback
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
LDAP_IMP_ERR = None
try:
import ldap
import ldap.modlist
HAS_LDAP = True
except ImportError:
LDAP_IMP_ERR = traceback.format_exc()
HAS_LDAP = False
def argument_spec():
args = {}
args['bind_dn'] = dict(required=True)
args['bind_pw'] = dict(required=True, no_log=True)
args['dn'] = dict(required=True)
args['server_uri'] = dict(required=True)
return args
def execute():
module = AnsibleModule(
argument_spec=argument_spec(),
supports_check_mode=True
)
if not HAS_LDAP:
module.fail_json(msg=missing_required_lib("python-ldap"), exception=LDAP_IMP_ERR)
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
connection = ldap.initialize(module.params['server_uri'])
connection.set_option(ldap.OPT_REFERRALS, 0)
try:
connection.simple_bind_s(module.params['bind_dn'], module.params['bind_pw'])
except ldap.LDAPError as e:
module.fail_json(msg="Cannot bind to the server due to: %s" % e)
try:
connection.search_s(module.params['dn'], ldap.SCOPE_BASE)
module.exit_json(changed=False, found=True)
except ldap.NO_SUCH_OBJECT:
module.exit_json(changed=False, found=False)
def main():
execute()
if __name__ == '__main__':
main()
@@ -0,0 +1,4 @@
---
collections:
- community.okd
- kubernetes.core
@@ -0,0 +1,235 @@
---
- block:
- name: Get LDAP definition
set_fact:
ldap_entries: "{{ lookup('template', 'ad/definition.j2') | from_yaml }}"
- name: Delete openshift groups if existing
community.okd.k8s:
state: absent
kind: Group
version: "user.openshift.io/v1"
name: "{{ item }}"
with_items:
- admins
- developers
- name: Delete existing LDAP Entries
openshift_ldap_entry:
bind_dn: "{{ ldap_bind_dn }}"
bind_pw: "{{ ldap_bind_pw }}"
server_uri: "{{ ldap_server_uri }}"
dn: "{{ item.dn }}"
state: absent
with_items: "{{ ldap_entries.users + ldap_entries.units | reverse | list }}"
- name: Create LDAP Entries
openshift_ldap_entry:
bind_dn: "{{ ldap_bind_dn }}"
bind_pw: "{{ ldap_bind_pw }}"
server_uri: "{{ ldap_server_uri }}"
dn: "{{ item.dn }}"
attributes: "{{ item.attr }}"
objectClass: "{{ item.class }}"
with_items: "{{ ldap_entries.units + ldap_entries.users }}"
- name: Load test configurations
set_fact:
sync_config: "{{ lookup('template', 'ad/sync-config.j2') | from_yaml }}"
- name: Synchronize Groups
community.okd.openshift_adm_groups_sync:
config: "{{ sync_config }}"
check_mode: yes
register: result
- name: Validate Group going to be created
assert:
that:
- result is changed
- admins_group
- devs_group
- '"jane.smith@ansible.org" in admins_group.users'
- '"jim.adams@ansible.org" in admins_group.users'
- '"jordanbulls@ansible.org" in devs_group.users'
- admins_group.users | length == 2
- devs_group.users | length == 1
vars:
admins_group: "{{ result.groups | selectattr('metadata.name', 'equalto', 'admins') | first }}"
devs_group: "{{ result.groups | selectattr('metadata.name', 'equalto', 'developers') | first }}"
- name: Synchronize Groups (Remove check_mode)
community.okd.openshift_adm_groups_sync:
config: "{{ sync_config }}"
register: result
- name: Validate Group going to be created
assert:
that:
- result is changed
- name: Read admins group
kubernetes.core.k8s_info:
kind: Group
version: "user.openshift.io/v1"
name: admins
register: result
- name: Validate group was created
assert:
that:
- result.resources | length == 1
- '"jane.smith@ansible.org" in result.resources.0.users'
- '"jim.adams@ansible.org" in result.resources.0.users'
- name: Read developers group
kubernetes.core.k8s_info:
kind: Group
version: "user.openshift.io/v1"
name: developers
register: result
- name: Validate group was created
assert:
that:
- result.resources | length == 1
- '"jordanbulls@ansible.org" in result.resources.0.users'
- name: Define user dn to delete
set_fact:
user_to_delete: "cn=Jane,ou=engineers,ou=activeD,{{ ldap_root }}"
- name: Delete 1 admin user
openshift_ldap_entry:
bind_dn: "{{ ldap_bind_dn }}"
bind_pw: "{{ ldap_bind_pw }}"
server_uri: "{{ ldap_server_uri }}"
dn: "{{ user_to_delete }}"
state: absent
- name: Synchronize Openshift groups using allow_groups
community.okd.openshift_adm_groups_sync:
config: "{{ sync_config }}"
allow_groups:
- developers
type: openshift
register: openshift_sync
- name: Validate that only developers group was sync
assert:
that:
- openshift_sync is changed
- openshift_sync.groups | length == 1
- openshift_sync.groups.0.metadata.name == "developers"
- name: Read admins group
kubernetes.core.k8s_info:
kind: Group
version: "user.openshift.io/v1"
name: admins
register: result
- name: Validate admins group content has not changed
assert:
that:
- result.resources | length == 1
- '"jane.smith@ansible.org" in result.resources.0.users'
- '"jim.adams@ansible.org" in result.resources.0.users'
- name: Synchronize Openshift groups using deny_groups
community.okd.openshift_adm_groups_sync:
config: "{{ sync_config }}"
deny_groups:
- developers
type: openshift
register: openshift_sync
- name: Validate that only admins group was sync
assert:
that:
- openshift_sync is changed
- openshift_sync.groups | length == 1
- openshift_sync.groups.0.metadata.name == "admins"
- name: Read admins group
kubernetes.core.k8s_info:
kind: Group
version: "user.openshift.io/v1"
name: admins
register: result
- name: Validate admins group contains only 1 user now
assert:
that:
- result.resources | length == 1
- result.resources.0.users == ["jim.adams@ansible.org"]
- name: Set users to delete (delete all developers users)
set_fact:
user_to_delete: "cn=Jordan,ou=engineers,ou=activeD,{{ ldap_root }}"
- name: Delete 1 admin user
openshift_ldap_entry:
bind_dn: "{{ ldap_bind_dn }}"
bind_pw: "{{ ldap_bind_pw }}"
server_uri: "{{ ldap_server_uri }}"
dn: "{{ user_to_delete }}"
state: absent
- name: Prune groups
community.okd.openshift_adm_groups_sync:
config: "{{ sync_config }}"
state: absent
register: result
- name: Validate result is changed (only developers group be deleted)
assert:
that:
- result is changed
- result.groups | length == 1
- name: Get developers group info
kubernetes.core.k8s_info:
kind: Group
version: "user.openshift.io/v1"
name: developers
register: result
- name: assert group was deleted
assert:
that:
- result.resources | length == 0
- name: Get admins group info
kubernetes.core.k8s_info:
kind: Group
version: "user.openshift.io/v1"
name: admins
register: result
- name: assert group was not deleted
assert:
that:
- result.resources | length == 1
- name: Prune groups once again (idempotency)
community.okd.openshift_adm_groups_sync:
config: "{{ sync_config }}"
state: absent
register: result
- name: Assert nothing was changed
assert:
that:
- result is not changed
always:
- name: Delete openshift groups if existing
community.okd.k8s:
state: absent
kind: Group
version: "user.openshift.io/v1"
name: "{{ item }}"
with_items:
- admins
- developers
@@ -0,0 +1,173 @@
---
- block:
- name: Get LDAP definition
set_fact:
ldap_entries: "{{ lookup('template', 'augmented-ad/definition.j2') | from_yaml }}"
- name: Delete openshift groups if existing
community.okd.k8s:
state: absent
kind: Group
version: "user.openshift.io/v1"
name: "{{ item }}"
with_items:
- banking
- insurance
- name: Delete existing LDAP entries
openshift_ldap_entry:
bind_dn: "{{ ldap_bind_dn }}"
bind_pw: "{{ ldap_bind_pw }}"
server_uri: "{{ ldap_server_uri }}"
dn: "{{ item.dn }}"
state: absent
with_items: "{{ ldap_entries.users + ldap_entries.groups + ldap_entries.units | reverse | list }}"
- name: Create LDAP Entries
openshift_ldap_entry:
bind_dn: "{{ ldap_bind_dn }}"
bind_pw: "{{ ldap_bind_pw }}"
server_uri: "{{ ldap_server_uri }}"
dn: "{{ item.dn }}"
attributes: "{{ item.attr }}"
objectClass: "{{ item.class }}"
with_items: "{{ ldap_entries.units + ldap_entries.groups + ldap_entries.users }}"
- name: Load test configurations
set_fact:
sync_config: "{{ lookup('template', 'augmented-ad/sync-config.j2') | from_yaml }}"
- name: Synchronize Groups
community.okd.openshift_adm_groups_sync:
config: "{{ sync_config }}"
check_mode: yes
register: result
- name: Validate that 'banking' and 'insurance' groups were created
assert:
that:
- result is changed
- banking_group
- insurance_group
- '"james-allan@ansible.org" in banking_group.users'
- '"gordon-kane@ansible.org" in banking_group.users'
- '"alice-courtney@ansible.org" in insurance_group.users'
- banking_group.users | length == 2
- insurance_group.users | length == 1
vars:
banking_group: "{{ result.groups | selectattr('metadata.name', 'equalto', 'banking') | first }}"
insurance_group: "{{ result.groups | selectattr('metadata.name', 'equalto', 'insurance') | first }}"
- name: Synchronize Groups (Remove check_mode)
community.okd.openshift_adm_groups_sync:
config: "{{ sync_config }}"
register: result
- name: Validate Group going to be created
assert:
that:
- result is changed
- name: Define facts for group to create
set_fact:
ldap_groups:
- name: banking
users:
- "james-allan@ansible.org"
- "gordon-kane@ansible.org"
- name: insurance
users:
- "alice-courtney@ansible.org"
- name: Read 'banking' openshift group
kubernetes.core.k8s_info:
kind: Group
version: "user.openshift.io/v1"
name: banking
register: result
- name: Validate group info
assert:
that:
- result.resources | length == 1
- '"james-allan@ansible.org" in result.resources.0.users'
- '"gordon-kane@ansible.org" in result.resources.0.users'
- name: Read 'insurance' openshift group
kubernetes.core.k8s_info:
kind: Group
version: "user.openshift.io/v1"
name: insurance
register: result
- name: Validate group info
assert:
that:
- result.resources | length == 1
- 'result.resources.0.users == ["alice-courtney@ansible.org"]'
- name: Delete employee from 'insurance' group
openshift_ldap_entry:
bind_dn: "{{ ldap_bind_dn }}"
bind_pw: "{{ ldap_bind_pw }}"
server_uri: "{{ ldap_server_uri }}"
dn: "cn=Alice,ou=employee,ou=augmentedAD,{{ ldap_root }}"
state: absent
- name: Prune groups
community.okd.openshift_adm_groups_sync:
config: "{{ sync_config }}"
state: absent
register: result
- name: Validate result is changed (only insurance group be deleted)
assert:
that:
- result is changed
- result.groups | length == 1
- name: Get 'insurance' openshift group info
kubernetes.core.k8s_info:
kind: Group
version: "user.openshift.io/v1"
name: insurance
register: result
- name: assert group was deleted
assert:
that:
- result.resources | length == 0
- name: Get 'banking' openshift group info
kubernetes.core.k8s_info:
kind: Group
version: "user.openshift.io/v1"
name: banking
register: result
- name: assert group was not deleted
assert:
that:
- result.resources | length == 1
- name: Prune groups once again (idempotency)
community.okd.openshift_adm_groups_sync:
config: "{{ sync_config }}"
state: absent
register: result
- name: Assert no change was made
assert:
that:
- result is not changed
always:
- name: Delete openshift groups if existing
community.okd.k8s:
state: absent
kind: Group
version: "user.openshift.io/v1"
name: "{{ item }}"
with_items:
- banking
- insurance
@@ -0,0 +1,63 @@
---
- name: Get cluster information
kubernetes.core.k8s_cluster_info:
register: info
- name: Create LDAP Pod
community.okd.k8s:
namespace: "default"
wait: yes
definition:
kind: Pod
apiVersion: v1
metadata:
name: ldap-pod
labels:
app: ldap
spec:
containers:
- name: ldap
image: bitnami/openldap
env:
- name: LDAP_ADMIN_USERNAME
value: "{{ ldap_admin_user }}"
- name: LDAP_ADMIN_PASSWORD
value: "{{ ldap_admin_password }}"
- name: LDAP_USERS
value: "ansible"
- name: LDAP_PASSWORDS
value: "ansible123"
- name: LDAP_ROOT
value: "{{ ldap_root }}"
ports:
- containerPort: 1389
name: ldap-server
register: pod_info
- name: Set LDAP Common facts
set_fact:
# we can use the Pod IP directly because the integration are running inside a Pod in the
# same openshift cluster
ldap_server_uri: "ldap://{{ pod_info.result.status.podIP }}:1389"
ldap_bind_dn: "cn={{ ldap_admin_user }},{{ ldap_root }}"
ldap_bind_pw: "{{ ldap_admin_password }}"
- name: Display LDAP Server URI
debug:
var: ldap_server_uri
- name: Test existing user from LDAP server
openshift_ldap_entry_info:
bind_dn: "{{ ldap_bind_dn }}"
bind_pw: "{{ ldap_bind_pw }}"
dn: "ou=users,{{ ldap_root }}"
server_uri: "{{ ldap_server_uri }}"
register: test_ldap
retries: 10
delay: 5
until: test_ldap is not failed
- include_tasks: "tasks/python-ldap-not-installed.yml"
- include_tasks: "tasks/rfc2307.yml"
- include_tasks: "tasks/activeDirectory.yml"
- include_tasks: "tasks/augmentedActiveDirectory.yml"
@@ -0,0 +1,43 @@
---
- block:
- name: Create temp directory
tempfile:
state: directory
register: test_dir
- set_fact:
test_dir: "{{ test_dir.path }}"
- set_fact:
venv: "{{ test_dir }}/virtualenv"
- pip:
name:
- kubernetes
virtualenv: "{{ venv }}"
virtualenv_command: "{{ virtualenv_command }}"
virtualenv_site_packages: false
- name: Load test configurations
set_fact:
configs: "{{ lookup('template', 'rfc2307/sync-config.j2') | from_yaml }}"
- name: Synchronize Groups without python-ldap
community.okd.openshift_adm_groups_sync:
config: "{{ configs.simple }}"
register: result
ignore_errors: true
vars:
ansible_python_interpreter: "{{ venv }}/bin/python"
- name: Check that module failed gracefully
assert:
that:
- '"Failed to import the required Python library (python-ldap)" in result.msg'
always:
- name: Remove temp directory
file:
path: "{{ test_dir }}"
state: absent
ignore_errors: true
@@ -0,0 +1,469 @@
---
- block:
- name: Get LDAP definition
set_fact:
ldap_resources: "{{ lookup('template', 'rfc2307/definition.j2') | from_yaml }}"
- name: Delete openshift groups if existing
community.okd.k8s:
state: absent
kind: Group
version: "user.openshift.io/v1"
name: "{{ item }}"
with_items:
- admins
- engineers
- developers
- name: Delete existing LDAP entries
openshift_ldap_entry:
bind_dn: "{{ ldap_bind_dn }}"
bind_pw: "{{ ldap_bind_pw }}"
server_uri: "{{ ldap_server_uri }}"
dn: "{{ item.dn }}"
state: absent
with_items: "{{ ldap_resources.users + ldap_resources.groups + ldap_resources.units | reverse | list }}"
- name: Create LDAP units
openshift_ldap_entry:
bind_dn: "{{ ldap_bind_dn }}"
bind_pw: "{{ ldap_bind_pw }}"
server_uri: "{{ ldap_server_uri }}"
dn: "{{ item.dn }}"
attributes: "{{ item.attr }}"
objectClass: "{{ item.class }}"
with_items: "{{ ldap_resources.units }}"
- name: Create LDAP Groups
openshift_ldap_entry:
bind_dn: "{{ ldap_bind_dn }}"
bind_pw: "{{ ldap_bind_pw }}"
server_uri: "{{ ldap_server_uri }}"
dn: "{{ item.dn }}"
attributes: "{{ item.attr }}"
objectClass: "{{ item.class }}"
with_items: "{{ ldap_resources.groups }}"
- name: Create LDAP users
openshift_ldap_entry:
bind_dn: "{{ ldap_bind_dn }}"
bind_pw: "{{ ldap_bind_pw }}"
server_uri: "{{ ldap_server_uri }}"
dn: "{{ item.dn }}"
attributes: "{{ item.attr }}"
objectClass: "{{ item.class }}"
with_items: "{{ ldap_resources.users }}"
- name: Load test configurations
set_fact:
configs: "{{ lookup('template', 'rfc2307/sync-config.j2') | from_yaml }}"
- name: Synchronize Groups
community.okd.openshift_adm_groups_sync:
config: "{{ configs.simple }}"
check_mode: yes
register: result
- name: Validate Group going to be created
assert:
that:
- result is changed
- admins_group
- devs_group
- '"jane.smith@ansible.org" in admins_group.users'
- '"jim.adams@ansible.org" in devs_group.users'
- '"jordanbulls@ansible.org" in devs_group.users'
- admins_group.users | length == 1
- devs_group.users | length == 2
vars:
admins_group: "{{ result.groups | selectattr('metadata.name', 'equalto', 'admins') | first }}"
devs_group: "{{ result.groups | selectattr('metadata.name', 'equalto', 'developers') | first }}"
- name: Synchronize Groups - User defined mapping
community.okd.openshift_adm_groups_sync:
config: "{{ configs.user_defined }}"
check_mode: yes
register: result
- name: Validate Group going to be created
assert:
that:
- result is changed
- admins_group
- devs_group
- '"jane.smith@ansible.org" in admins_group.users'
- '"jim.adams@ansible.org" in devs_group.users'
- '"jordanbulls@ansible.org" in devs_group.users'
- admins_group.users | length == 1
- devs_group.users | length == 2
vars:
admins_group: "{{ result.groups | selectattr('metadata.name', 'equalto', 'ansible-admins') | first }}"
devs_group: "{{ result.groups | selectattr('metadata.name', 'equalto', 'ansible-devs') | first }}"
- name: Synchronize Groups - Using dn for every query
community.okd.openshift_adm_groups_sync:
config: "{{ configs.dn_everywhere }}"
check_mode: yes
register: result
- name: Validate Group going to be created
assert:
that:
- result is changed
- admins_group
- devs_group
- '"cn=Jane,ou=people,ou=rfc2307,"+ldap_root in admins_group.users'
- '"cn=Jim,ou=people,ou=rfc2307,"+ldap_root in devs_group.users'
- '"cn=Jordan,ou=people,ou=rfc2307,"+ldap_root in devs_group.users'
- admins_group.users | length == 1
- devs_group.users | length == 2
vars:
admins_group: "{{ result.groups | selectattr('metadata.name', 'equalto', 'cn=admins,ou=groups,ou=rfc2307,' + ldap_root ) | first }}"
devs_group: "{{ result.groups | selectattr('metadata.name', 'equalto', 'cn=developers,ou=groups,ou=rfc2307,' + ldap_root ) | first }}"
- name: Synchronize Groups - Partially user defined mapping
community.okd.openshift_adm_groups_sync:
config: "{{ configs.partially_user_defined }}"
check_mode: yes
register: result
- name: Validate Group going to be created
assert:
that:
- result is changed
- admins_group
- devs_group
- '"jane.smith@ansible.org" in admins_group.users'
- '"jim.adams@ansible.org" in devs_group.users'
- '"jordanbulls@ansible.org" in devs_group.users'
- admins_group.users | length == 1
- devs_group.users | length == 2
vars:
admins_group: "{{ result.groups | selectattr('metadata.name', 'equalto', 'ansible-admins') | first }}"
devs_group: "{{ result.groups | selectattr('metadata.name', 'equalto', 'developers') | first }}"
- name: Delete Group 'engineers' if created before
community.okd.k8s:
state: absent
kind: Group
version: "user.openshift.io/v1"
name: 'engineers'
wait: yes
ignore_errors: yes
- name: Synchronize Groups - Partially user defined mapping
community.okd.openshift_adm_groups_sync:
config: "{{ configs.out_scope }}"
check_mode: yes
register: result
ignore_errors: yes
- name: Assert group sync failed due to non-existent member
assert:
that:
- result is failed
- result.msg.startswith("Entry not found for base='cn=Matthew,ou=people,ou=outrfc2307,"+ldap_root+"'")
- name: Define sync configuration with tolerateMemberNotFoundErrors
set_fact:
config_out_of_scope_tolerate_not_found: "{{ configs.out_scope | combine({'rfc2307': merge_rfc2307 })}}"
vars:
merge_rfc2307: "{{ configs.out_scope.rfc2307 | combine({'tolerateMemberNotFoundErrors': 'true'}) }}"
- name: Synchronize Groups - Partially user defined mapping (tolerateMemberNotFoundErrors=true)
community.okd.openshift_adm_groups_sync:
config: "{{ config_out_of_scope_tolerate_not_found }}"
check_mode: yes
register: result
- name: Assert group sync did not fail (tolerateMemberNotFoundErrors=true)
assert:
that:
- result is changed
- result.groups | length == 1
- result.groups.0.metadata.name == 'engineers'
- result.groups.0.users == ['Abraham']
- name: Create Group 'engineers'
community.okd.k8s:
state: present
wait: yes
definition:
kind: Group
apiVersion: "user.openshift.io/v1"
metadata:
name: engineers
users: []
- name: Try to sync LDAP group with Openshift existing group not created using sync should failed
community.okd.openshift_adm_groups_sync:
config: "{{ config_out_of_scope_tolerate_not_found }}"
check_mode: yes
register: result
ignore_errors: yes
- name: Validate group sync failed
assert:
that:
- result is failed
- '"openshift.io/ldap.host label did not match sync host" in result.msg'
- name: Define allow_groups and deny_groups groups
set_fact:
allow_groups:
- "cn=developers,ou=groups,ou=rfc2307,{{ ldap_root }}"
deny_groups:
- "cn=admins,ou=groups,ou=rfc2307,{{ ldap_root }}"
- name: Synchronize Groups using allow_groups
community.okd.openshift_adm_groups_sync:
config: "{{ configs.simple }}"
allow_groups: "{{ allow_groups }}"
register: result
check_mode: yes
- name: Validate Group going to be created
assert:
that:
- result is changed
- result.groups | length == 1
- result.groups.0.metadata.name == "developers"
- name: Synchronize Groups using deny_groups
community.okd.openshift_adm_groups_sync:
config: "{{ configs.simple }}"
deny_groups: "{{ deny_groups }}"
register: result
check_mode: yes
- name: Validate Group going to be created
assert:
that:
- result is changed
- result.groups | length == 1
- result.groups.0.metadata.name == "developers"
- name: Synchronize groups, remove check_mode
community.okd.openshift_adm_groups_sync:
config: "{{ configs.simple }}"
register: result
- name: Validate result is changed
assert:
that:
- result is changed
- name: Read Groups
kubernetes.core.k8s_info:
kind: Group
version: "user.openshift.io/v1"
name: admins
register: result
- name: Validate group was created
assert:
that:
- result.resources | length == 1
- '"jane.smith@ansible.org" in result.resources.0.users'
- name: Read Groups
kubernetes.core.k8s_info:
kind: Group
version: "user.openshift.io/v1"
name: developers
register: result
- name: Validate group was created
assert:
that:
- result.resources | length == 1
- '"jim.adams@ansible.org" in result.resources.0.users'
- '"jordanbulls@ansible.org" in result.resources.0.users'
- name: Set users to delete (no admins users anymore and only 1 developer kept)
set_fact:
users_to_delete:
- "cn=Jane,ou=people,ou=rfc2307,{{ ldap_root }}"
- "cn=Jim,ou=people,ou=rfc2307,{{ ldap_root }}"
- name: Delete users from LDAP servers
openshift_ldap_entry:
bind_dn: "{{ ldap_bind_dn }}"
bind_pw: "{{ ldap_bind_pw }}"
server_uri: "{{ ldap_server_uri }}"
dn: "{{ item }}"
state: absent
with_items: "{{ users_to_delete }}"
- name: Define sync configuration with tolerateMemberNotFoundErrors
set_fact:
config_simple_tolerate_not_found: "{{ configs.simple | combine({'rfc2307': merge_rfc2307 })}}"
vars:
merge_rfc2307: "{{ configs.simple.rfc2307 | combine({'tolerateMemberNotFoundErrors': 'true'}) }}"
- name: Synchronize groups once again after users deletion
community.okd.openshift_adm_groups_sync:
config: "{{ config_simple_tolerate_not_found }}"
register: result
- name: Validate result is changed
assert:
that:
- result is changed
- name: Read Groups
kubernetes.core.k8s_info:
kind: Group
version: "user.openshift.io/v1"
name: admins
register: result
- name: Validate admins group does not contains users anymore
assert:
that:
- result.resources | length == 1
- result.resources.0.users == []
- name: Read Groups
kubernetes.core.k8s_info:
kind: Group
version: "user.openshift.io/v1"
name: developers
register: result
- name: Validate group was created
assert:
that:
- result.resources | length == 1
- '"jordanbulls@ansible.org" in result.resources.0.users'
- name: Set group to delete
set_fact:
groups_to_delete:
- "cn=developers,ou=groups,ou=rfc2307,{{ ldap_root }}"
- name: Delete Group from LDAP servers
openshift_ldap_entry:
bind_dn: "{{ ldap_bind_dn }}"
bind_pw: "{{ ldap_bind_pw }}"
server_uri: "{{ ldap_server_uri }}"
dn: "{{ item }}"
state: absent
with_items: "{{ groups_to_delete }}"
- name: Prune groups
community.okd.openshift_adm_groups_sync:
config: "{{ config_simple_tolerate_not_found }}"
state: absent
register: result
check_mode: yes
- name: Validate that only developers group is candidate for Prune
assert:
that:
- result is changed
- result.groups | length == 1
- result.groups.0.metadata.name == "developers"
- name: Read Group (validate that check_mode did not performed update in the cluster)
kubernetes.core.k8s_info:
kind: Group
version: "user.openshift.io/v1"
name: developers
register: result
- name: Assert group was found
assert:
that:
- result.resources | length == 1
- name: Prune using allow_groups
community.okd.openshift_adm_groups_sync:
config: "{{ config_simple_tolerate_not_found }}"
allow_groups:
- developers
state: absent
register: result
check_mode: yes
- name: assert developers group was candidate for prune
assert:
that:
- result is changed
- result.groups | length == 1
- result.groups.0.metadata.name == "developers"
- name: Prune using deny_groups
community.okd.openshift_adm_groups_sync:
config: "{{ config_simple_tolerate_not_found }}"
deny_groups:
- developers
state: absent
register: result
check_mode: yes
- name: assert nothing found candidate for prune
assert:
that:
- result is not changed
- result.groups | length == 0
- name: Prune groups
community.okd.openshift_adm_groups_sync:
config: "{{ config_simple_tolerate_not_found }}"
state: absent
register: result
- name: Validate result is changed
assert:
that:
- result is changed
- result.groups | length == 1
- name: Get developers group info
kubernetes.core.k8s_info:
kind: Group
version: "user.openshift.io/v1"
name: developers
register: result
- name: assert group was deleted
assert:
that:
- result.resources | length == 0
- name: Get admins group info
kubernetes.core.k8s_info:
kind: Group
version: "user.openshift.io/v1"
name: admins
register: result
- name: assert group was not deleted
assert:
that:
- result.resources | length == 1
- name: Prune groups once again (idempotency)
community.okd.openshift_adm_groups_sync:
config: "{{ config_simple_tolerate_not_found }}"
state: absent
register: result
- name: Assert nothing changed
assert:
that:
- result is not changed
- result.groups | length == 0
always:
- name: Delete openshift groups if existing
community.okd.k8s:
state: absent
kind: Group
version: "user.openshift.io/v1"
name: "{{ item }}"
with_items:
- admins
- engineers
- developers
@@ -0,0 +1,39 @@
units:
- dn: "ou=activeD,{{ ldap_root }}"
class:
- organizationalUnit
attr:
ou: activeD
- dn: "ou=engineers,ou=activeD,{{ ldap_root }}"
class:
- organizationalUnit
attr:
ou: engineers
users:
- dn: cn=Jane,ou=engineers,ou=activeD,{{ ldap_root }}
class:
- inetOrgPerson
attr:
cn: Jane
sn: Smith
displayName: Jane Smith
mail: jane.smith@ansible.org
employeeType: admins
- dn: cn=Jim,ou=engineers,ou=activeD,{{ ldap_root }}
class:
- inetOrgPerson
attr:
cn: Jim
sn: Adams
displayName: Jim Adams
mail: jim.adams@ansible.org
employeeType: admins
- dn: cn=Jordan,ou=engineers,ou=activeD,{{ ldap_root }}
class:
- inetOrgPerson
attr:
cn: Jordan
sn: Bulls
displayName: Jordan Bulls
mail: jordanbulls@ansible.org
employeeType: developers
@@ -0,0 +1,12 @@
kind: LDAPSyncConfig
apiVersion: v1
url: "{{ ldap_server_uri }}"
insecure: true
activeDirectory:
usersQuery:
baseDN: "ou=engineers,ou=activeD,{{ ldap_root }}"
scope: sub
derefAliases: never
filter: (objectclass=inetOrgPerson)
userNameAttributes: [ mail ]
groupMembershipAttributes: [ employeeType ]
@@ -0,0 +1,59 @@
units:
- dn: "ou=augmentedAD,{{ ldap_root }}"
class:
- organizationalUnit
attr:
ou: augmentedAD
- dn: "ou=employee,ou=augmentedAD,{{ ldap_root }}"
class:
- organizationalUnit
attr:
ou: employee
- dn: "ou=category,ou=augmentedAD,{{ ldap_root }}"
class:
- organizationalUnit
attr:
ou: category
groups:
- dn: "cn=banking,ou=category,ou=augmentedAD,{{ ldap_root }}"
class:
- groupOfNames
attr:
cn: banking
description: Banking employees
member:
- cn=James,ou=employee,ou=augmentedAD,{{ ldap_root }}
- cn=Gordon,ou=employee,ou=augmentedAD,{{ ldap_root }}
- dn: "cn=insurance,ou=category,ou=augmentedAD,{{ ldap_root }}"
class:
- groupOfNames
attr:
cn: insurance
description: Insurance employees
member:
- cn=Alice,ou=employee,ou=augmentedAD,{{ ldap_root }}
users:
- dn: cn=James,ou=employee,ou=augmentedAD,{{ ldap_root }}
class:
- inetOrgPerson
attr:
cn: James
sn: Allan
mail: james-allan@ansible.org
businessCategory: cn=banking,ou=category,ou=augmentedAD,{{ ldap_root }}
- dn: cn=Gordon,ou=employee,ou=augmentedAD,{{ ldap_root }}
class:
- inetOrgPerson
attr:
cn: Gordon
sn: Kane
mail: gordon-kane@ansible.org
businessCategory: cn=banking,ou=category,ou=augmentedAD,{{ ldap_root }}
- dn: cn=Alice,ou=employee,ou=augmentedAD,{{ ldap_root }}
class:
- inetOrgPerson
attr:
cn: Alice
sn: Courtney
mail: alice-courtney@ansible.org
businessCategory: cn=insurance,ou=category,ou=augmentedAD,{{ ldap_root }}
@@ -0,0 +1,20 @@
kind: LDAPSyncConfig
apiVersion: v1
url: "{{ ldap_server_uri }}"
insecure: true
augmentedActiveDirectory:
groupsQuery:
baseDN: "ou=category,ou=augmentedAD,{{ ldap_root }}"
scope: sub
derefAliases: never
pageSize: 0
groupUIDAttribute: dn
groupNameAttributes: [ cn ]
usersQuery:
baseDN: "ou=employee,ou=augmentedAD,{{ ldap_root }}"
scope: sub
derefAliases: never
filter: (objectclass=inetOrgPerson)
pageSize: 0
userNameAttributes: [ mail ]
groupMembershipAttributes: [ businessCategory ]
@@ -0,0 +1,102 @@
units:
- dn: "ou=rfc2307,{{ ldap_root }}"
class:
- organizationalUnit
attr:
ou: rfc2307
- dn: "ou=groups,ou=rfc2307,{{ ldap_root }}"
class:
- organizationalUnit
attr:
ou: groups
- dn: "ou=people,ou=rfc2307,{{ ldap_root }}"
class:
- organizationalUnit
attr:
ou: people
- dn: "ou=outrfc2307,{{ ldap_root }}"
class:
- organizationalUnit
attr:
ou: outrfc2307
- dn: "ou=groups,ou=outrfc2307,{{ ldap_root }}"
class:
- organizationalUnit
attr:
ou: groups
- dn: "ou=people,ou=outrfc2307,{{ ldap_root }}"
class:
- organizationalUnit
attr:
ou: people
groups:
- dn: "cn=admins,ou=groups,ou=rfc2307,{{ ldap_root }}"
class:
- groupOfNames
attr:
cn: admins
description: System Administrators
member:
- cn=Jane,ou=people,ou=rfc2307,{{ ldap_root }}
- dn: "cn=developers,ou=groups,ou=rfc2307,{{ ldap_root }}"
class:
- groupOfNames
attr:
cn: developers
description: Developers
member:
- cn=Jim,ou=people,ou=rfc2307,{{ ldap_root }}
- cn=Jordan,ou=people,ou=rfc2307,{{ ldap_root }}
- dn: "cn=engineers,ou=groups,ou=outrfc2307,{{ ldap_root }}"
class:
- groupOfNames
attr:
cn: engineers
description: Engineers
member:
- cn=Jim,ou=people,ou=rfc2307,{{ ldap_root }}
- cn=Jordan,ou=people,ou=rfc2307,{{ ldap_root }}
- cn=Julia,ou=people,ou=outrfc2307,{{ ldap_root }}
- cn=Matthew,ou=people,ou=outrfc2307,{{ ldap_root }}
users:
- dn: cn=Jane,ou=people,ou=rfc2307,{{ ldap_root }}
class:
- person
- organizationalPerson
- inetOrgPerson
attr:
cn: Jane
sn: Smith
displayName: Jane Smith
mail: jane.smith@ansible.org
admin: yes
- dn: cn=Jim,ou=people,ou=rfc2307,{{ ldap_root }}
class:
- person
- organizationalPerson
- inetOrgPerson
attr:
cn: Jim
sn: Adams
displayName: Jim Adams
mail: jim.adams@ansible.org
- dn: cn=Jordan,ou=people,ou=rfc2307,{{ ldap_root }}
class:
- person
- organizationalPerson
- inetOrgPerson
attr:
cn: Jordan
sn: Bulls
displayName: Jordan Bulls
mail: jordanbulls@ansible.org
- dn: cn=Julia,ou=people,ou=outrfc2307,{{ ldap_root }}
class:
- person
- organizationalPerson
- inetOrgPerson
attr:
cn: Julia
sn: Abraham
displayName: Julia Abraham
mail: juliaabraham@ansible.org
@@ -0,0 +1,105 @@
simple:
kind: LDAPSyncConfig
apiVersion: v1
url: "{{ ldap_server_uri }}"
insecure: true
rfc2307:
groupsQuery:
baseDN: "ou=groups,ou=rfc2307,{{ ldap_root }}"
scope: sub
derefAliases: never
filter: (objectclass=groupOfNames)
groupUIDAttribute: dn
groupNameAttributes: [ cn ]
groupMembershipAttributes: [ member ]
usersQuery:
baseDN: "ou=people,ou=rfc2307,{{ ldap_root }}"
scope: sub
derefAliases: never
userUIDAttribute: dn
userNameAttributes: [ mail ]
user_defined:
kind: LDAPSyncConfig
apiVersion: v1
url: "{{ ldap_server_uri }}"
insecure: true
groupUIDNameMapping:
"cn=admins,ou=groups,ou=rfc2307,{{ ldap_root }}": ansible-admins
"cn=developers,ou=groups,ou=rfc2307,{{ ldap_root }}": ansible-devs
rfc2307:
groupsQuery:
baseDN: "ou=groups,ou=rfc2307,{{ ldap_root }}"
scope: sub
derefAliases: never
filter: (objectclass=groupOfNames)
groupUIDAttribute: dn
groupNameAttributes: [ cn ]
groupMembershipAttributes: [ member ]
usersQuery:
baseDN: "ou=people,ou=rfc2307,{{ ldap_root }}"
scope: sub
derefAliases: never
userUIDAttribute: dn
userNameAttributes: [ mail ]
partially_user_defined:
kind: LDAPSyncConfig
apiVersion: v1
url: "{{ ldap_server_uri }}"
insecure: true
groupUIDNameMapping:
"cn=admins,ou=groups,ou=rfc2307,{{ ldap_root }}": ansible-admins
rfc2307:
groupsQuery:
baseDN: "ou=groups,ou=rfc2307,{{ ldap_root }}"
scope: sub
derefAliases: never
filter: (objectclass=groupOfNames)
groupUIDAttribute: dn
groupNameAttributes: [ cn ]
groupMembershipAttributes: [ member ]
usersQuery:
baseDN: "ou=people,ou=rfc2307,{{ ldap_root }}"
scope: sub
derefAliases: never
userUIDAttribute: dn
userNameAttributes: [ mail ]
dn_everywhere:
kind: LDAPSyncConfig
apiVersion: v1
url: "{{ ldap_server_uri }}"
insecure: true
rfc2307:
groupsQuery:
baseDN: "ou=groups,ou=rfc2307,{{ ldap_root }}"
scope: sub
derefAliases: never
filter: (objectclass=groupOfNames)
groupUIDAttribute: dn
groupNameAttributes: [ dn ]
groupMembershipAttributes: [ member ]
usersQuery:
baseDN: "ou=people,ou=rfc2307,{{ ldap_root }}"
scope: sub
derefAliases: never
userUIDAttribute: dn
userNameAttributes: [ dn ]
out_scope:
kind: LDAPSyncConfig
apiVersion: v1
url: "{{ ldap_server_uri }}"
insecure: true
rfc2307:
groupsQuery:
baseDN: "ou=groups,ou=outrfc2307,{{ ldap_root }}"
scope: sub
derefAliases: never
filter: (objectclass=groupOfNames)
groupUIDAttribute: dn
groupNameAttributes: [ cn ]
groupMembershipAttributes: [ member ]
usersQuery:
baseDN: "ou=people,ou=outrfc2307,{{ ldap_root }}"
scope: sub
derefAliases: never
userUIDAttribute: dn
userNameAttributes: [ sn ]
@@ -0,0 +1,319 @@
---
- block:
- set_fact:
test_sa: "clusterrole-sa"
test_ns: "clusterrole-ns"
- name: Ensure namespace
kubernetes.core.k8s:
kind: Namespace
name: "{{ test_ns }}"
- name: Get cluster information
kubernetes.core.k8s_cluster_info:
register: cluster_info
no_log: true
- set_fact:
cluster_host: "{{ cluster_info['connection']['host'] }}"
- name: Create Service account
kubernetes.core.k8s:
definition:
apiVersion: v1
kind: ServiceAccount
metadata:
name: "{{ test_sa }}"
namespace: "{{ test_ns }}"
- name: Read Service Account
kubernetes.core.k8s_info:
kind: ServiceAccount
namespace: "{{ test_ns }}"
name: "{{ test_sa }}"
register: result
- set_fact:
secret_token: "{{ result.resources[0]['secrets'][0]['name'] }}"
- name: Get secret details
kubernetes.core.k8s_info:
kind: Secret
namespace: '{{ test_ns }}'
name: '{{ secret_token }}'
register: _secret
retries: 10
delay: 10
until:
- ("'openshift.io/token-secret.value' in _secret.resources[0]['metadata']['annotations']") or ("'token' in _secret.resources[0]['data']")
- set_fact:
api_token: "{{ _secret.resources[0]['metadata']['annotations']['openshift.io/token-secret.value'] }}"
when: "'openshift.io/token-secret.value' in _secret.resources[0]['metadata']['annotations']"
- set_fact:
api_token: "{{ _secret.resources[0]['data']['token'] | b64decode }}"
when: "'token' in _secret.resources[0]['data']"
- name: list Node should failed (forbidden user)
kubernetes.core.k8s_info:
api_key: "{{ api_token }}"
host: "{{ cluster_host }}"
validate_certs: no
kind: Node
register: error
ignore_errors: true
- assert:
that:
- '"nodes is forbidden: User" in error.msg'
- name: list Pod for all namespace should failed
kubernetes.core.k8s_info:
api_key: "{{ api_token }}"
host: "{{ cluster_host }}"
validate_certs: no
kind: Pod
register: error
ignore_errors: true
- assert:
that:
- '"pods is forbidden: User" in error.msg'
- name: list Pod for test namespace should failed
kubernetes.core.k8s_info:
api_key: "{{ api_token }}"
host: "{{ cluster_host }}"
validate_certs: no
kind: Pod
namespace: "{{ test_ns }}"
register: error
ignore_errors: true
- assert:
that:
- '"pods is forbidden: User" in error.msg'
- set_fact:
test_labels:
phase: dev
cluster_roles:
- name: pod-manager
resources:
- pods
verbs:
- list
api_version_binding: "authorization.openshift.io/v1"
- name: node-manager
resources:
- nodes
verbs:
- list
api_version_binding: "rbac.authorization.k8s.io/v1"
- name: Create cluster roles
kubernetes.core.k8s:
definition:
kind: ClusterRole
apiVersion: "rbac.authorization.k8s.io/v1"
metadata:
name: "{{ item.name }}"
labels: "{{ test_labels }}"
rules:
- apiGroups: [""]
resources: "{{ item.resources }}"
verbs: "{{ item.verbs }}"
with_items: '{{ cluster_roles }}'
- name: Create Role Binding (namespaced)
kubernetes.core.k8s:
definition:
kind: RoleBinding
apiVersion: "rbac.authorization.k8s.io/v1"
metadata:
name: "{{ cluster_roles[0].name }}-binding"
namespace: "{{ test_ns }}"
labels: "{{ test_labels }}"
subjects:
- kind: ServiceAccount
name: "{{ test_sa }}"
namespace: "{{ test_ns }}"
apiGroup: ""
roleRef:
kind: ClusterRole
name: "{{ cluster_roles[0].name }}"
apiGroup: ""
- name: list Pod for all namespace should failed
kubernetes.core.k8s_info:
api_key: "{{ api_token }}"
host: "{{ cluster_host }}"
validate_certs: no
kind: Pod
register: error
ignore_errors: true
- assert:
that:
- '"pods is forbidden: User" in error.msg'
- name: list Pod for test namespace should succeed
kubernetes.core.k8s_info:
api_key: "{{ api_token }}"
host: "{{ cluster_host }}"
validate_certs: no
kind: Pod
namespace: "{{ test_ns }}"
no_log: true
- name: Create Cluster role Binding
kubernetes.core.k8s:
definition:
kind: ClusterRoleBinding
apiVersion: "{{ item.api_version_binding }}"
metadata:
name: "{{ item.name }}-binding"
labels: "{{ test_labels }}"
subjects:
- kind: ServiceAccount
name: "{{ test_sa }}"
namespace: "{{ test_ns }}"
apiGroup: ""
roleRef:
kind: ClusterRole
name: "{{ item.name }}"
apiGroup: ""
with_items: "{{ cluster_roles }}"
- name: list Pod for all namespace should succeed
kubernetes.core.k8s_info:
api_key: "{{ api_token }}"
host: "{{ cluster_host }}"
validate_certs: no
kind: Pod
no_log: true
- name: list Pod for test namespace should succeed
kubernetes.core.k8s_info:
api_key: "{{ api_token }}"
host: "{{ cluster_host }}"
validate_certs: no
kind: Pod
namespace: "{{ test_ns }}"
no_log: true
- name: list Node using ServiceAccount
kubernetes.core.k8s_info:
api_key: "{{ api_token }}"
host: "{{ cluster_host }}"
validate_certs: no
kind: Node
namespace: "{{ test_ns }}"
no_log: true
- name: Prune clusterroles (check mode)
community.okd.openshift_adm_prune_auth:
resource: clusterroles
label_selectors:
- phase=dev
register: check
check_mode: true
- name: validate clusterrole binding candidates for prune
assert:
that:
- 'item["name"]+"-binding" in check.cluster_role_binding'
- 'test_ns+"/"+cluster_roles[0].name+"-binding" in check.role_binding'
with_items: "{{ cluster_roles }}"
- name: Prune Cluster Role for managing Pod
community.okd.openshift_adm_prune_auth:
resource: clusterroles
name: "{{ cluster_roles[0].name }}"
- name: list Pod for all namespace should failed
kubernetes.core.k8s_info:
api_key: "{{ api_token }}"
host: "{{ cluster_host }}"
validate_certs: no
kind: Pod
register: error
no_log: true
ignore_errors: true
- assert:
that:
- '"pods is forbidden: User" in error.msg'
- name: list Pod for test namespace should failed
kubernetes.core.k8s_info:
api_key: "{{ api_token }}"
host: "{{ cluster_host }}"
validate_certs: no
kind: Pod
namespace: "{{ test_ns }}"
register: error
no_log: true
ignore_errors: true
- assert:
that:
- '"pods is forbidden: User" in error.msg'
- name: list Node using ServiceAccount
kubernetes.core.k8s_info:
api_key: "{{ api_token }}"
host: "{{ cluster_host }}"
validate_certs: no
kind: Node
namespace: "{{ test_ns }}"
no_log: true
- name: Prune clusterroles (remaining)
community.okd.openshift_adm_prune_auth:
resource: clusterroles
label_selectors:
- phase=dev
- name: list Node using ServiceAccount should fail
kubernetes.core.k8s_info:
api_key: "{{ api_token }}"
host: "{{ cluster_host }}"
validate_certs: no
kind: Node
namespace: "{{ test_ns }}"
register: error
ignore_errors: true
- assert:
that:
- '"nodes is forbidden: User" in error.msg'
always:
- name: Ensure namespace is deleted
kubernetes.core.k8s:
state: absent
kind: Namespace
name: "{{ test_ns }}"
ignore_errors: true
- name: Delete ClusterRoleBinding
kubernetes.core.k8s:
kind: ClusterRoleBinding
api_version: "rbac.authorization.k8s.io/v1"
name: "{{ item.name }}-binding"
state: absent
ignore_errors: true
with_items: "{{ cluster_roles }}"
when: cluster_roles is defined
- name: Delete ClusterRole
kubernetes.core.k8s:
kind: ClusterRole
api_version: "rbac.authorization.k8s.io/v1"
name: "{{ item.name }}"
state: absent
ignore_errors: true
with_items: "{{ cluster_roles }}"
when: cluster_roles is defined
@@ -0,0 +1,341 @@
---
- block:
- set_fact:
test_ns: "prune-roles"
sa_name: "roles-sa"
pod_name: "pod-prune"
role_definition:
- name: pod-list
labels:
action: list
verbs:
- list
role_binding:
api_version: rbac.authorization.k8s.io/v1
- name: pod-create
labels:
action: create
verbs:
- create
- get
role_binding:
api_version: authorization.openshift.io/v1
- name: pod-delete
labels:
action: delete
verbs:
- delete
role_binding:
api_version: rbac.authorization.k8s.io/v1
- name: Ensure namespace
kubernetes.core.k8s:
kind: Namespace
name: '{{ test_ns }}'
- name: Get cluster information
kubernetes.core.k8s_cluster_info:
register: cluster_info
no_log: true
- set_fact:
cluster_host: "{{ cluster_info['connection']['host'] }}"
- name: Create Service account
kubernetes.core.k8s:
definition:
apiVersion: v1
kind: ServiceAccount
metadata:
name: '{{ sa_name }}'
namespace: '{{ test_ns }}'
- name: Read Service Account
kubernetes.core.k8s_info:
kind: ServiceAccount
namespace: '{{ test_ns }}'
name: '{{ sa_name }}'
register: sa_out
- set_fact:
secret_token: "{{ sa_out.resources[0]['secrets'][0]['name'] }}"
- name: Get secret details
kubernetes.core.k8s_info:
kind: Secret
namespace: '{{ test_ns }}'
name: '{{ secret_token }}'
register: r_secret
retries: 10
delay: 10
until:
- ("'openshift.io/token-secret.value' in r_secret.resources[0]['metadata']['annotations']") or ("'token' in r_secret.resources[0]['data']")
- set_fact:
api_token: "{{ r_secret.resources[0]['metadata']['annotations']['openshift.io/token-secret.value'] }}"
when: "'openshift.io/token-secret.value' in r_secret.resources[0]['metadata']['annotations']"
- set_fact:
api_token: "{{ r_secret.resources[0]['data']['token'] | b64decode }}"
when: "'token' in r_secret.resources[0]['data']"
- name: list resources using service account
kubernetes.core.k8s_info:
api_key: '{{ api_token }}'
host: '{{ cluster_host }}'
validate_certs: no
kind: Pod
namespace: '{{ test_ns }}'
register: error
ignore_errors: true
- assert:
that:
- '"pods is forbidden: User" in error.msg'
- name: Create a role to manage Pod from namespace "{{ test_ns }}"
kubernetes.core.k8s:
definition:
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
namespace: "{{ test_ns }}"
name: "{{ item.name }}"
labels: "{{ item.labels }}"
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: "{{ item.verbs }}"
with_items: "{{ role_definition }}"
- name: Create Role Binding
kubernetes.core.k8s:
definition:
kind: RoleBinding
apiVersion: "{{ item.role_binding.api_version }}"
metadata:
name: "{{ item.name }}-bind"
namespace: "{{ test_ns }}"
subjects:
- kind: ServiceAccount
name: "{{ sa_name }}"
namespace: "{{ test_ns }}"
apiGroup: ""
roleRef:
kind: Role
name: "{{ item.name }}"
namespace: "{{ test_ns }}"
apiGroup: ""
with_items: "{{ role_definition }}"
- name: Create Pod should succeed
kubernetes.core.k8s:
api_key: "{{ api_token }}"
host: "{{ cluster_host }}"
validate_certs: no
namespace: "{{ test_ns }}"
definition:
kind: Pod
metadata:
name: "{{ pod_name }}"
spec:
containers:
- name: python
image: python:3.7-alpine
command:
- /bin/sh
- -c
- while true; do echo $(date); sleep 15; done
imagePullPolicy: IfNotPresent
register: result
- name: assert pod creation succeed
assert:
that:
- result is successful
- name: List Pod
kubernetes.core.k8s_info:
api_key: "{{ api_token }}"
host: "{{ cluster_host }}"
validate_certs: no
namespace: "{{ test_ns }}"
kind: Pod
register: result
- name: assert user is still authorize to list pods
assert:
that:
- result is successful
- name: Prune auth roles (check mode)
community.okd.openshift_adm_prune_auth:
resource: roles
namespace: "{{ test_ns }}"
register: check
check_mode: true
- name: validate that list role binding are candidates for prune
assert:
that: 'test_ns+"/"+item["name"]+"-bind" in check.role_binding'
with_items: "{{ role_definition }}"
- name: Prune resource using label_selectors option
community.okd.openshift_adm_prune_auth:
resource: roles
namespace: "{{ test_ns }}"
label_selectors:
- action=delete
register: prune
- name: assert that role binding 'delete' was pruned
assert:
that:
- prune is changed
- 'test_ns+"/"+role_definition[2]["name"]+"-bind" in check.role_binding'
- name: assert that user could not delete pod anymore
kubernetes.core.k8s:
api_key: "{{ api_token }}"
host: "{{ cluster_host }}"
validate_certs: no
state: absent
namespace: "{{ test_ns }}"
kind: Pod
name: "{{ pod_name }}"
register: result
ignore_errors: true
- name: assert pod deletion failed due to forbidden user
assert:
that:
- '"forbidden: User" in error.msg'
- name: List Pod
kubernetes.core.k8s_info:
api_key: "{{ api_token }}"
host: "{{ cluster_host }}"
validate_certs: no
namespace: "{{ test_ns }}"
kind: Pod
register: result
- name: assert user is still able to list pods
assert:
that:
- result is successful
- name: Create Pod should succeed
kubernetes.core.k8s:
api_key: "{{ api_token }}"
host: "{{ cluster_host }}"
validate_certs: no
namespace: "{{ test_ns }}"
definition:
kind: Pod
metadata:
name: "{{ pod_name }}-1"
spec:
containers:
- name: python
image: python:3.7-alpine
command:
- /bin/sh
- -c
- while true; do echo $(date); sleep 15; done
imagePullPolicy: IfNotPresent
register: result
- name: assert user is still authorize to create pod
assert:
that:
- result is successful
- name: Prune role using name
community.okd.openshift_adm_prune_auth:
resource: roles
namespace: "{{ test_ns }}"
name: "{{ role_definition[1].name }}"
register: prune
- name: assert that role binding 'create' was pruned
assert:
that:
- prune is changed
- 'test_ns+"/"+role_definition[1]["name"]+"-bind" in check.role_binding'
- name: Create Pod (should failed)
kubernetes.core.k8s:
api_key: "{{ api_token }}"
host: "{{ cluster_host }}"
validate_certs: no
namespace: "{{ test_ns }}"
definition:
kind: Pod
metadata:
name: "{{ pod_name }}-2"
spec:
containers:
- name: python
image: python:3.7-alpine
command:
- /bin/sh
- -c
- while true; do echo $(date); sleep 15; done
imagePullPolicy: IfNotPresent
register: result
ignore_errors: true
- name: assert user is not authorize to create pod anymore
assert:
that:
- '"forbidden: User" in error.msg'
- name: List Pod
kubernetes.core.k8s_info:
api_key: "{{ api_token }}"
host: "{{ cluster_host }}"
validate_certs: no
namespace: "{{ test_ns }}"
kind: Pod
register: result
- name: assert user is still able to list pods
assert:
that:
- result is successful
- name: Prune all role for namespace (neither name nor label_selectors are specified)
community.okd.openshift_adm_prune_auth:
resource: roles
namespace: "{{ test_ns }}"
register: prune
- name: assert that role binding 'list' was pruned
assert:
that:
- prune is changed
- 'test_ns+"/"+role_definition[0]["name"]+"-bind" in check.role_binding'
- name: List Pod
kubernetes.core.k8s_info:
api_key: "{{ api_token }}"
host: "{{ cluster_host }}"
validate_certs: no
namespace: "{{ test_ns }}"
kind: Pod
register: result
ignore_errors: true
- name: assert user is not authorize to list pod anymore
assert:
that:
- '"forbidden: User" in error.msg'
always:
- name: Ensure namespace is deleted
kubernetes.core.k8s:
state: absent
kind: Namespace
name: "{{ test_ns }}"
ignore_errors: true
@@ -0,0 +1,269 @@
---
- name: Prune deployments
block:
- set_fact:
dc_name: "hello"
deployment_ns: "prune-deployments"
deployment_ns_2: "prune-deployments-2"
- name: Ensure namespace
community.okd.k8s:
kind: Namespace
name: '{{ deployment_ns }}'
- name: Create deployment config
community.okd.k8s:
namespace: '{{ deployment_ns }}'
definition:
kind: DeploymentConfig
apiVersion: apps.openshift.io/v1
metadata:
name: '{{ dc_name }}'
spec:
replicas: 1
selector:
name: '{{ dc_name }}'
template:
metadata:
labels:
name: '{{ dc_name }}'
spec:
containers:
- name: hello-openshift
imagePullPolicy: IfNotPresent
image: python:3.7-alpine
command: [ "/bin/sh", "-c", "while true;do date;sleep 2s; done"]
wait: yes
- name: prune deployments (no candidate DeploymentConfig)
community.okd.openshift_adm_prune_deployments:
namespace: "{{ deployment_ns }}"
register: test_prune
- assert:
that:
- test_prune is not changed
- test_prune.replication_controllers | length == 0
- name: Update DeploymentConfig - set replicas to 0
community.okd.k8s:
namespace: "{{ deployment_ns }}"
definition:
kind: DeploymentConfig
apiVersion: "apps.openshift.io/v1"
metadata:
name: "{{ dc_name }}"
spec:
replicas: 0
selector:
name: "{{ dc_name }}"
template:
metadata:
labels:
name: "{{ dc_name }}"
spec:
containers:
- name: hello-openshift
imagePullPolicy: IfNotPresent
image: python:3.7-alpine
command: [ "/bin/sh", "-c", "while true;do date;sleep 2s; done"]
wait: yes
- name: Wait for ReplicationController candidate for pruning
kubernetes.core.k8s_info:
kind: ReplicationController
namespace: "{{ deployment_ns }}"
register: result
retries: 10
delay: 30
until:
- result.resources.0.metadata.annotations["openshift.io/deployment.phase"] in ("Failed", "Complete")
- name: Prune deployments - should delete 1 ReplicationController
community.okd.openshift_adm_prune_deployments:
namespace: "{{ deployment_ns }}"
check_mode: yes
register: test_prune
- name: Read ReplicationController
kubernetes.core.k8s_info:
kind: ReplicationController
namespace: "{{ deployment_ns }}"
register: replications
- name: Assert that Replication controller was not deleted
assert:
that:
- replications.resources | length == 1
- replications.resources.0.metadata.name is match(dc_name+"-*")
- name: Assure that candidate ReplicationController was found for pruning
assert:
that:
- test_prune is changed
- test_prune.replication_controllers | length == 1
- test_prune.replication_controllers.0.metadata.name == replications.resources.0.metadata.name
- test_prune.replication_controllers.0.metadata.namespace == replications.resources.0.metadata.namespace
- name: Prune deployments - keep younger than 45min (check_mode)
community.okd.openshift_adm_prune_deployments:
keep_younger_than: 45
namespace: "{{ deployment_ns }}"
check_mode: true
register: keep_younger
- name: assert no candidate was found
assert:
that:
- keep_younger is not changed
- keep_younger.replication_controllers == []
- name: Ensure second namespace is created
community.okd.k8s:
kind: Namespace
name: '{{ deployment_ns_2 }}'
- name: Create deployment config from 2nd namespace
community.okd.k8s:
namespace: '{{ deployment_ns_2 }}'
definition:
kind: DeploymentConfig
apiVersion: apps.openshift.io/v1
metadata:
name: '{{ dc_name }}2'
spec:
replicas: 1
selector:
name: '{{ dc_name }}2'
template:
metadata:
labels:
name: '{{ dc_name }}2'
spec:
containers:
- name: hello-openshift
imagePullPolicy: IfNotPresent
image: python:3.7-alpine
command: [ "/bin/sh", "-c", "while true;do date;sleep 2s; done"]
wait: yes
- name: Stop deployment config - replicas = 0
community.okd.k8s:
namespace: '{{ deployment_ns_2 }}'
definition:
kind: DeploymentConfig
apiVersion: apps.openshift.io/v1
metadata:
name: '{{ dc_name }}2'
spec:
replicas: 0
selector:
name: '{{ dc_name }}2'
template:
metadata:
labels:
name: '{{ dc_name }}2'
spec:
containers:
- name: hello-openshift
imagePullPolicy: IfNotPresent
image: python:3.7-alpine
command: [ "/bin/sh", "-c", "while true;do date;sleep 2s; done"]
wait: yes
- name: Wait for ReplicationController candidate for pruning
kubernetes.core.k8s_info:
kind: ReplicationController
namespace: "{{ deployment_ns_2 }}"
register: result
retries: 10
delay: 30
until:
- result.resources.0.metadata.annotations["openshift.io/deployment.phase"] in ("Failed", "Complete")
# Prune from one namespace should not have any effect on others namespaces
- name: Prune deployments from 2nd namespace
community.okd.openshift_adm_prune_deployments:
namespace: "{{ deployment_ns_2 }}"
check_mode: yes
register: test_prune
- name: Assure that candidate ReplicationController was found for pruning
assert:
that:
- test_prune is changed
- test_prune.replication_controllers | length == 1
- "test_prune.replication_controllers.0.metadata.namespace == deployment_ns_2"
# Prune without namespace option
- name: Prune from all namespace should update more deployments
community.okd.openshift_adm_prune_deployments:
check_mode: yes
register: no_namespace_prune
- name: Assure multiple ReplicationController were found for pruning
assert:
that:
- no_namespace_prune is changed
- no_namespace_prune.replication_controllers | length == 2
# Execute Prune from 2nd namespace
- name: Read ReplicationController before Prune operation
kubernetes.core.k8s_info:
kind: ReplicationController
namespace: "{{ deployment_ns_2 }}"
register: replications
- assert:
that:
- replications.resources | length == 1
- name: Prune DeploymentConfig from 2nd namespace
community.okd.openshift_adm_prune_deployments:
namespace: "{{ deployment_ns_2 }}"
register: _prune
- name: Assert DeploymentConfig was deleted
assert:
that:
- _prune is changed
- _prune.replication_controllers | length == 1
- _prune.replication_controllers.0.details.name == replications.resources.0.metadata.name
# Execute Prune without namespace option
- name: Read ReplicationController before Prune operation
kubernetes.core.k8s_info:
kind: ReplicationController
namespace: "{{ deployment_ns }}"
register: replications
- assert:
that:
- replications.resources | length == 1
- name: Prune from all namespace should update more deployments
community.okd.openshift_adm_prune_deployments:
register: _prune
- name: Assure multiple ReplicationController were found for pruning
assert:
that:
- _prune is changed
- _prune.replication_controllers | length > 0
always:
- name: Delete 1st namespace
community.okd.k8s:
state: absent
kind: Namespace
name: "{{ deployment_ns }}"
ignore_errors: yes
when: deployment_ns is defined
- name: Delete 2nd namespace
community.okd.k8s:
state: absent
kind: Namespace
name: "{{ deployment_ns_2 }}"
ignore_errors: yes
when: deployment_ns_2 is defined
+88 -28
View File
@@ -1,51 +1,111 @@
--- ---
- vars: - block:
# TODO(fabianvf) Get this parameter working locally as well - set_fact:
openshift_host: 'https://kubernetes.default.svc' admin_user: test
block: admin_pass: testing123
- name: Retrieve cluster info
kubernetes.core.k8s_cluster_info:
register: k8s_cluster
- name: set openshift host value
set_fact:
openshift_host: "{{ k8s_cluster.connection.host }}"
- name: Log in (obtain access token) - name: Log in (obtain access token)
community.okd.openshift_auth: community.okd.openshift_auth:
username: test username: "{{ admin_user }}"
password: testing123 password: "{{ admin_pass }}"
host: '{{ openshift_host }}' host: '{{ openshift_host }}'
verify_ssl: false verify_ssl: false
register: openshift_auth_results register: openshift_auth_results
- name: Get the test User - set_fact:
community.kubernetes.k8s_info: auth_api_key: "{{ openshift_auth_results.openshift_auth.api_key }}"
api_key: "{{ openshift_auth_results.openshift_auth.api_key }}"
- name: "Get the {{ admin_user }} User"
kubernetes.core.k8s_info:
api_key: "{{ auth_api_key }}"
host: '{{ openshift_host }}' host: '{{ openshift_host }}'
verify_ssl: false verify_ssl: false
kind: User kind: User
api_version: user.openshift.io/v1 api_version: user.openshift.io/v1
name: test name: "{{ admin_user }}"
register: user_result register: user_result
- name: assert that the user was found - name: assert that the user was found
assert: assert:
that: (user_result.resources | length) == 1 that: (user_result.resources | length) == 1
- name: list available tokens
kubernetes.core.k8s_info:
kind: UserOAuthAccessToken
version: oauth.openshift.io/v1
register: tokens
- debug: var=tokens
- set_fact:
token_names: "{{ tokens.resources | map(attribute='metadata.name') | list }}"
- block:
- debug: var=token_names
- name: Revoke access token
community.okd.openshift_auth:
state: absent
api_key: "{{ auth_api_key }}"
host: '{{ openshift_host }}'
verify_ssl: false
register: _revoke
- name: Ensure that token has been revoked
assert:
that:
- _revoke is changed
- name: "Get the {{ admin_user }} User (after token deletion)"
kubernetes.core.k8s_info:
api_key: "{{ auth_api_key }}"
host: '{{ openshift_host }}'
verify_ssl: false
kind: User
api_version: user.openshift.io/v1
name: "{{ admin_user }}"
ignore_errors: true
retries: 50
until: user_result is failed
delay: 20
register: user_result
- name: Ensure that task has failed due to revoked token
assert:
that:
- user_result is failed
- name: Revoke access token once again (should fail)
community.okd.openshift_auth:
state: absent
api_key: "{{ auth_api_key }}"
host: '{{ openshift_host }}'
verify_ssl: false
register: _revoke
ignore_errors: true
- name: Ensure that nothing changed
assert:
that:
- _revoke is failed
- _revoke.msg.startswith("Couldn't delete user oauth access token")
when: token_names | length > 0
always: always:
- name: If login succeeded, try to log out (revoke access token) - name: If login succeeded, try to log out (revoke access token)
when: openshift_auth_results.openshift_auth.api_key is defined when: auth_api_key is defined
community.okd.openshift_auth: community.okd.openshift_auth:
state: absent state: absent
api_key: "{{ openshift_auth_results.openshift_auth.api_key }}" api_key: "{{ auth_api_key }}"
host: '{{ openshift_host }}' host: '{{ openshift_host }}'
verify_ssl: false verify_ssl: false
ignore_errors: true
- name: Get the test user
community.kubernetes.k8s_info:
api_key: "{{ openshift_auth_results.openshift_auth.api_key }}"
host: '{{ openshift_host }}'
verify_ssl: false
kind: User
name: test
api_version: user.openshift.io/v1
register: failed_user_result
ignore_errors: yes
# TODO(fabianvf) determine why token is not being rejected, maybe add more info to return
# - name: assert that the user was not found
# assert:
# that: (failed_user_result.resources | length) == 0
+250
View File
@@ -0,0 +1,250 @@
---
- block:
- set_fact:
build_ns: "builds"
build_config: "start-build"
is_name: "ruby"
prune_build: "prune-build"
- name: Ensure namespace
kubernetes.core.k8s:
kind: Namespace
name: "{{ build_ns }}"
- name: Create ImageStream
community.okd.k8s:
namespace: "{{ build_ns }}"
definition:
apiVersion: image.openshift.io/v1
kind: ImageStream
metadata:
name: "{{ is_name }}"
spec:
lookupPolicy:
local: false
tags: []
- name: Create build configuration
community.okd.k8s:
namespace: "{{ build_ns }}"
definition:
kind: BuildConfig
apiVersion: build.openshift.io/v1
metadata:
name: "{{ build_config }}"
spec:
source:
dockerfile: |
FROM openshift/ruby-22-centos7
RUN sleep 60s
USER ansible
strategy:
type: Docker
output:
to:
kind: "ImageStreamTag"
name: "{{ is_name }}:latest"
- name: Start Build from Build configuration
community.okd.openshift_build:
namespace: "{{ build_ns }}"
build_config_name: "{{ build_config }}"
register: new_build
- name: Assert that a build has been created
assert:
that:
- new_build is changed
- new_build.builds.0.metadata.name == build_config+"-1"
- name: Start a new Build from previous Build
community.okd.openshift_build:
namespace: "{{ build_ns }}"
build_name: "{{ new_build.builds.0.metadata.name }}"
register: rerun_build
- name: Assert that another build has been created
assert:
that:
- rerun_build is changed
- rerun_build.builds.0.metadata.name == build_config+"-2"
- name: Cancel first build created
community.okd.openshift_build:
namespace: "{{ build_ns }}"
build_name: "{{ build_config }}-1"
state: cancelled
wait: yes
register: cancel
- name: Assert that the Build was cancelled
assert:
that:
- cancel is changed
- cancel.builds | length == 1
- cancel.builds.0.metadata.name == build_config+"-1"
- cancel.builds.0.metadata.namespace == build_ns
- '"cancelled" in cancel.builds.0.status'
- cancel.builds.0.status.cancelled
- name: Get info for 1st Build
kubernetes.core.k8s_info:
version: build.openshift.io/v1
kind: Build
namespace: "{{ build_ns }}"
name: "{{ cancel.builds.0.metadata.name }}"
register: build
- name: Assert that build phase is cancelled
assert:
that:
- build.resources | length == 1
- '"cancelled" in build.resources.0.status'
- build.resources.0.status.cancelled
- build.resources.0.status.phase == 'Cancelled'
- name: Cancel and restart Build using build config name
community.okd.openshift_build:
namespace: "{{ build_ns }}"
build_config_name: "{{ build_config }}"
state: restarted
build_phases:
- Pending
- Running
- New
register: restart
- name: assert that new build was created
assert:
that:
- restart is changed
- restart.builds | length == 1
- restart.builds.0.metadata.name == build_config+"-3"
- name: Get info for 2nd Build
kubernetes.core.k8s_info:
version: build.openshift.io/v1
kind: Build
namespace: "{{ build_ns }}"
name: "{{ build_config }}-2"
register: build
- name: Assert that build phase is cancelled
assert:
that:
- build.resources | length == 1
- '"cancelled" in build.resources.0.status'
- build.resources.0.status.cancelled
- build.resources.0.status.phase == 'Cancelled'
- name: Get info for 3rd build
kubernetes.core.k8s_info:
version: build.openshift.io/v1
kind: Build
namespace: "{{ build_ns }}"
name: "{{ build_config }}-3"
register: build
- name: Assert that Build is not cancelled
assert:
that:
- build.resources | length == 1
- '"cancelled" not in build.resources.0.status'
- "build.resources.0.status.phase in ('New', 'Pending', 'Running')"
- name: Prune Builds keep younger than 30min
community.okd.openshift_adm_prune_builds:
keep_younger_than: 30
namespace: "{{ build_ns }}"
register: prune
check_mode: yes
- name: Assert that no Builds were found
assert:
that:
- not prune.changed
- prune.builds | length == 0
- name: Prune Builds without namespace
community.okd.openshift_adm_prune_builds:
register: prune_without_ns
check_mode: yes
- name: Assert that completed build are candidate for prune
assert:
that:
- prune_without_ns is changed
- prune_without_ns.builds | length > 0
- 'build_config+"-1" in build_names'
- 'build_config+"-2" in build_names'
vars:
build_names: '{{ prune_without_ns.builds | map(attribute="metadata") | flatten | map(attribute="name") | list }}'
- name: Prune Builds using namespace
community.okd.openshift_adm_prune_builds:
namespace: "{{ build_ns }}"
register: prune_with_ns
check_mode: yes
- name: Assert that prune operation found the completed build
assert:
that:
- prune_with_ns is changed
- prune_with_ns.builds | length == 2
- name: Check Build before prune
kubernetes.core.k8s_info:
kind: Build
api_version: build.openshift.io/v1
name: "{{ build_config }}-1"
namespace: "{{ build_ns }}"
register: resource
- name: Validate that any previous build operation executed with check_mode did not deleted the build
assert:
that:
- resource.resources | length == 1
- name: Execute prune operation
community.okd.openshift_adm_prune_builds:
namespace: "{{ build_ns }}"
register: prune
- name: assert prune is changed
assert:
that:
- prune is changed
- name: Check Build
kubernetes.core.k8s_info:
kind: Build
api_version: build.openshift.io/v1
name: "{{ build_config }}-1"
namespace: "{{ build_ns }}"
register: resource
- name: Assert that the Build does not exist anymore
assert:
that:
- resource.resources | length == 0
- name: Check Build
kubernetes.core.k8s_info:
kind: Build
api_version: build.openshift.io/v1
name: "{{ build_config }}-2"
namespace: "{{ build_ns }}"
register: resource
- name: Assert that the Build does not exist anymore
assert:
that:
- resource.resources | length == 0
always:
- name: Ensure namespace is deleted
kubernetes.core.k8s:
state: absent
kind: Namespace
name: "{{ build_ns }}"
ignore_errors: true
@@ -0,0 +1,180 @@
---
- name: Openshift import image testing
block:
- set_fact:
test_ns: "import-images"
- name: Ensure namespace
community.okd.k8s:
kind: Namespace
name: '{{ test_ns }}'
- name: Import image using tag (should import latest tag only)
community.okd.openshift_import_image:
namespace: "{{ test_ns }}"
name: "ansible/awx"
check_mode: yes
register: import_tag
- name: Assert only latest was imported
assert:
that:
- import_tag is changed
- import_tag.result | length == 1
- import_tag.result.0.spec.import
- import_tag.result.0.spec.images.0.from.kind == "DockerImage"
- import_tag.result.0.spec.images.0.from.name == "ansible/awx"
- name: check image stream
kubernetes.core.k8s_info:
kind: ImageStream
namespace: "{{ test_ns }}"
name: awx
register: resource
- name: assert that image stream is not created when using check_mode=yes
assert:
that:
- resource.resources == []
- name: Import image using tag (should import latest tag only)
community.okd.openshift_import_image:
namespace: "{{ test_ns }}"
name: "ansible/awx"
register: import_tag
- name: Assert only latest was imported
assert:
that:
- import_tag is changed
- name: check image stream
kubernetes.core.k8s_info:
kind: ImageStream
namespace: "{{ test_ns }}"
name: awx
register: resource
- name: assert that image stream contains only tag latest
assert:
that:
- resource.resources | length == 1
- resource.resources.0.status.tags.0.tag == 'latest'
- name: Import once again the latest tag
community.okd.openshift_import_image:
namespace: "{{ test_ns }}"
name: "ansible/awx"
register: import_tag
- name: assert change was performed
assert:
that:
- import_tag is changed
- name: check image stream
kubernetes.core.k8s_info:
kind: ImageStream
version: image.openshift.io/v1
namespace: "{{ test_ns }}"
name: awx
register: resource
- name: assert that image stream still contains unique tag
assert:
that:
- resource.resources | length == 1
- resource.resources.0.status.tags.0.tag == 'latest'
- name: Import another tags
community.okd.openshift_import_image:
namespace: "{{ test_ns }}"
name: "ansible/awx:17.1.0"
register: import_another_tag
ignore_errors: yes
- name: assert that another tag was imported
assert:
that:
- import_another_tag is failed
- '"the tag 17.1.0 does not exist on the image stream" in import_another_tag.msg'
- name: Create simple ImageStream (without docker external container)
community.okd.k8s:
namespace: "{{ test_ns }}"
name: "local-is"
definition:
apiVersion: image.openshift.io/v1
kind: ImageStream
spec:
lookupPolicy:
local: false
tags: []
- name: Import all tag for image stream not pointing on external container image should failed
community.okd.openshift_import_image:
namespace: "{{ test_ns }}"
name: "local-is"
all: true
register: error_tag
ignore_errors: true
check_mode: yes
- name: Assert module cannot import from non-existing tag from ImageStream
assert:
that:
- error_tag is failed
- error_tag.msg == "image stream "+test_ns+"/local-is does not have tags pointing to external container images"
- name: import all tags for container image ibmcom/pause and specific tag for redhat/ubi8-micro
community.okd.openshift_import_image:
namespace: "{{ test_ns }}"
name:
- "ibmcom/pause"
- "redhat/ubi8-micro:8.5-437"
all: true
register: multiple_import
- name: Assert that import succeed
assert:
that:
- multiple_import is changed
- multiple_import.result | length == 2
- name: Read ibmcom/pause ImageStream
kubernetes.core.k8s_info:
version: image.openshift.io/v1
kind: ImageStream
namespace: "{{ test_ns }}"
name: pause
register: pause
- name: assert that ibmcom/pause has multiple tags
assert:
that:
- pause.resources | length == 1
- pause.resources.0.status.tags | length > 1
- name: Read redhat/ubi8-micro ImageStream
kubernetes.core.k8s_info:
version: image.openshift.io/v1
kind: ImageStream
namespace: "{{ test_ns }}"
name: ubi8-micro
register: resource
- name: assert that redhat/ubi8-micro has only one tag
assert:
that:
- resource.resources | length == 1
- resource.resources.0.status.tags | length == 1
- 'resource.resources.0.status.tags.0.tag == "8.5-437"'
always:
- name: Delete testing namespace
community.okd.k8s:
state: absent
kind: Namespace
name: "{{ test_ns }}"
ignore_errors: yes
+20 -1
View File
@@ -133,7 +133,7 @@
that: result is not changed that: result is not changed
- name: Get the created configmap - name: Get the created configmap
community.kubernetes.k8s_info: kubernetes.core.k8s_info:
api_version: v1 api_version: v1
kind: ConfigMap kind: ConfigMap
name: example name: example
@@ -162,3 +162,22 @@
- assert: - assert:
that: result is not changed that: result is not changed
# Processing template without message
- name: create template with file {{ files_dir }}/pod-template.yaml
kubernetes.core.k8s:
namespace: process-test
src: "{{ files_dir }}/pod-template.yaml"
state: present
- name: Process pod template
community.okd.openshift_process:
name: pod-template
namespace: process-test
state: rendered
parameters:
NAME: ansible
register: rendered_template
- assert:
that: rendered_template.message == ""
@@ -0,0 +1,217 @@
---
- name: Read registry information
community.okd.openshift_registry_info:
check: yes
register: registry
- name: Display registry information
debug: var=registry
- block:
- set_fact:
prune_ns: "prune-images"
prune_registry: "{{ registry.public_hostname }}"
container:
name: "httpd"
from: "centos/python-38-centos7:20210629-304c7c8"
pod_name: "test-pod"
- name: Ensure namespace is created
community.okd.k8s:
kind: Namespace
name: "{{ prune_ns }}"
- name: Import image into internal registry
community.okd.openshift_import_image:
namespace: "{{ prune_ns }}"
name: "{{ container.name }}"
source: "{{ container.from }}"
- name: Create simple Pod
community.okd.k8s:
namespace: "{{ prune_ns }}"
wait: yes
definition:
apiVersion: v1
kind: Pod
metadata:
name: "{{ pod_name }}"
spec:
containers:
- name: test-container
image: "{{ prune_registry }}/{{ prune_ns }}/{{ container.name }}:latest"
command:
- /bin/sh
- -c
- while true;do date;sleep 5; done
- name: Create limit range for images size
community.okd.k8s:
namespace: "{{ prune_ns }}"
definition:
kind: "LimitRange"
metadata:
name: "image-resource-limits"
spec:
limits:
- type: openshift.io/Image
max:
storage: 1Gi
- name: Prune images from namespace
community.okd.openshift_adm_prune_images:
registry_url: "{{ prune_registry }}"
namespace: "{{ prune_ns }}"
check_mode: yes
register: prune
- name: Assert that nothing to prune as image is in used
assert:
that:
- prune is not changed
- prune is successful
- prune.deleted_images == []
- prune.updated_image_streams == []
- name: Delete Pod created before
community.okd.k8s:
state: absent
name: "{{ pod_name }}"
kind: Pod
namespace: "{{ prune_ns }}"
wait: yes
- name: Prune images from namespace
community.okd.openshift_adm_prune_images:
registry_url: "{{ prune_registry }}"
namespace: "{{ prune_ns }}"
check_mode: yes
register: prune
- name: Read ImageStream
kubernetes.core.k8s_info:
version: image.openshift.io/v1
kind: ImageStream
namespace: "{{ prune_ns }}"
name: "{{ container.name }}"
register: isinfo
- set_fact:
is_image_name: "{{ isinfo.resources.0.status.tags[0]['items'].0.image }}"
- name: Assert that corresponding Image and ImageStream were candidate for pruning
assert:
that:
- prune is changed
- prune.deleted_images | length == 1
- prune.deleted_images.0.metadata.name == is_image_name
- prune.updated_image_streams | length == 1
- prune.updated_image_streams.0.metadata.name == container.name
- prune.updated_image_streams.0.metadata.namespace == prune_ns
- prune.updated_image_streams.0.status.tags == []
- name: Prune images from namespace keeping images and referrer younger than 60minutes
community.okd.openshift_adm_prune_images:
registry_url: "{{ prune_registry }}"
namespace: "{{ prune_ns }}"
keep_younger_than: 60
check_mode: yes
register: younger
- assert:
that:
- younger is not changed
- younger is successful
- younger.deleted_images == []
- younger.updated_image_streams == []
- name: Prune images over size limit
community.okd.openshift_adm_prune_images:
registry_url: "{{ prune_registry }}"
namespace: "{{ prune_ns }}"
prune_over_size_limit: yes
check_mode: yes
register: prune_over_size
- assert:
that:
- prune_over_size is not changed
- prune_over_size is successful
- prune_over_size.deleted_images == []
- prune_over_size.updated_image_streams == []
- name: Update limit range for images size
community.okd.k8s:
namespace: "{{ prune_ns }}"
definition:
kind: "LimitRange"
metadata:
name: "image-resource-limits"
spec:
limits:
- type: openshift.io/Image
max:
storage: 1Ki
- name: Prune images over size limit (check_mode=yes)
community.okd.openshift_adm_prune_images:
registry_url: "{{ prune_registry }}"
namespace: "{{ prune_ns }}"
prune_over_size_limit: yes
check_mode: yes
register: prune
- name: Assert Images and ImageStream were candidate for prune
assert:
that:
- prune is changed
- prune.deleted_images | length == 1
- prune.deleted_images.0.metadata.name == is_image_name
- prune.updated_image_streams | length == 1
- prune.updated_image_streams.0.metadata.name == container.name
- prune.updated_image_streams.0.metadata.namespace == prune_ns
- prune.updated_image_streams.0.status.tags == []
- name: Prune images over size limit
community.okd.openshift_adm_prune_images:
registry_url: "{{ prune_registry }}"
namespace: "{{ prune_ns }}"
prune_over_size_limit: yes
register: prune
- name: Assert that Images and ImageStream were candidate for prune
assert:
that:
- prune is changed
- prune.deleted_images | length == 1
- prune.deleted_images.0.details.name == is_image_name
- prune.updated_image_streams | length == 1
- prune.updated_image_streams.0.metadata.name == container.name
- prune.updated_image_streams.0.metadata.namespace == prune_ns
- '"tags" not in prune.updated_image_streams.0.status'
- name: Validate that ImageStream was updated
kubernetes.core.k8s_info:
version: image.openshift.io/v1
kind: ImageStream
namespace: "{{ prune_ns }}"
name: "{{ container.name }}"
register: stream
- name: Assert that ImageStream was updated
assert:
that:
- stream.resources | length == 1
- '"tags" not in stream.resources.0.status'
always:
- name: Delete namespace
community.okd.k8s:
name: "{{ prune_ns }}"
kind: Namespace
state: absent
ignore_errors: true
when:
- registry.public_hostname
- registry.check.reached
+46 -11
View File
@@ -19,10 +19,10 @@
app: hello-kubernetes app: hello-kubernetes
spec: spec:
containers: containers:
- name: hello-kubernetes - name: hello-kubernetes
image: docker.io/openshift/hello-openshift image: docker.io/openshift/hello-openshift
ports: ports:
- containerPort: 8080 - containerPort: 8080
- name: Create Service - name: Create Service
community.okd.k8s: community.okd.k8s:
@@ -35,8 +35,8 @@
namespace: default namespace: default
spec: spec:
ports: ports:
- port: 80 - port: 80
targetPort: 8080 targetPort: 8080
selector: selector:
app: hello-kubernetes app: hello-kubernetes
@@ -51,7 +51,7 @@
url: 'http://{{ route.result.spec.host }}' url: 'http://{{ route.result.spec.host }}'
return_content: yes return_content: yes
until: result is successful until: result is successful
retries: 10 retries: 20
register: result register: result
- name: Assert the page content is as expected - name: Assert the page content is as expected
@@ -87,6 +87,8 @@
uri: uri:
url: 'http://{{ route.result.spec.host }}' url: 'http://{{ route.result.spec.host }}'
return_content: yes return_content: yes
until: result is successful
retries: 20
register: result register: result
- name: Assert the page content is as expected - name: Assert the page content is as expected
@@ -118,7 +120,7 @@
url: 'http://{{ route.result.spec.host }}' url: 'http://{{ route.result.spec.host }}'
return_content: yes return_content: yes
until: result is successful until: result is successful
retries: 10 retries: 20
register: result register: result
- name: Assert the page content is as expected - name: Assert the page content is as expected
@@ -178,7 +180,7 @@
validate_certs: no validate_certs: no
return_content: yes return_content: yes
until: result is successful until: result is successful
retries: 10 retries: 20
register: result register: result
- name: Assert the page content is as expected - name: Assert the page content is as expected
@@ -206,7 +208,7 @@
validate_certs: no validate_certs: no
return_content: yes return_content: yes
until: result is successful until: result is successful
retries: 10 retries: 20
register: result register: result
- name: Assert the page content is as expected - name: Assert the page content is as expected
@@ -221,7 +223,7 @@
url: 'http://{{ route.result.spec.host }}' url: 'http://{{ route.result.spec.host }}'
status_code: 503 status_code: 503
until: result is successful until: result is successful
retries: 10 retries: 20
register: result register: result
- debug: var=result - debug: var=result
@@ -238,3 +240,36 @@
namespace: default namespace: default
state: absent state: absent
wait: yes wait: yes
# Route with labels and annotations
- name: Create route with labels and annotations
community.okd.openshift_route:
service: hello-kubernetes
namespace: default
name: route-label-annotation
labels:
ansible: test
annotations:
haproxy.router.openshift.io/balance: roundrobin
- name: Get route information
kubernetes.core.k8s_info:
api_version: route.openshift.io/v1
kind: Route
name: route-label-annotation
namespace: default
register: route
- assert:
that:
- route.resources[0].metadata.annotations is defined
- '"haproxy.router.openshift.io/balance" in route.resources[0].metadata.annotations'
- route.resources[0].metadata.labels is defined
- '"ansible" in route.resources[0].metadata.labels'
- name: Delete route
community.okd.openshift_route:
name: route-label-annotation
namespace: default
state: absent
wait: yes
@@ -97,7 +97,6 @@
assert: assert:
that: that:
- unknown_kind is successful - unknown_kind is successful
- "'warnings' in unknown_kind"
always: always:
- name: remove custom resource - name: remove custom resource
@@ -22,4 +22,4 @@
assert: assert:
that: that:
- k8s_no_validate is failed - k8s_no_validate is failed
- "k8s_no_validate.msg == 'kubernetes-validate python library is required to validate resources'" - k8s_no_validate.msg.startswith('Failed to import the required Python library (kubernetes-validate)')
+12 -10
View File
@@ -64,14 +64,16 @@ okd_dc_triggers:
okd_dc_spec: okd_dc_spec:
template: '{{ k8s_pod_template }}' template: '{{ k8s_pod_template }}'
triggers: '{{ okd_dc_triggers }}' selector:
matchLabels:
app: "{{ k8s_pod_name }}"
replicas: 1 replicas: 1
strategy: strategy:
type: Recreate type: Recreate
okd_dc_template: okd_dc_template:
apiVersion: v1 apiVersion: apps/v1
kind: DeploymentConfig kind: Deployment
spec: '{{ okd_dc_spec }}' spec: '{{ okd_dc_spec }}'
okd_imagestream_template: okd_imagestream_template:
@@ -83,12 +85,12 @@ okd_imagestream_template:
lookupPolicy: lookupPolicy:
local: true local: true
tags: tags:
- annotations: null - annotations: null
from: from:
kind: DockerImage kind: DockerImage
name: '{{ image }}' name: '{{ image }}'
name: '{{ image_tag }}' name: '{{ image_tag }}'
referencePolicy: referencePolicy:
type: Source type: Source
image_tag: latest image_tag: latest
+9
View File
@@ -61,7 +61,13 @@
- import_tasks: tasks/validate_not_installed.yml - import_tasks: tasks/validate_not_installed.yml
- import_tasks: tasks/openshift_auth.yml - import_tasks: tasks/openshift_auth.yml
- import_tasks: tasks/openshift_adm_prune_auth_clusterroles.yml
- import_tasks: tasks/openshift_adm_prune_auth_roles.yml
- import_tasks: tasks/openshift_adm_prune_deployments.yml
- import_tasks: tasks/openshift_builds.yml
- import_tasks: tasks/openshift_route.yml - import_tasks: tasks/openshift_route.yml
- import_tasks: tasks/openshift_import_images.yml
- import_tasks: tasks/openshift_prune_images.yml
- block: - block:
- name: Create namespace - name: Create namespace
community.okd.k8s: community.okd.k8s:
@@ -78,3 +84,6 @@
kind: Namespace kind: Namespace
name: process-test name: process-test
state: absent state: absent
roles:
- role: openshift_adm_groups
+32 -19
View File
@@ -17,14 +17,15 @@
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>. # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function) from __future__ import absolute_import, division, print_function
__metaclass__ = type __metaclass__ = type
DOCUMENTATION = ''' DOCUMENTATION = """
author: author:
- xuxinkun - xuxinkun (@xuxinkun)
connection: oc name: oc
short_description: Execute tasks in pods running on OpenShift. short_description: Execute tasks in pods running on OpenShift.
@@ -71,7 +72,7 @@ DOCUMENTATION = '''
- name: K8S_AUTH_EXTRA_ARGS - name: K8S_AUTH_EXTRA_ARGS
oc_kubeconfig: oc_kubeconfig:
description: description:
- Path to a oc config file. Defaults to I(~/.kube/conig) - Path to a oc config file. Defaults to I(~/.kube/config)
default: '' default: ''
vars: vars:
- name: ansible_oc_kubeconfig - name: ansible_oc_kubeconfig
@@ -105,6 +106,15 @@ DOCUMENTATION = '''
env: env:
- name: K8S_AUTH_TOKEN - name: K8S_AUTH_TOKEN
- name: K8S_AUTH_API_KEY - name: K8S_AUTH_API_KEY
oc_local_env_vars:
description:
- Local environment variable to be passed locally to the oc command line.
- Please be aware that this passes information directly on the command line and it could expose sensitive data.
default: {}
type: dict
version_added: 4.0.0
vars:
- name: ansible_oc_local_env_vars
client_cert: client_cert:
description: description:
- Path to a certificate used to authenticate with the API. - Path to a certificate used to authenticate with the API.
@@ -145,29 +155,32 @@ DOCUMENTATION = '''
env: env:
- name: K8S_AUTH_VERIFY_SSL - name: K8S_AUTH_VERIFY_SSL
aliases: [ oc_verify_ssl ] aliases: [ oc_verify_ssl ]
''' """
from ansible_collections.community.kubernetes.plugins.connection.kubectl import Connection as KubectlConnection from ansible_collections.kubernetes.core.plugins.connection.kubectl import (
Connection as KubectlConnection,
)
CONNECTION_TRANSPORT = 'oc' CONNECTION_TRANSPORT = "oc"
CONNECTION_OPTIONS = { CONNECTION_OPTIONS = {
'oc_container': '-c', "oc_container": "-c",
'oc_namespace': '-n', "oc_namespace": "-n",
'oc_kubeconfig': '--config', "oc_kubeconfig": "--kubeconfig",
'oc_context': '--context', "oc_context": "--context",
'oc_host': '--server', "oc_host": "--server",
'client_cert': '--client-certificate', "client_cert": "--client-certificate",
'client_key': '--client-key', "client_key": "--client-key",
'ca_cert': '--certificate-authority', "ca_cert": "--certificate-authority",
'validate_certs': '--insecure-skip-tls-verify', "validate_certs": "--insecure-skip-tls-verify",
'oc_token': '--token' "oc_token": "--token",
} }
class Connection(KubectlConnection): class Connection(KubectlConnection):
''' Local oc based connections ''' """Local oc based connections"""
transport = CONNECTION_TRANSPORT transport = CONNECTION_TRANSPORT
connection_options = CONNECTION_OPTIONS connection_options = CONNECTION_OPTIONS
documentation = DOCUMENTATION documentation = DOCUMENTATION
+105 -56
View File
@@ -1,15 +1,14 @@
# Copyright (c) 2018 Ansible Project # Copyright (c) 2018 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # 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) from __future__ import absolute_import, division, print_function
__metaclass__ = type __metaclass__ = type
DOCUMENTATION = ''' DOCUMENTATION = """
name: openshift name: openshift
plugin_type: inventory
author: author:
- Chris Houseknecht <@chouseknecht> - Chris Houseknecht (@chouseknecht)
short_description: OpenShift inventory source short_description: OpenShift inventory source
@@ -18,11 +17,18 @@ DOCUMENTATION = '''
- Groups by cluster name, namespace, namespace_services, namespace_pods, namespace_routes, and labels - Groups by cluster name, namespace, namespace_services, namespace_pods, namespace_routes, and labels
- Uses openshift.(yml|yaml) YAML configuration file to set parameter values. - Uses openshift.(yml|yaml) YAML configuration file to set parameter values.
deprecated:
removed_in: 5.0.0
why: |
As discussed in U(https://github.com/ansible-collections/kubernetes.core/issues/31), we decided to
remove the openshift inventory plugin in release 5.0.0.
alternative: "Use M(kubernetes.core.k8s_info) and M(ansible.builtin.add_host) instead."
options: options:
plugin: plugin:
description: token that ensures this is a source file for the 'openshift' plugin. description: token that ensures this is a source file for the 'openshift' plugin.
required: True required: True
choices: ['openshift'] choices: ['openshift', 'community.okd.openshift']
connections: connections:
description: description:
- Optional list of cluster connection settings. If no connections are provided, the default - Optional list of cluster connection settings. If no connections are provided, the default
@@ -36,8 +42,8 @@ DOCUMENTATION = '''
kubeconfig: kubeconfig:
description: description:
- Path to an existing Kubernetes config file. If not provided, and no other connection - Path to an existing Kubernetes config file. If not provided, and no other connection
options are provided, the OpenShift client will attempt to load the default options are provided, the Kubernetes client will attempt to load the default
configuration file from I(~/.kube/config.json). Can also be specified via K8S_AUTH_KUBECONFIG configuration file from I(~/.kube/config). Can also be specified via K8S_AUTH_KUBECONFIG
environment variable. environment variable.
context: context:
description: description:
@@ -85,81 +91,114 @@ DOCUMENTATION = '''
to access. to access.
requirements: requirements:
- "python >= 2.7" - "python >= 3.6"
- "openshift >= 0.6" - "kubernetes >= 12.0.0"
- "PyYAML >= 3.11" - "PyYAML >= 3.11"
''' """
EXAMPLES = ''' EXAMPLES = """
# File must be named openshift.yaml or openshift.yml # File must be named openshift.yaml or openshift.yml
# Authenticate with token, and return all pods and services for all namespaces - name: Authenticate with token, and return all pods and services for all namespaces
plugin: community.okd.openshift plugin: community.okd.openshift
connections: connections:
- host: https://192.168.64.4:8443 - host: https://192.168.64.4:8443
api_key: xxxxxxxxxxxxxxxx api_key: xxxxxxxxxxxxxxxx
verify_ssl: false verify_ssl: false
# Use default config (~/.kube/config) file and active context, and return objects for a specific namespace - name: Use default config (~/.kube/config) file and active context, and return objects for a specific namespace
plugin: community.okd.openshift plugin: community.okd.openshift
connections: connections:
- namespaces: - namespaces:
- testing - testing
# Use a custom config file, and a specific context. - name: Use a custom config file, and a specific context.
plugin: community.okd.openshift plugin: community.okd.openshift
connections: connections:
- kubeconfig: /path/to/config - kubeconfig: /path/to/config
context: 'awx/192-168-64-4:8443/developer' context: 'awx/192-168-64-4:8443/developer'
''' """
from ansible_collections.community.kubernetes.plugins.inventory.k8s import K8sInventoryException, InventoryModule as K8sInventoryModule, format_dynamic_api_exc
try: try:
from openshift.dynamic.exceptions import DynamicApiError from ansible_collections.kubernetes.core.plugins.inventory.k8s import (
K8sInventoryException,
InventoryModule as K8sInventoryModule,
format_dynamic_api_exc,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
get_api_client,
)
HAS_KUBERNETES_COLLECTION = True
except ImportError as e:
HAS_KUBERNETES_COLLECTION = False
try:
from kubernetes.dynamic.exceptions import DynamicApiError
except ImportError: except ImportError:
pass pass
class InventoryModule(K8sInventoryModule): class InventoryModule(K8sInventoryModule):
NAME = 'community.okd.openshift' NAME = "community.okd.openshift"
connection_plugin = 'community.okd.oc' connection_plugin = "community.okd.oc"
transport = 'oc' transport = "oc"
def check_kubernetes_collection(self):
if not HAS_KUBERNETES_COLLECTION:
raise K8sInventoryException(
"The kubernetes.core collection must be installed"
)
def fetch_objects(self, connections): def fetch_objects(self, connections):
self.check_kubernetes_collection()
super(InventoryModule, self).fetch_objects(connections) super(InventoryModule, self).fetch_objects(connections)
self.display.deprecated(
"The 'openshift' inventory plugin has been deprecated and will be removed in release 5.0.0",
version="5.0.0",
collection_name="community.okd",
)
if connections: if connections:
if not isinstance(connections, list): if not isinstance(connections, list):
raise K8sInventoryException("Expecting connections to be a list.") raise K8sInventoryException("Expecting connections to be a list.")
for connection in connections: for connection in connections:
client = self.get_api_client(**connection) client = get_api_client(**connection)
name = connection.get('name', self.get_default_host_name(client.configuration.host)) name = connection.get(
if connection.get('namespaces'): "name", self.get_default_host_name(client.configuration.host)
namespaces = connection['namespaces'] )
if connection.get("namespaces"):
namespaces = connection["namespaces"]
else: else:
namespaces = self.get_available_namespaces(client) namespaces = self.get_available_namespaces(client)
for namespace in namespaces: for namespace in namespaces:
self.get_routes_for_namespace(client, name, namespace) self.get_routes_for_namespace(client, name, namespace)
else: else:
client = self.get_api_client() client = get_api_client()
name = self.get_default_host_name(client.configuration.host) name = self.get_default_host_name(client.configuration.host)
namespaces = self.get_available_namespaces(client) namespaces = self.get_available_namespaces(client)
for namespace in namespaces: for namespace in namespaces:
self.get_routes_for_namespace(client, name, namespace) self.get_routes_for_namespace(client, name, namespace)
def get_routes_for_namespace(self, client, name, namespace): def get_routes_for_namespace(self, client, name, namespace):
v1_route = client.resources.get(api_version='route.openshift.io/v1', kind='Route') self.check_kubernetes_collection()
v1_route = client.resources.get(
api_version="route.openshift.io/v1", kind="Route"
)
try: try:
obj = v1_route.get(namespace=namespace) obj = v1_route.get(namespace=namespace)
except DynamicApiError as exc: except DynamicApiError as exc:
self.display.debug(exc) self.display.debug(exc)
raise K8sInventoryException('Error fetching Routes list: %s' % format_dynamic_api_exc(exc)) raise K8sInventoryException(
"Error fetching Routes list: %s" % format_dynamic_api_exc(exc)
)
namespace_group = 'namespace_{0}'.format(namespace) namespace_group = "namespace_{0}".format(namespace)
namespace_routes_group = '{0}_routes'.format(namespace_group) namespace_routes_group = "{0}_routes".format(namespace_group)
self.inventory.add_group(name) self.inventory.add_group(name)
self.inventory.add_group(namespace_group) self.inventory.add_group(namespace_group)
@@ -168,14 +207,18 @@ class InventoryModule(K8sInventoryModule):
self.inventory.add_child(namespace_group, namespace_routes_group) self.inventory.add_child(namespace_group, namespace_routes_group)
for route in obj.items: for route in obj.items:
route_name = route.metadata.name route_name = route.metadata.name
route_annotations = {} if not route.metadata.annotations else dict(route.metadata.annotations) route_annotations = (
{}
if not route.metadata.annotations
else dict(route.metadata.annotations)
)
self.inventory.add_host(route_name) self.inventory.add_host(route_name)
if route.metadata.labels: if route.metadata.labels:
# create a group for each label_value # create a group for each label_value
for key, value in route.metadata.labels: for key, value in route.metadata.labels:
group_name = 'label_{0}_{1}'.format(key, value) group_name = "label_{0}_{1}".format(key, value)
self.inventory.add_group(group_name) self.inventory.add_group(group_name)
self.inventory.add_child(group_name, route_name) self.inventory.add_child(group_name, route_name)
route_labels = dict(route.metadata.labels) route_labels = dict(route.metadata.labels)
@@ -185,19 +228,25 @@ class InventoryModule(K8sInventoryModule):
self.inventory.add_child(namespace_routes_group, route_name) self.inventory.add_child(namespace_routes_group, route_name)
# add hostvars # add hostvars
self.inventory.set_variable(route_name, 'labels', route_labels) self.inventory.set_variable(route_name, "labels", route_labels)
self.inventory.set_variable(route_name, 'annotations', route_annotations) self.inventory.set_variable(route_name, "annotations", route_annotations)
self.inventory.set_variable(route_name, 'cluster_name', route.metadata.clusterName) self.inventory.set_variable(
self.inventory.set_variable(route_name, 'object_type', 'route') route_name, "cluster_name", route.metadata.clusterName
self.inventory.set_variable(route_name, 'self_link', route.metadata.selfLink) )
self.inventory.set_variable(route_name, 'resource_version', route.metadata.resourceVersion) self.inventory.set_variable(route_name, "object_type", "route")
self.inventory.set_variable(route_name, 'uid', route.metadata.uid) self.inventory.set_variable(
route_name, "self_link", route.metadata.selfLink
)
self.inventory.set_variable(
route_name, "resource_version", route.metadata.resourceVersion
)
self.inventory.set_variable(route_name, "uid", route.metadata.uid)
if route.spec.host: if route.spec.host:
self.inventory.set_variable(route_name, 'host', route.spec.host) self.inventory.set_variable(route_name, "host", route.spec.host)
if route.spec.path: if route.spec.path:
self.inventory.set_variable(route_name, 'path', route.spec.path) self.inventory.set_variable(route_name, "path", route.spec.path)
if hasattr(route.spec.port, 'targetPort') and route.spec.port.targetPort: if hasattr(route.spec.port, "targetPort") and route.spec.port.targetPort:
self.inventory.set_variable(route_name, 'port', dict(route.spec.port)) self.inventory.set_variable(route_name, "port", dict(route.spec.port))
+321
View File
@@ -0,0 +1,321 @@
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import re
import operator
from functools import reduce
from ansible_collections.community.okd.plugins.module_utils.openshift_common import (
AnsibleOpenshiftModule,
)
try:
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.resource import (
create_definitions,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import (
CoreException,
)
except ImportError:
pass
from ansible.module_utils._text import to_native
try:
from kubernetes.dynamic.exceptions import (
DynamicApiError,
NotFoundError,
ForbiddenError,
)
except ImportError as e:
pass
TRIGGER_ANNOTATION = "image.openshift.io/triggers"
TRIGGER_CONTAINER = re.compile(
r"(?P<path>.*)\[((?P<index>[0-9]+)|\?\(@\.name==[\"'\\]*(?P<name>[a-z0-9]([-a-z0-9]*[a-z0-9])?))"
)
class OKDRawModule(AnsibleOpenshiftModule):
def __init__(self, **kwargs):
super(OKDRawModule, self).__init__(**kwargs)
@property
def module(self):
return self._module
def execute_module(self):
results = []
changed = False
try:
definitions = create_definitions(self.params)
except Exception as e:
msg = "Failed to load resource definition: {0}".format(e)
raise CoreException(msg) from e
for definition in definitions:
result = {"changed": False, "result": {}}
warnings = []
if self.params.get("state") != "absent":
existing = None
name = definition.get("metadata", {}).get("name")
namespace = definition.get("metadata", {}).get("namespace")
if definition.get("kind") in ["Project", "ProjectRequest"]:
try:
resource = self.svc.find_resource(
kind=definition.get("kind"),
api_version=definition.get("apiVersion", "v1"),
)
existing = resource.get(
name=name, namespace=namespace
).to_dict()
except (NotFoundError, ForbiddenError):
result = self.create_project_request(definition)
changed |= result["changed"]
results.append(result)
continue
except DynamicApiError as exc:
self.fail_json(
msg="Failed to retrieve requested object: {0}".format(
exc.body
),
error=exc.status,
status=exc.status,
reason=exc.reason,
)
if definition.get("kind") not in ["Project", "ProjectRequest"]:
try:
resource = self.svc.find_resource(
kind=definition.get("kind"),
api_version=definition.get("apiVersion", "v1"),
)
existing = resource.get(
name=name, namespace=namespace
).to_dict()
except Exception:
existing = None
if existing:
if resource.kind == "DeploymentConfig":
if definition.get("spec", {}).get("triggers"):
definition = self.resolve_imagestream_triggers(
existing, definition
)
elif (
existing["metadata"]
.get("annotations", {})
.get(TRIGGER_ANNOTATION)
):
definition = self.resolve_imagestream_trigger_annotation(
existing, definition
)
if self.params.get("validate") is not None:
warnings = self.validate(definition)
try:
result = self.perform_action(definition, self.params)
except Exception as e:
try:
error = e.result
except AttributeError:
error = {}
try:
error["reason"] = e.__cause__.reason
except AttributeError:
pass
error["msg"] = to_native(e)
if warnings:
error.setdefault("warnings", []).extend(warnings)
if self.params.get("continue_on_error"):
result["error"] = error
else:
self.fail_json(**error)
if warnings:
result.setdefault("warnings", []).extend(warnings)
changed |= result["changed"]
results.append(result)
if len(results) == 1:
self.exit_json(**results[0])
self.exit_json(**{"changed": changed, "result": {"results": results}})
@staticmethod
def get_index(desired, objects, keys):
"""Iterates over keys, returns the first object from objects where the value of the key
matches the value in desired
"""
# pylint: disable=use-a-generator
# Use a generator instead 'all(desired.get(key, True) == item.get(key, False) for key in keys)'
for i, item in enumerate(objects):
if item and all(
[desired.get(key, True) == item.get(key, False) for key in keys]
):
return i
def resolve_imagestream_trigger_annotation(self, existing, definition):
import yaml
def get_from_fields(d, fields):
try:
return reduce(operator.getitem, fields, d)
except Exception:
return None
def set_from_fields(d, fields, value):
get_from_fields(d, fields[:-1])[fields[-1]] = value
if TRIGGER_ANNOTATION in definition["metadata"].get("annotations", {}).keys():
triggers = yaml.safe_load(
definition["metadata"]["annotations"][TRIGGER_ANNOTATION] or "[]"
)
else:
triggers = yaml.safe_load(
existing["metadata"]
.get("annotations", "{}")
.get(TRIGGER_ANNOTATION, "[]")
)
if not isinstance(triggers, list):
return definition
for trigger in triggers:
if trigger.get("fieldPath"):
parsed = self.parse_trigger_fieldpath(trigger["fieldPath"])
path = parsed.get("path", "").split(".")
if path:
existing_containers = get_from_fields(existing, path)
new_containers = get_from_fields(definition, path)
if parsed.get("name"):
existing_index = self.get_index(
{"name": parsed["name"]}, existing_containers, ["name"]
)
new_index = self.get_index(
{"name": parsed["name"]}, new_containers, ["name"]
)
elif parsed.get("index") is not None:
existing_index = new_index = int(parsed["index"])
else:
existing_index = new_index = None
if existing_index is not None and new_index is not None:
if existing_index < len(
existing_containers
) and new_index < len(new_containers):
set_from_fields(
definition,
path + [new_index, "image"],
get_from_fields(
existing, path + [existing_index, "image"]
),
)
return definition
def resolve_imagestream_triggers(self, existing, definition):
existing_triggers = existing.get("spec", {}).get("triggers")
new_triggers = definition["spec"]["triggers"]
existing_containers = (
existing.get("spec", {})
.get("template", {})
.get("spec", {})
.get("containers", [])
)
new_containers = (
definition.get("spec", {})
.get("template", {})
.get("spec", {})
.get("containers", [])
)
for i, trigger in enumerate(new_triggers):
if trigger.get("type") == "ImageChange" and trigger.get(
"imageChangeParams"
):
names = trigger["imageChangeParams"].get("containerNames", [])
for name in names:
old_container_index = self.get_index(
{"name": name}, existing_containers, ["name"]
)
new_container_index = self.get_index(
{"name": name}, new_containers, ["name"]
)
if (
old_container_index is not None
and new_container_index is not None
):
image = existing["spec"]["template"]["spec"]["containers"][
old_container_index
]["image"]
definition["spec"]["template"]["spec"]["containers"][
new_container_index
]["image"] = image
existing_index = self.get_index(
trigger["imageChangeParams"],
[x.get("imageChangeParams") for x in existing_triggers],
["containerNames"],
)
if existing_index is not None:
existing_image = (
existing_triggers[existing_index]
.get("imageChangeParams", {})
.get("lastTriggeredImage")
)
if existing_image:
definition["spec"]["triggers"][i]["imageChangeParams"][
"lastTriggeredImage"
] = existing_image
existing_from = (
existing_triggers[existing_index]
.get("imageChangeParams", {})
.get("from", {})
)
new_from = trigger["imageChangeParams"].get("from", {})
existing_namespace = existing_from.get("namespace")
existing_name = existing_from.get("name", False)
new_name = new_from.get("name", True)
add_namespace = (
existing_namespace
and "namespace" not in new_from.keys()
and existing_name == new_name
)
if add_namespace:
definition["spec"]["triggers"][i]["imageChangeParams"][
"from"
]["namespace"] = existing_from["namespace"]
return definition
def parse_trigger_fieldpath(self, expression):
parsed = TRIGGER_CONTAINER.search(expression).groupdict()
if parsed.get("index"):
parsed["index"] = int(parsed["index"])
return parsed
def create_project_request(self, definition):
definition["kind"] = "ProjectRequest"
result = {"changed": False, "result": {}}
resource = self.svc.find_resource(
kind="ProjectRequest", api_version=definition["apiVersion"], fail=True
)
if not self.check_mode:
try:
k8s_obj = resource.create(definition)
result["result"] = k8s_obj.to_dict()
except DynamicApiError as exc:
self.fail_json(
msg="Failed to create object: {0}".format(exc.body),
error=exc.status,
status=exc.status,
reason=exc.reason,
)
result["changed"] = True
result["method"] = "create"
return result
@@ -0,0 +1,380 @@
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils._text import to_native
from ansible_collections.community.okd.plugins.module_utils.openshift_common import (
AnsibleOpenshiftModule,
)
try:
from kubernetes import client
from kubernetes.dynamic.exceptions import DynamicApiError, NotFoundError
except ImportError:
pass
class OpenShiftAdmPruneAuth(AnsibleOpenshiftModule):
def __init__(self, **kwargs):
super(OpenShiftAdmPruneAuth, self).__init__(**kwargs)
def prune_resource_binding(
self, kind, api_version, ref_kind, ref_namespace_names, propagation_policy=None
):
resource = self.find_resource(kind=kind, api_version=api_version, fail=True)
candidates = []
for ref_namespace, ref_name in ref_namespace_names:
try:
result = resource.get(name=None, namespace=ref_namespace)
result = result.to_dict()
result = result.get("items") if "items" in result else [result]
for obj in result:
namespace = obj["metadata"].get("namespace", None)
name = obj["metadata"].get("name")
if ref_kind and obj["roleRef"]["kind"] != ref_kind:
# skip this binding as the roleRef.kind does not match
continue
if obj["roleRef"]["name"] == ref_name:
# select this binding as the roleRef.name match
candidates.append((namespace, name))
except NotFoundError:
continue
except DynamicApiError as exc:
msg = "Failed to get {kind} resource due to: {msg}".format(
kind=kind, msg=exc.body
)
self.fail_json(msg=msg)
except Exception as e:
msg = "Failed to get {kind} due to: {msg}".format(
kind=kind, msg=to_native(e)
)
self.fail_json(msg=msg)
if len(candidates) == 0 or self.check_mode:
return [y if x is None else x + "/" + y for x, y in candidates]
delete_options = client.V1DeleteOptions()
if propagation_policy:
delete_options.propagation_policy = propagation_policy
for namespace, name in candidates:
try:
result = resource.delete(
name=name, namespace=namespace, body=delete_options
)
except DynamicApiError as exc:
msg = "Failed to delete {kind} {namespace}/{name} due to: {msg}".format(
kind=kind, namespace=namespace, name=name, msg=exc.body
)
self.fail_json(msg=msg)
except Exception as e:
msg = "Failed to delete {kind} {namespace}/{name} due to: {msg}".format(
kind=kind, namespace=namespace, name=name, msg=to_native(e)
)
self.fail_json(msg=msg)
return [y if x is None else x + "/" + y for x, y in candidates]
def update_resource_binding(self, ref_kind, ref_names, namespaced=False):
kind = "ClusterRoleBinding"
api_version = "rbac.authorization.k8s.io/v1"
if namespaced:
kind = "RoleBinding"
resource = self.find_resource(kind=kind, api_version=api_version, fail=True)
result = resource.get(name=None, namespace=None).to_dict()
result = result.get("items") if "items" in result else [result]
if len(result) == 0:
return [], False
def _update_user_group(binding_namespace, subjects):
users, groups = [], []
for x in subjects:
if x["kind"] == "User":
users.append(x["name"])
elif x["kind"] == "Group":
groups.append(x["name"])
elif x["kind"] == "ServiceAccount":
namespace = binding_namespace
if x.get("namespace") is not None:
namespace = x.get("namespace")
if namespace is not None:
users.append(
"system:serviceaccount:%s:%s" % (namespace, x["name"])
)
return users, groups
candidates = []
changed = False
for item in result:
subjects = item.get("subjects", [])
retainedSubjects = [
x for x in subjects if x["kind"] == ref_kind and x["name"] in ref_names
]
if len(subjects) != len(retainedSubjects):
updated_binding = item
updated_binding["subjects"] = retainedSubjects
binding_namespace = item["metadata"].get("namespace", None)
(
updated_binding["userNames"],
updated_binding["groupNames"],
) = _update_user_group(binding_namespace, retainedSubjects)
candidates.append(
binding_namespace + "/" + item["metadata"]["name"]
if binding_namespace
else item["metadata"]["name"]
)
changed = True
if not self.check_mode:
try:
resource.apply(updated_binding, namespace=binding_namespace)
except DynamicApiError as exc:
msg = "Failed to apply object due to: {0}".format(exc.body)
self.fail_json(msg=msg)
return candidates, changed
def update_security_context(self, ref_names, key):
params = {
"kind": "SecurityContextConstraints",
"api_version": "security.openshift.io/v1",
}
sccs = self.kubernetes_facts(**params)
if not sccs["api_found"]:
self.fail_json(msg=sccs["msg"])
sccs = sccs.get("resources")
candidates = []
changed = False
resource = self.find_resource(
kind="SecurityContextConstraints", api_version="security.openshift.io/v1"
)
for item in sccs:
subjects = item.get(key, [])
retainedSubjects = [x for x in subjects if x not in ref_names]
if len(subjects) != len(retainedSubjects):
candidates.append(item["metadata"]["name"])
changed = True
if not self.check_mode:
upd_sec_ctx = item
upd_sec_ctx.update({key: retainedSubjects})
try:
resource.apply(upd_sec_ctx, namespace=None)
except DynamicApiError as exc:
msg = "Failed to apply object due to: {0}".format(exc.body)
self.fail_json(msg=msg)
return candidates, changed
def auth_prune_roles(self):
params = {
"kind": "Role",
"api_version": "rbac.authorization.k8s.io/v1",
"namespace": self.params.get("namespace"),
}
for attr in ("name", "label_selectors"):
if self.params.get(attr):
params[attr] = self.params.get(attr)
result = self.kubernetes_facts(**params)
if not result["api_found"]:
self.fail_json(msg=result["msg"])
roles = result.get("resources")
if len(roles) == 0:
self.exit_json(
changed=False,
msg="No candidate rolebinding to prune from namespace %s."
% self.params.get("namespace"),
)
ref_roles = [(x["metadata"]["namespace"], x["metadata"]["name"]) for x in roles]
candidates = self.prune_resource_binding(
kind="RoleBinding",
api_version="rbac.authorization.k8s.io/v1",
ref_kind="Role",
ref_namespace_names=ref_roles,
propagation_policy="Foreground",
)
if len(candidates) == 0:
self.exit_json(changed=False, role_binding=candidates)
self.exit_json(changed=True, role_binding=candidates)
def auth_prune_clusterroles(self):
params = {"kind": "ClusterRole", "api_version": "rbac.authorization.k8s.io/v1"}
for attr in ("name", "label_selectors"):
if self.params.get(attr):
params[attr] = self.params.get(attr)
result = self.kubernetes_facts(**params)
if not result["api_found"]:
self.fail_json(msg=result["msg"])
clusterroles = result.get("resources")
if len(clusterroles) == 0:
self.exit_json(
changed=False, msg="No clusterroles found matching input criteria."
)
ref_clusterroles = [(None, x["metadata"]["name"]) for x in clusterroles]
# Prune ClusterRoleBinding
candidates_cluster_binding = self.prune_resource_binding(
kind="ClusterRoleBinding",
api_version="rbac.authorization.k8s.io/v1",
ref_kind=None,
ref_namespace_names=ref_clusterroles,
)
# Prune Role Binding
candidates_namespaced_binding = self.prune_resource_binding(
kind="RoleBinding",
api_version="rbac.authorization.k8s.io/v1",
ref_kind="ClusterRole",
ref_namespace_names=ref_clusterroles,
)
self.exit_json(
changed=True,
cluster_role_binding=candidates_cluster_binding,
role_binding=candidates_namespaced_binding,
)
def list_groups(self, params=None):
options = {"kind": "Group", "api_version": "user.openshift.io/v1"}
if params:
for attr in ("name", "label_selectors"):
if params.get(attr):
options[attr] = params.get(attr)
return self.kubernetes_facts(**options)
def auth_prune_users(self):
params = {"kind": "User", "api_version": "user.openshift.io/v1"}
for attr in ("name", "label_selectors"):
if self.params.get(attr):
params[attr] = self.params.get(attr)
users = self.kubernetes_facts(**params)
if len(users) == 0:
self.exit_json(
changed=False,
msg="No resource type 'User' found matching input criteria.",
)
names = [x["metadata"]["name"] for x in users]
changed = False
# Remove the user role binding
rolebinding, changed_role = self.update_resource_binding(
ref_kind="User", ref_names=names, namespaced=True
)
changed = changed or changed_role
# Remove the user cluster role binding
clusterrolesbinding, changed_cr = self.update_resource_binding(
ref_kind="User", ref_names=names
)
changed = changed or changed_cr
# Remove the user from security context constraints
sccs, changed_sccs = self.update_security_context(names, "users")
changed = changed or changed_sccs
# Remove the user from groups
groups = self.list_groups()
deleted_groups = []
resource = self.find_resource(kind="Group", api_version="user.openshift.io/v1")
for grp in groups:
subjects = grp.get("users", [])
retainedSubjects = [x for x in subjects if x not in names]
if len(subjects) != len(retainedSubjects):
deleted_groups.append(grp["metadata"]["name"])
changed = True
if not self.check_mode:
upd_group = grp
upd_group.update({"users": retainedSubjects})
try:
resource.apply(upd_group, namespace=None)
except DynamicApiError as exc:
msg = "Failed to apply object due to: {0}".format(exc.body)
self.fail_json(msg=msg)
# Remove the user's OAuthClientAuthorizations
oauth = self.kubernetes_facts(
kind="OAuthClientAuthorization", api_version="oauth.openshift.io/v1"
)
deleted_auths = []
resource = self.find_resource(
kind="OAuthClientAuthorization", api_version="oauth.openshift.io/v1"
)
for authorization in oauth:
if authorization.get("userName", None) in names:
auth_name = authorization["metadata"]["name"]
deleted_auths.append(auth_name)
changed = True
if not self.check_mode:
try:
resource.delete(
name=auth_name,
namespace=None,
body=client.V1DeleteOptions(),
)
except DynamicApiError as exc:
msg = "Failed to delete OAuthClientAuthorization {name} due to: {msg}".format(
name=auth_name, msg=exc.body
)
self.fail_json(msg=msg)
except Exception as e:
msg = "Failed to delete OAuthClientAuthorization {name} due to: {msg}".format(
name=auth_name, msg=to_native(e)
)
self.fail_json(msg=msg)
self.exit_json(
changed=changed,
cluster_role_binding=clusterrolesbinding,
role_binding=rolebinding,
security_context_constraints=sccs,
authorization=deleted_auths,
group=deleted_groups,
)
def auth_prune_groups(self):
groups = self.list_groups(params=self.params)
if len(groups) == 0:
self.exit_json(
changed=False,
result="No resource type 'Group' found matching input criteria.",
)
names = [x["metadata"]["name"] for x in groups]
changed = False
# Remove the groups role binding
rolebinding, changed_role = self.update_resource_binding(
ref_kind="Group", ref_names=names, namespaced=True
)
changed = changed or changed_role
# Remove the groups cluster role binding
clusterrolesbinding, changed_cr = self.update_resource_binding(
ref_kind="Group", ref_names=names
)
changed = changed or changed_cr
# Remove the groups security context constraints
sccs, changed_sccs = self.update_security_context(names, "groups")
changed = changed or changed_sccs
self.exit_json(
changed=changed,
cluster_role_binding=clusterrolesbinding,
role_binding=rolebinding,
security_context_constraints=sccs,
)
def execute_module(self):
auth_prune = {
"roles": self.auth_prune_roles,
"clusterroles": self.auth_prune_clusterroles,
"users": self.auth_prune_users,
"groups": self.auth_prune_groups,
}
auth_prune[self.params.get("resource")]()
@@ -0,0 +1,137 @@
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from datetime import datetime, timezone
from ansible.module_utils._text import to_native
from ansible_collections.community.okd.plugins.module_utils.openshift_common import (
AnsibleOpenshiftModule,
)
try:
from kubernetes import client
from kubernetes.dynamic.exceptions import DynamicApiError
except ImportError as e:
pass
def get_deploymentconfig_for_replicationcontroller(replica_controller):
# DeploymentConfigAnnotation is an annotation name used to correlate a deployment with the
# DeploymentConfig on which the deployment is based.
# This is set on replication controller pod template by deployer controller.
DeploymentConfigAnnotation = "openshift.io/deployment-config.name"
try:
deploymentconfig_name = replica_controller["metadata"]["annotations"].get(
DeploymentConfigAnnotation
)
if deploymentconfig_name is None or deploymentconfig_name == "":
return None
return deploymentconfig_name
except Exception:
return None
class OpenShiftAdmPruneDeployment(AnsibleOpenshiftModule):
def __init__(self, **kwargs):
super(OpenShiftAdmPruneDeployment, self).__init__(**kwargs)
def filter_replication_controller(self, replicacontrollers):
def _deployment(obj):
return get_deploymentconfig_for_replicationcontroller(obj) is not None
def _zeroReplicaSize(obj):
return obj["spec"]["replicas"] == 0 and obj["status"]["replicas"] == 0
def _complete_failed(obj):
DeploymentStatusAnnotation = "openshift.io/deployment.phase"
try:
# validate that replication controller status is either 'Complete' or 'Failed'
deployment_phase = obj["metadata"]["annotations"].get(
DeploymentStatusAnnotation
)
return deployment_phase in ("Failed", "Complete")
except Exception:
return False
def _younger(obj):
creation_timestamp = datetime.strptime(
obj["metadata"]["creationTimestamp"], "%Y-%m-%dT%H:%M:%SZ"
)
now = datetime.now(timezone.utc).replace(tzinfo=None)
age = (now - creation_timestamp).seconds / 60
return age > self.params["keep_younger_than"]
def _orphan(obj):
try:
# verify if the deploymentconfig associated to the replication controller is still existing
deploymentconfig_name = get_deploymentconfig_for_replicationcontroller(
obj
)
params = dict(
kind="DeploymentConfig",
api_version="apps.openshift.io/v1",
name=deploymentconfig_name,
namespace=obj["metadata"]["name"],
)
exists = self.kubernetes_facts(**params)
return not (exists.get["api_found"] and len(exists["resources"]) > 0)
except Exception:
return False
predicates = [_deployment, _zeroReplicaSize, _complete_failed]
if self.params["orphans"]:
predicates.append(_orphan)
if self.params["keep_younger_than"]:
predicates.append(_younger)
results = replicacontrollers.copy()
for pred in predicates:
results = filter(pred, results)
return list(results)
def execute_module(self):
# list replicationcontroller candidate for pruning
kind = "ReplicationController"
api_version = "v1"
resource = self.find_resource(kind=kind, api_version=api_version, fail=True)
# Get ReplicationController
params = dict(
kind=kind,
api_version="v1",
namespace=self.params.get("namespace"),
)
candidates = self.kubernetes_facts(**params)
candidates = self.filter_replication_controller(candidates["resources"])
if len(candidates) == 0:
self.exit_json(changed=False, replication_controllers=[])
changed = True
delete_options = client.V1DeleteOptions(propagation_policy="Background")
replication_controllers = []
for replica in candidates:
try:
result = replica
if not self.check_mode:
name = replica["metadata"]["name"]
namespace = replica["metadata"]["namespace"]
result = resource.delete(
name=name, namespace=namespace, body=delete_options
).to_dict()
replication_controllers.append(result)
except DynamicApiError as exc:
msg = "Failed to delete ReplicationController {namespace}/{name} due to: {msg}".format(
namespace=namespace, name=name, msg=exc.body
)
self.fail_json(msg=msg)
except Exception as e:
msg = "Failed to delete ReplicationController {namespace}/{name} due to: {msg}".format(
namespace=namespace, name=name, msg=to_native(e)
)
self.fail_json(msg=msg)
self.exit_json(changed=changed, replication_controllers=replication_controllers)
@@ -0,0 +1,495 @@
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from datetime import datetime, timezone, timedelta
import copy
from ansible.module_utils._text import to_native
from ansible.module_utils.parsing.convert_bool import boolean
from ansible.module_utils.six import iteritems
from ansible_collections.community.okd.plugins.module_utils.openshift_common import (
AnsibleOpenshiftModule,
)
from ansible_collections.community.okd.plugins.module_utils.openshift_images_common import (
OpenShiftAnalyzeImageStream,
get_image_blobs,
is_too_young_object,
is_created_after,
)
from ansible_collections.community.okd.plugins.module_utils.openshift_docker_image import (
parse_docker_image_ref,
convert_storage_to_bytes,
)
try:
from kubernetes import client
from kubernetes.client import rest
from kubernetes.dynamic.exceptions import (
DynamicApiError,
NotFoundError,
ApiException,
)
except ImportError:
pass
ApiConfiguration = {
"LimitRange": "v1",
"Pod": "v1",
"ReplicationController": "v1",
"DaemonSet": "apps/v1",
"Deployment": "apps/v1",
"ReplicaSet": "apps/v1",
"StatefulSet": "apps/v1",
"Job": "batch/v1",
"CronJob": "batch/v1beta1",
"DeploymentConfig": "apps.openshift.io/v1",
"BuildConfig": "build.openshift.io/v1",
"Build": "build.openshift.io/v1",
"Image": "image.openshift.io/v1",
"ImageStream": "image.openshift.io/v1",
}
def read_object_annotation(obj, name):
return obj["metadata"]["annotations"].get(name)
def determine_host_registry(module, images, image_streams):
# filter managed images
def _f_managed_images(obj):
value = read_object_annotation(obj, "openshift.io/image.managed")
return boolean(value) if value is not None else False
managed_images = list(filter(_f_managed_images, images))
# Be sure to pick up the newest managed image which should have an up to date information
sorted_images = sorted(
managed_images, key=lambda x: x["metadata"]["creationTimestamp"], reverse=True
)
docker_image_ref = ""
if len(sorted_images) > 0:
docker_image_ref = sorted_images[0].get("dockerImageReference", "")
else:
# 2nd try to get the pull spec from any image stream
# Sorting by creation timestamp may not get us up to date info. Modification time would be much
sorted_image_streams = sorted(
image_streams,
key=lambda x: x["metadata"]["creationTimestamp"],
reverse=True,
)
for i_stream in sorted_image_streams:
docker_image_ref = i_stream["status"].get("dockerImageRepository", "")
if len(docker_image_ref) > 0:
break
if len(docker_image_ref) == 0:
module.exit_json(changed=False, result="no managed image found")
result, error = parse_docker_image_ref(docker_image_ref, module)
return result["hostname"]
class OpenShiftAdmPruneImages(AnsibleOpenshiftModule):
def __init__(self, **kwargs):
super(OpenShiftAdmPruneImages, self).__init__(**kwargs)
self.max_creation_timestamp = self.get_max_creation_timestamp()
self._rest_client = None
self.registryhost = self.params.get("registry_url")
self.changed = False
def list_objects(self):
result = {}
for kind, version in iteritems(ApiConfiguration):
namespace = None
if self.params.get("namespace") and kind.lower() == "imagestream":
namespace = self.params.get("namespace")
try:
result[kind] = self.kubernetes_facts(
kind=kind, api_version=version, namespace=namespace
).get("resources")
except DynamicApiError as e:
self.fail_json(
msg="An error occurred while trying to list objects.",
reason=e.reason,
status=e.status,
)
except Exception as e:
self.fail_json(
msg="An error occurred while trying to list objects.",
error=to_native(e),
)
return result
def get_max_creation_timestamp(self):
result = None
if self.params.get("keep_younger_than"):
dt_now = datetime.now(timezone.utc).replace(tzinfo=None)
result = dt_now - timedelta(minutes=self.params.get("keep_younger_than"))
return result
@property
def rest_client(self):
if not self._rest_client:
configuration = copy.deepcopy(self.client.configuration)
validate_certs = self.params.get("registry_validate_certs")
ssl_ca_cert = self.params.get("registry_ca_cert")
if validate_certs is not None:
configuration.verify_ssl = validate_certs
if ssl_ca_cert is not None:
configuration.ssl_ca_cert = ssl_ca_cert
self._rest_client = rest.RESTClientObject(configuration)
return self._rest_client
def delete_from_registry(self, url):
try:
response = self.rest_client.DELETE(
url=url, headers=self.client.configuration.api_key
)
if response.status == 404:
# Unable to delete layer
return None
# non-2xx/3xx response doesn't cause an error
if response.status < 200 or response.status >= 400:
return None
if response.status != 202 and response.status != 204:
self.fail_json(
msg="Delete URL {0}: Unexpected status code in response: {1}".format(
response.status, url
),
reason=response.reason,
)
return None
except ApiException as e:
if e.status != 404:
self.fail_json(
msg="Failed to delete URL: %s" % url,
reason=e.reason,
status=e.status,
)
except Exception as e:
self.fail_json(msg="Delete URL {0}: {1}".format(url, type(e)))
def delete_layers_links(self, path, layers):
for layer in layers:
url = "%s/v2/%s/blobs/%s" % (self.registryhost, path, layer)
self.changed = True
if not self.check_mode:
self.delete_from_registry(url=url)
def delete_manifests(self, path, digests):
for digest in digests:
url = "%s/v2/%s/manifests/%s" % (self.registryhost, path, digest)
self.changed = True
if not self.check_mode:
self.delete_from_registry(url=url)
def delete_blobs(self, blobs):
for blob in blobs:
self.changed = True
url = "%s/admin/blobs/%s" % (self.registryhost, blob)
if not self.check_mode:
self.delete_from_registry(url=url)
def update_image_stream_status(self, definition):
kind = definition["kind"]
api_version = definition["apiVersion"]
namespace = definition["metadata"]["namespace"]
name = definition["metadata"]["name"]
self.changed = True
result = definition
if not self.check_mode:
try:
result = self.request(
"PUT",
"/apis/{api_version}/namespaces/{namespace}/imagestreams/{name}/status".format(
api_version=api_version, namespace=namespace, name=name
),
body=definition,
content_type="application/json",
).to_dict()
except DynamicApiError as exc:
msg = "Failed to patch object: kind={0} {1}/{2}".format(
kind, namespace, name
)
self.fail_json(msg=msg, status=exc.status, reason=exc.reason)
except Exception as exc:
msg = "Failed to patch object kind={0} {1}/{2} due to: {3}".format(
kind, namespace, name, exc
)
self.fail_json(msg=msg, error=to_native(exc))
return result
def delete_image(self, image):
kind = "Image"
api_version = "image.openshift.io/v1"
resource = self.find_resource(kind=kind, api_version=api_version)
name = image["metadata"]["name"]
self.changed = True
if not self.check_mode:
try:
delete_options = client.V1DeleteOptions(grace_period_seconds=0)
return resource.delete(name=name, body=delete_options).to_dict()
except NotFoundError:
pass
except DynamicApiError as exc:
self.fail_json(
msg="Failed to delete object %s/%s due to: %s"
% (kind, name, exc.body),
reason=exc.reason,
status=exc.status,
)
else:
existing = resource.get(name=name)
if existing:
existing = existing.to_dict()
return existing
def exceeds_limits(self, namespace, image):
if namespace not in self.limit_range:
return False
docker_image_metadata = image.get("dockerImageMetadata")
if not docker_image_metadata:
return False
docker_image_size = docker_image_metadata["Size"]
for limit in self.limit_range.get(namespace):
for item in limit["spec"]["limits"]:
if item["type"] != "openshift.io/Image":
continue
limit_max = item["max"]
if not limit_max:
continue
storage = limit_max["storage"]
if not storage:
continue
if convert_storage_to_bytes(storage) < docker_image_size:
# image size is larger than the permitted limit range max size
return True
return False
def prune_image_stream_tag(self, stream, tag_event_list):
manifests_to_delete, images_to_delete = [], []
filtered_items = []
tag_event_items = tag_event_list["items"] or []
prune_over_size_limit = self.params.get("prune_over_size_limit")
stream_namespace = stream["metadata"]["namespace"]
stream_name = stream["metadata"]["name"]
for idx, item in enumerate(tag_event_items):
if is_created_after(item["created"], self.max_creation_timestamp):
filtered_items.append(item)
continue
if idx == 0:
istag = "%s/%s:%s" % (
stream_namespace,
stream_name,
tag_event_list["tag"],
)
if istag in self.used_tags:
# keeping because tag is used
filtered_items.append(item)
continue
if item["image"] not in self.image_mapping:
# There are few options why the image may not be found:
# 1. the image is deleted manually and this record is no longer valid
# 2. the imagestream was observed before the image creation, i.e.
# this record was created recently and it should be protected by keep_younger_than
continue
image = self.image_mapping[item["image"]]
# check prune over limit size
if prune_over_size_limit and not self.exceeds_limits(
stream_namespace, image
):
filtered_items.append(item)
continue
image_ref = "%s/%s@%s" % (stream_namespace, stream_name, item["image"])
if image_ref in self.used_images:
# keeping because tag is used
filtered_items.append(item)
continue
images_to_delete.append(item["image"])
if self.params.get("prune_registry"):
manifests_to_delete.append(image["metadata"]["name"])
path = stream_namespace + "/" + stream_name
image_blobs, err = get_image_blobs(image)
if not err:
self.delete_layers_links(path, image_blobs)
return filtered_items, manifests_to_delete, images_to_delete
def prune_image_streams(self, stream):
name = stream["metadata"]["namespace"] + "/" + stream["metadata"]["name"]
if is_too_young_object(stream, self.max_creation_timestamp):
# keeping all images because of image stream too young
return None, []
facts = self.kubernetes_facts(
kind="ImageStream",
api_version=ApiConfiguration.get("ImageStream"),
name=stream["metadata"]["name"],
namespace=stream["metadata"]["namespace"],
)
image_stream = facts.get("resources")
if len(image_stream) != 1:
# skipping because it does not exist anymore
return None, []
stream = image_stream[0]
namespace = self.params.get("namespace")
stream_to_update = not namespace or (
stream["metadata"]["namespace"] == namespace
)
manifests_to_delete, images_to_delete = [], []
deleted_items = False
# Update Image stream tag
if stream_to_update:
tags = stream["status"].get("tags", [])
for idx, tag_event_list in enumerate(tags):
(
filtered_tag_event,
tag_manifests_to_delete,
tag_images_to_delete,
) = self.prune_image_stream_tag(stream, tag_event_list)
stream["status"]["tags"][idx]["items"] = filtered_tag_event
manifests_to_delete += tag_manifests_to_delete
images_to_delete += tag_images_to_delete
deleted_items = deleted_items or (len(tag_images_to_delete) > 0)
# Deleting tags without items
tags = []
for tag in stream["status"].get("tags", []):
if tag["items"] is None or len(tag["items"]) == 0:
continue
tags.append(tag)
stream["status"]["tags"] = tags
result = None
# Update ImageStream
if stream_to_update:
if deleted_items:
result = self.update_image_stream_status(stream)
if self.params.get("prune_registry"):
self.delete_manifests(name, manifests_to_delete)
return result, images_to_delete
def prune_images(self, image):
if not self.params.get("all_images"):
if read_object_annotation(image, "openshift.io/image.managed") != "true":
# keeping external image because all_images is set to false
# pruning only managed images
return None
if is_too_young_object(image, self.max_creation_timestamp):
# keeping because of keep_younger_than
return None
# Deleting image from registry
if self.params.get("prune_registry"):
image_blobs, err = get_image_blobs(image)
if err:
self.fail_json(msg=err)
# add blob for image name
image_blobs.append(image["metadata"]["name"])
self.delete_blobs(image_blobs)
# Delete image from cluster
return self.delete_image(image)
def execute_module(self):
resources = self.list_objects()
if not self.check_mode and self.params.get("prune_registry"):
if not self.registryhost:
self.registryhost = determine_host_registry(
self.module, resources["Image"], resources["ImageStream"]
)
# validate that host has a scheme
if "://" not in self.registryhost:
self.registryhost = "https://" + self.registryhost
# Analyze Image Streams
analyze_ref = OpenShiftAnalyzeImageStream(
ignore_invalid_refs=self.params.get("ignore_invalid_refs"),
max_creation_timestamp=self.max_creation_timestamp,
module=self.module,
)
self.used_tags, self.used_images, error = analyze_ref.analyze_image_stream(
resources
)
if error:
self.fail_json(msg=error)
# Create image mapping
self.image_mapping = {}
for m in resources["Image"]:
self.image_mapping[m["metadata"]["name"]] = m
# Create limit range mapping
self.limit_range = {}
for limit in resources["LimitRange"]:
namespace = limit["metadata"]["namespace"]
if namespace not in self.limit_range:
self.limit_range[namespace] = []
self.limit_range[namespace].append(limit)
# Stage 1: delete history from image streams
updated_image_streams = []
deleted_tags_images = []
updated_is_mapping = {}
for stream in resources["ImageStream"]:
result, images_to_delete = self.prune_image_streams(stream)
if result:
updated_is_mapping[
result["metadata"]["namespace"] + "/" + result["metadata"]["name"]
] = result
updated_image_streams.append(result)
deleted_tags_images += images_to_delete
# Create a list with images referenced on image stream
self.referenced_images = []
for item in self.kubernetes_facts(
kind="ImageStream", api_version="image.openshift.io/v1"
)["resources"]:
name = "%s/%s" % (item["metadata"]["namespace"], item["metadata"]["name"])
if name in updated_is_mapping:
item = updated_is_mapping[name]
for tag in item["status"].get("tags", []):
self.referenced_images += [t["image"] for t in tag["items"] or []]
# Stage 2: delete images
images = []
images_to_delete = [x["metadata"]["name"] for x in resources["Image"]]
if self.params.get("namespace") is not None:
# When namespace is defined, prune only images that were referenced by ImageStream
# from the corresponding namespace
images_to_delete = deleted_tags_images
for name in images_to_delete:
if name in self.referenced_images:
# The image is referenced in one or more Image stream
continue
if name not in self.image_mapping:
# The image is not existing anymore
continue
result = self.prune_images(self.image_mapping[name])
if result:
images.append(result)
result = {
"changed": self.changed,
"deleted_images": images,
"updated_image_streams": updated_image_streams,
}
self.exit_json(**result)
+424
View File
@@ -0,0 +1,424 @@
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from datetime import datetime, timezone, timedelta
import time
from ansible.module_utils._text import to_native
from ansible_collections.community.okd.plugins.module_utils.openshift_common import (
AnsibleOpenshiftModule,
)
try:
from kubernetes.dynamic.exceptions import DynamicApiError
except ImportError as e:
pass
class OpenShiftBuilds(AnsibleOpenshiftModule):
def __init__(self, **kwargs):
super(OpenShiftBuilds, self).__init__(**kwargs)
def get_build_config(self, name, namespace):
params = dict(
kind="BuildConfig",
api_version="build.openshift.io/v1",
name=name,
namespace=namespace,
)
result = self.kubernetes_facts(**params)
return result["resources"]
def clone_build(self, name, namespace, request):
try:
result = self.request(
method="POST",
path="/apis/build.openshift.io/v1/namespaces/{namespace}/builds/{name}/clone".format(
namespace=namespace, name=name
),
body=request,
content_type="application/json",
)
return result.to_dict()
except DynamicApiError as exc:
msg = "Failed to clone Build %s/%s due to: %s" % (namespace, name, exc.body)
self.fail_json(msg=msg, status=exc.status, reason=exc.reason)
except Exception as e:
msg = "Failed to clone Build %s/%s due to: %s" % (
namespace,
name,
to_native(e),
)
self.fail_json(msg=msg, error=to_native(e), exception=e)
def instantiate_build_config(self, name, namespace, request):
try:
result = self.request(
method="POST",
path="/apis/build.openshift.io/v1/namespaces/{namespace}/buildconfigs/{name}/instantiate".format(
namespace=namespace, name=name
),
body=request,
content_type="application/json",
)
return result.to_dict()
except DynamicApiError as exc:
msg = "Failed to instantiate BuildConfig %s/%s due to: %s" % (
namespace,
name,
exc.body,
)
self.fail_json(msg=msg, status=exc.status, reason=exc.reason)
except Exception as e:
msg = "Failed to instantiate BuildConfig %s/%s due to: %s" % (
namespace,
name,
to_native(e),
)
self.fail_json(msg=msg, error=to_native(e), exception=e)
def start_build(self):
result = None
name = self.params.get("build_config_name")
if not name:
name = self.params.get("build_name")
build_request = {
"kind": "BuildRequest",
"apiVersion": "build.openshift.io/v1",
"metadata": {"name": name},
"triggeredBy": [{"message": "Manually triggered"}],
}
# Overrides incremental
incremental = self.params.get("incremental")
if incremental is not None:
build_request.update(
{"sourceStrategyOptions": {"incremental": incremental}}
)
# Environment variable
if self.params.get("env_vars"):
build_request.update({"env": self.params.get("env_vars")})
# Docker strategy option
if self.params.get("build_args"):
build_request.update(
{
"dockerStrategyOptions": {
"buildArgs": self.params.get("build_args")
},
}
)
# caching option
no_cache = self.params.get("no_cache")
if no_cache is not None:
build_request.update(
{
"dockerStrategyOptions": {"noCache": no_cache},
}
)
# commit
if self.params.get("commit"):
build_request.update(
{"revision": {"git": {"commit": self.params.get("commit")}}}
)
if self.params.get("build_config_name"):
# Instantiate Build from Build config
result = self.instantiate_build_config(
name=self.params.get("build_config_name"),
namespace=self.params.get("namespace"),
request=build_request,
)
else:
# Re-run Build
result = self.clone_build(
name=self.params.get("build_name"),
namespace=self.params.get("namespace"),
request=build_request,
)
if result and self.params.get("wait"):
start = datetime.now()
def _total_wait_time():
return (datetime.now() - start).seconds
wait_timeout = self.params.get("wait_timeout")
wait_sleep = self.params.get("wait_sleep")
last_status_phase = None
while _total_wait_time() < wait_timeout:
params = dict(
kind=result["kind"],
api_version=result["apiVersion"],
name=result["metadata"]["name"],
namespace=result["metadata"]["namespace"],
)
facts = self.kubernetes_facts(**params)
if len(facts["resources"]) > 0:
last_status_phase = facts["resources"][0]["status"]["phase"]
if last_status_phase == "Complete":
result = facts["resources"][0]
break
elif last_status_phase in ("Cancelled", "Error", "Failed"):
self.fail_json(
msg="Unexpected status for Build %s/%s: %s"
% (
result["metadata"]["name"],
result["metadata"]["namespace"],
last_status_phase,
)
)
time.sleep(wait_sleep)
if last_status_phase != "Complete":
name = result["metadata"]["name"]
namespace = result["metadata"]["namespace"]
msg = (
"Build %s/%s has not complete after %d second(s),"
"current status is %s"
% (namespace, name, wait_timeout, last_status_phase)
)
self.fail_json(msg=msg)
result = [result] if result else []
self.exit_json(changed=True, builds=result)
def cancel_build(self, restart):
kind = "Build"
api_version = "build.openshift.io/v1"
namespace = self.params.get("namespace")
phases = ["new", "pending", "running"]
build_phases = self.params.get("build_phases", [])
if build_phases:
phases = [p.lower() for p in build_phases]
names = []
if self.params.get("build_name"):
names.append(self.params.get("build_name"))
else:
build_config = self.params.get("build_config_name")
# list all builds from namespace
params = dict(kind=kind, api_version=api_version, namespace=namespace)
resources = self.kubernetes_facts(**params).get("resources", [])
def _filter_builds(build):
config = (
build["metadata"]
.get("labels", {})
.get("openshift.io/build-config.name")
)
return build_config is None or (
build_config is not None and config in build_config
)
for item in list(filter(_filter_builds, resources)):
name = item["metadata"]["name"]
if name not in names:
names.append(name)
if len(names) == 0:
self.exit_json(
changed=False, msg="No Build found from namespace %s" % namespace
)
warning = []
builds_to_cancel = []
for name in names:
params = dict(
kind=kind, api_version=api_version, name=name, namespace=namespace
)
resource = self.kubernetes_facts(**params).get("resources", [])
if len(resource) == 0:
warning.append("Build %s/%s not found" % (namespace, name))
continue
resource = resource[0]
phase = resource["status"].get("phase").lower()
# Build status.phase is matching the requested state and is not completed
if phase in phases:
builds_to_cancel.append(resource)
else:
warning.append(
"build %s/%s is not in expected phase, found %s"
% (namespace, name, phase)
)
changed = False
result = []
for build in builds_to_cancel:
# Set cancelled to true
build["status"]["cancelled"] = True
name = build["metadata"]["name"]
changed = True
try:
content_type = "application/json"
cancelled_build = self.request(
"PUT",
"/apis/build.openshift.io/v1/namespaces/{0}/builds/{1}".format(
namespace, name
),
body=build,
content_type=content_type,
).to_dict()
result.append(cancelled_build)
except DynamicApiError as exc:
self.fail_json(
msg="Failed to cancel Build %s/%s due to: %s"
% (namespace, name, exc),
reason=exc.reason,
status=exc.status,
)
except Exception as e:
self.fail_json(
msg="Failed to cancel Build %s/%s due to: %s" % (namespace, name, e)
)
# Make sure the build phase is really cancelled.
def _wait_until_cancelled(build, wait_timeout, wait_sleep):
start = datetime.now()
last_phase = None
name = build["metadata"]["name"]
while (datetime.now() - start).seconds < wait_timeout:
params = dict(
kind=kind, api_version=api_version, name=name, namespace=namespace
)
resource = self.kubernetes_facts(**params).get("resources", [])
if len(resource) == 0:
return None, "Build %s/%s not found" % (namespace, name)
resource = resource[0]
last_phase = resource["status"]["phase"]
if last_phase == "Cancelled":
return resource, None
time.sleep(wait_sleep)
return (
None,
"Build %s/%s is not cancelled as expected, current state is %s"
% (namespace, name, last_phase),
)
if result and self.params.get("wait"):
wait_timeout = self.params.get("wait_timeout")
wait_sleep = self.params.get("wait_sleep")
wait_result = []
for build in result:
ret, err = _wait_until_cancelled(build, wait_timeout, wait_sleep)
if err:
self.exit_json(msg=err)
wait_result.append(ret)
result = wait_result
if restart:
self.start_build()
self.exit_json(builds=result, changed=changed)
def execute_module(self):
state = self.params.get("state")
if state == "started":
self.start_build()
else:
restart = bool(state == "restarted")
self.cancel_build(restart=restart)
class OpenShiftPruneBuilds(OpenShiftBuilds):
def __init__(self, **kwargs):
super(OpenShiftPruneBuilds, self).__init__(**kwargs)
def execute_module(self):
# list replicationcontroller candidate for pruning
kind = "Build"
api_version = "build.openshift.io/v1"
resource = self.find_resource(kind=kind, api_version=api_version, fail=True)
self.max_creation_timestamp = None
keep_younger_than = self.params.get("keep_younger_than")
if keep_younger_than:
now = datetime.now(timezone.utc).replace(tzinfo=None)
self.max_creation_timestamp = now - timedelta(minutes=keep_younger_than)
def _prunable_build(build):
return build["status"]["phase"] in (
"Complete",
"Failed",
"Error",
"Cancelled",
)
def _orphan_build(build):
if not _prunable_build(build):
return False
config = build["status"].get("config", None)
if not config:
return True
build_config = self.get_build_config(config["name"], config["namespace"])
return len(build_config) == 0
def _younger_build(build):
if not self.max_creation_timestamp:
return False
creation_timestamp = datetime.strptime(
build["metadata"]["creationTimestamp"], "%Y-%m-%dT%H:%M:%SZ"
)
return creation_timestamp < self.max_creation_timestamp
predicates = [
_prunable_build,
]
if self.params.get("orphans"):
predicates.append(_orphan_build)
if self.max_creation_timestamp:
predicates.append(_younger_build)
# Get ReplicationController
params = dict(
kind=kind,
api_version=api_version,
namespace=self.params.get("namespace"),
)
result = self.kubernetes_facts(**params)
candidates = result["resources"]
for pred in predicates:
candidates = list(filter(pred, candidates))
if self.check_mode:
changed = len(candidates) > 0
self.exit_json(changed=changed, builds=candidates)
changed = False
for build in candidates:
changed = True
try:
name = build["metadata"]["name"]
namespace = build["metadata"]["namespace"]
resource.delete(name=name, namespace=namespace, body={})
except DynamicApiError as exc:
msg = "Failed to delete Build %s/%s due to: %s" % (
namespace,
name,
exc.body,
)
self.fail_json(msg=msg, status=exc.status, reason=exc.reason)
except Exception as e:
msg = "Failed to delete Build %s/%s due to: %s" % (
namespace,
name,
to_native(e),
)
self.fail_json(msg=msg, error=to_native(e), exception=e)
self.exit_json(changed=changed, builds=candidates)
+99
View File
@@ -0,0 +1,99 @@
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import traceback
from abc import abstractmethod
from ansible.module_utils._text import to_native
try:
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
get_api_client,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.core import (
AnsibleK8SModule,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.service import (
K8sService,
diff_objects,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.runner import (
perform_action,
validate,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.resource import (
create_definitions,
merge_params,
flatten_list_kind,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import (
CoreException,
)
HAS_KUBERNETES_COLLECTION = True
k8s_collection_import_exception = None
K8S_COLLECTION_ERROR = None
except ImportError as e:
HAS_KUBERNETES_COLLECTION = False
k8s_collection_import_exception = e
K8S_COLLECTION_ERROR = traceback.format_exc()
class AnsibleOpenshiftModule(AnsibleK8SModule):
def __init__(self, **kwargs):
super(AnsibleOpenshiftModule, self).__init__(**kwargs)
self.client = get_api_client(module=self)
self.fail = self.fail_json
self.svc = K8sService(self.client, self._module)
self.find_resource = self.svc.find_resource
self.kubernetes_facts = self.svc.find
if not HAS_KUBERNETES_COLLECTION:
self.fail_json(
msg="The kubernetes.core collection must be installed",
exception=K8S_COLLECTION_ERROR,
error=to_native(k8s_collection_import_exception),
)
@property
def module(self):
return self._module
@abstractmethod
def execute_module(self):
pass
def request(self, *args, **kwargs):
return self.client.client.request(*args, **kwargs)
def set_resource_definitions(self):
self.resource_definitions = create_definitions(self.params)
def perform_action(self, definition, params):
return perform_action(self.svc, definition, params)
def validate(self, definition):
validate(self.client, self, definition)
@staticmethod
def merge_params(definition, params):
return merge_params(definition, params)
@staticmethod
def flatten_list_kind(definition, params):
return flatten_list_kind(definition, params)
@staticmethod
def diff_objects(existing, new):
return diff_objects(existing, new)
def run_module(self):
try:
self.execute_module()
except CoreException as e:
self.fail_from_exception(e)

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