Compare commits

...
39 Commits
Author SHA1 Message Date
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
Jeff GeerlingandGitHub 874cf9f171 Fixes #48: Update CHANGELOG and set up release 0.3.0. (#49) 2020-10-12 15:53:02 -04:00
Timothy AppnelandGitHub 5b2ec65cc6 Added openshift_process and openshiift_route to the README page (#47) 2020-10-12 13:52:32 -04:00
74ac82e76d Add openshift_process module (#44)
* Initial pass at openshift_process module. Render-only

* fix sanity test

* Add ability to create/delete resources rendered by template

* fix sanity tests

* add more tests and fix .env parser

* Add more tests

* Make multiline parsing work properly

* Add test for creating templates

* Template APIs require namespace to be provided whether or not the template exists

* add docs

* Update plugins/modules/openshift_process.py

Co-authored-by: Timothy Appnel <tima@ansible.com>

Co-authored-by: Timothy Appnel <tima@ansible.com>
2020-10-12 13:36:39 -04:00
Timothy AppnelandGitHub 308235e032 Fixes #45 with correct version_added in openshift_route (#46) 2020-10-09 19:32:44 -04:00
Fabian von FeilitzschandGitHub e7c3351309 Add openshift_route module for route creation (#40)
* first draft of interface

* Add basic implementation

* Add validation

* rename to openshift_route and add some test tasks

* Fix sanity checks

* Add checks for missing dependencies

* Add port processing like the oc command

* Add real tests

* Fix waiting

* add some more waiting to test

* add state parameters and fix RETURN docs

* try to fix odd sanity issue

* import tests passing

* Fix all sanity tests

* Do less work when state is absent, and add explicit removal values

* insecure_policy disable -> disallow

* add proper default for insecure_policy
2020-10-05 21:03:03 +02:00
56 changed files with 6730 additions and 334 deletions
+13 -67
View File
@@ -24,13 +24,11 @@ jobs:
ansible: ansible:
- stable-2.9 - stable-2.9
- stable-2.10 - stable-2.10
- stable-2.11
- devel - devel
python: python:
- 2.7
- 3.7 - 3.7
- 3.8 - 3.8
exclude:
- python: 3.8 # blocked by ansible/ansible#70155
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Check out code - name: Check out code
@@ -49,75 +47,22 @@ jobs:
# run ansible-test sanity inside of Docker. # run ansible-test sanity inside of Docker.
# The docker container has all the pinned dependencies that are required. # The docker container has all the pinned dependencies that are required.
# Explicity specify the version of Python we want to test # Explicitly specify the version of Python we want to test
- name: Run sanity tests - name: Run sanity tests
run: make upstream-test-sanity TEST_ARGS='--python ${{ matrix.python }}' run: make upstream-test-sanity PYTHON_VERSION='${{ matrix.python }}'
working-directory: ./ansible_collections/community/okd 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: downstream-sanity-29:
name: Sanity (Ⓐ${{ matrix.ansible }}+py${{ matrix.python }}) name: Downstream Sanity (Ⓐ${{ matrix.ansible }}+py${{ matrix.python }})
strategy: strategy:
matrix: matrix:
ansible: ansible:
- stable-2.9 - stable-2.9
- stable-2.10
- stable-2.11
python: python:
- 3.6 - 3.7
- 3.8
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Check out code - name: Check out code
@@ -130,12 +75,13 @@ jobs:
with: with:
python-version: ${{ matrix.python }} python-version: ${{ matrix.python }}
- name: Install ansible 2.9 # Install the head of the given branch (devel, stable-2.10)
run: pip install "ansible>=2.9.0,<2.10.0" - 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. # run ansible-test sanity inside of Docker.
# The docker container has all the pinned dependencies that are required. # The docker container has all the pinned dependencies that are required.
# Explicity specify the version of Python we want to test # Explicitly specify the version of Python we want to test
- name: Run sanity tests - name: Run sanity tests
run: make downstream-test-sanity run: make downstream-test-sanity PYTHON_VERSION='${{ matrix.python }}'
working-directory: ./ansible_collections/community/okd working-directory: ./ansible_collections/community/okd
+99
View File
@@ -5,6 +5,105 @@ OKD Collection Release Notes
.. contents:: Topics .. contents:: Topics
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
======
Major Changes
-------------
- Add openshift_process module for template rendering and optional application of rendered resources (https://github.com/ansible-collections/community.okd/pull/44).
- Add openshift_route module for creating routes from services (https://github.com/ansible-collections/community.okd/pull/40).
New Modules
-----------
- openshift_process - Process an OpenShift template.openshift.io/v1 Template
- openshift_route - Expose a Service as an OpenShift Route.
v0.2.0 v0.2.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.
+18 -17
View File
@@ -1,37 +1,38 @@
.PHONY: molecule
# Also needs to be updated in galaxy.yml # Also needs to be updated in galaxy.yml
VERSION = 0.2.0 VERSION = 2.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
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
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
install: build install-kubernetes-src
ansible-galaxy collection install -p ansible_collections community-okd-$(VERSION).tar.gz ansible-galaxy collection install -p ansible_collections community-okd-$(VERSION).tar.gz
sanity: install
cd ansible_collections/community/okd && ansible-test sanity -v --python $(PYTHON_VERSION) $(SANITY_TEST_ARGS)
molecule: install
molecule test
test-integration: upstream-test-integration downstream-test-integration
test-sanity: upstream-test-sanity downstream-test-sanity
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-integration: molecule
upstream-test-integration: install
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
+4 -6
View File
@@ -1,12 +1,10 @@
approvers: approvers:
- geerlingguy - gravesm
- fabianvf
- maxamillion
- akasurde - akasurde
- fabianvf
- tima - tima
reviewers: reviewers:
- geerlingguy - gravesm
- fabianvf
- maxamillion
- akasurde - akasurde
- fabianvf
- tima - tima
+46 -16
View File
@@ -1,24 +1,48 @@
# 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.9.17**.
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-->
## 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/ansible-collections/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)
> **Note**: 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/ansible-collections/community.okd/blob/main/docs/community.okd.openshift_inventory.rst)|OpenShift inventory source
### Modules
Name | Description
--- | ---
[community.okd.k8s](https://github.com/ansible-collections/community.okd/blob/main/docs/community.okd.k8s_module.rst)|Manage OpenShift objects
[community.okd.openshift_auth](https://github.com/ansible-collections/community.okd/blob/main/docs/community.okd.openshift_auth_module.rst)|Authenticate to OpenShift clusters which require an explicit login step
[community.okd.openshift_process](https://github.com/ansible-collections/community.okd/blob/main/docs/community.okd.openshift_process_module.rst)|Process an OpenShift template.openshift.io/v1 Template
[community.okd.openshift_route](https://github.com/ansible-collections/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
@@ -34,14 +58,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.2.0 version: 2.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
@@ -57,6 +81,7 @@ 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.
<!--- 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.
@@ -100,7 +125,11 @@ 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 `galaxy.yml`, this README's `requirements.yml` example, and the `Makefile` with the new `version` for the collection. 1. Update the version in the following places:
a. The `version` in `galaxy.yml`
b. This README's `requirements.yml` example
c. The `DOWNSTREAM_VERSION` in `ci/downstream.sh`
d. The `VERSION` in `Makefile`
1. Update the CHANGELOG: 1. Update the CHANGELOG:
1. Make sure you have [`antsibull-changelog`](https://pypi.org/project/antsibull-changelog/) installed. 1. Make sure you have [`antsibull-changelog`](https://pypi.org/project/antsibull-changelog/) installed.
1. Make sure there are fragments for all known changes in `changelogs/fragments`. 1. Make sure there are fragments for all known changes in `changelogs/fragments`.
@@ -109,10 +138,11 @@ Releases are automatically built and pushed to Ansible Galaxy for any new tag. B
1. Tag the version in Git and push to GitHub. 1. 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
+92
View File
@@ -44,3 +44,95 @@ releases:
name: openshift_auth name: openshift_auth
namespace: '' namespace: ''
release_date: '2020-09-24' release_date: '2020-09-24'
0.3.0:
changes:
major_changes:
- Add openshift_process module for template rendering and optional application
of rendered resources (https://github.com/ansible-collections/community.okd/pull/44).
- Add openshift_route module for creating routes from services (https://github.com/ansible-collections/community.okd/pull/40).
fragments:
- 40-openshift_route.yml
- 44-openshift_process.yml
modules:
- description: Process an OpenShift template.openshift.io/v1 Template
name: openshift_process
namespace: ''
- description: Expose a Service as an OpenShift Route.
name: openshift_route
namespace: ''
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'
+1 -1
View File
@@ -3,7 +3,7 @@ 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
@@ -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).
@@ -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 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).
+2 -2
View File
@@ -16,9 +16,9 @@ RUN yum install -y \
python3-setuptools \ python3-setuptools \
&& pip3 install --no-cache-dir --upgrade setuptools pip \ && pip3 install --no-cache-dir --upgrade setuptools pip \
&& pip3 install --no-cache-dir \ && pip3 install --no-cache-dir \
openshift \ kubernetes \
ansible==2.9.* \ ansible==2.9.* \
molecule \ "molecule<3.3.0" \
&& 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.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
+84 -57
View File
@@ -9,7 +9,7 @@
# - 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.1.0" DOWNSTREAM_VERSION="2.0.1"
KEEP_DOWNSTREAM_TMPDIR="${KEEP_DOWNSTREAM_TMPDIR:-''}" KEEP_DOWNSTREAM_TMPDIR="${KEEP_DOWNSTREAM_TMPDIR:-''}"
_build_dir="" _build_dir=""
@@ -31,15 +31,23 @@ 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"
find "${_build_dir}" -type f -exec sed -i.bak "s/community\.okd/redhat\.openshift/g" {} \;
find "${_build_dir}" -type f -name "*.bak" -delete
} }
f_prep() f_prep()
@@ -58,6 +66,8 @@ f_prep()
Makefile Makefile
setup.cfg setup.cfg
.yamllint .yamllint
requirements.txt
requirements.yml
) )
# Directories to recursively copy downstream (relative repo root dir path) # Directories to recursively copy downstream (relative repo root dir path)
@@ -70,9 +80,18 @@ f_prep()
tests tests
) )
# Modules with inherited doc fragments from kubernetes.core that need
# rendering to deal with Galaxy/AH lack of functionality.
_doc_fragment_modules=(
k8s
openshift_process
openshift_route
)
# 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,36 +130,55 @@ 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
}
# Build the collection, export docs, render them, stitch it all back together
pushd "${_build_dir}" || return
ansible-galaxy collection build
ansible-galaxy collection install -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}"
# FIXME: Check Python interpreter from environment variable to work with prow
if [ -e /usr/bin/python3.6 ]; then
PYTHON="/usr/bin/python3.6"
else
PYTHON="python"
fi
"${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()
{ {
@@ -155,6 +193,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 +201,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 +219,9 @@ 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 popd || return
f_cleanup f_cleanup
} }
@@ -200,13 +233,7 @@ f_build_option()
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
# community.kubernetes and redoing the text replacement over and over
#
# make build
ansible-galaxy collection build
popd || return popd || return
f_copy_collection_to_working_dir f_copy_collection_to_working_dir
f_cleanup f_cleanup
+28
View File
@@ -0,0 +1,28 @@
#!/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)
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 = '''\n")
df_fd.write(json_docs[sys.argv[1]]['examples'])
df_fd.write("'''\n\n")
df_fd.write("RETURN = '''\n")
df_fd.write(yaml.dump(json_docs[sys.argv[1]]['return'], default_flow_style=False))
df_fd.write("'''\n\n")
+8 -7
View File
@@ -1,4 +1,4 @@
#!/bin/bash #!/bin/bash -eu
set -x set -x
@@ -11,17 +11,18 @@ 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 eval IMAGE="$IMAGE_FORMAT"
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 +53,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,7 +61,7 @@ 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
File diff suppressed because it is too large Load Diff
+315
View File
@@ -0,0 +1,315 @@
.. _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_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
.. 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,424 @@
.. _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
- hosts: localhost
module_defaults:
group/k8s:
host: https://k8s.example.com/
ca_cert: ca.pem
tasks:
- block:
# It's good practice to store login credentials in a secure vault and not
# directly in playbooks.
- 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)
+356
View File
@@ -0,0 +1,356 @@
.. _community.okd.openshift_inventory:
***********************
community.okd.openshift
***********************
**OpenShift inventory source**
.. contents::
:local:
:depth: 1
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
# 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
# Use default config (~/.kube/config) file and active context, and return objects for a specific namespace
plugin: community.okd.openshift
connections:
- namespaces:
- testing
# 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
------
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
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -5,7 +5,7 @@ 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: '>=2.1.0,<2.2.0'
description: OKD Collection for Ansible. description: OKD Collection for Ansible.
documentation: '' documentation: ''
homepage: '' homepage: ''
@@ -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.2.0 version: 2.0.1
+8 -1
View File
@@ -1,2 +1,9 @@
--- ---
requires_ansible: '>=2.9' requires_ansible: '>=2.9.17'
plugin_routing:
modules:
k8s_auth:
redirect: community.okd.openshift_auth
action:
k8s:
redirect: kubernetes.core.k8s_info
+9
View File
@@ -0,0 +1,9 @@
#
NAME=example
# Multiline values shouldn't break things
export CONTENT=This is a long message\
that may take one or more lines to parse\
but should still work without issue
# This shouldn't throw an error
UNUSED=
+12
View File
@@ -0,0 +1,12 @@
# Want to make sure comments don't break it
export NAME=test123
NAMESPACE=openshift
# Blank lines should be fine too
# Equals in comments shouldn't break things=True
MEMORY_LIMIT=1Gi
+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
@@ -0,0 +1,34 @@
---
apiVersion: template.openshift.io/v1
kind: Template
labels:
template: simple-example-test
message: |-
The following configmaps have been created in your project: ${NAME}.
metadata:
annotations:
description: A super basic template for testing
openshift.io/display-name: Super basic template
openshift.io/provider-display-name: Red Hat, Inc.
tags: quickstart,examples
name: simple-example
objects:
- apiVersion: v1
kind: ConfigMap
metadata:
annotations:
description: Big example
name: ${NAME}
data:
content: "${CONTENT}"
parameters:
- description: The name assigned to the ConfigMap
displayName: Name
name: NAME
required: true
value: example
- description: The value for the content key of the configmap
displayName: Content
name: CONTENT
required: true
value: ''
+3
View File
@@ -1,6 +1,8 @@
--- ---
dependency: dependency:
name: galaxy name: galaxy
options:
requirements-file: requirements.yml
driver: driver:
name: delegated name: delegated
platforms: platforms:
@@ -38,6 +40,7 @@ verifier:
scenario: scenario:
name: default name: default
test_sequence: test_sequence:
- dependency
- lint - lint
- syntax - syntax
- prepare - prepare
+1 -1
View File
@@ -10,7 +10,7 @@
- pip: - pip:
name: name:
- openshift>=0.9.2 - kubernetes>=12.0.0
- coverage - coverage
virtualenv: "{{ virtualenv }}" virtualenv: "{{ virtualenv }}"
virtualenv_command: "{{ virtualenv_command }}" virtualenv_command: "{{ virtualenv_command }}"
+11 -6
View File
@@ -1,8 +1,13 @@
--- ---
- vars: - block:
# TODO(fabianvf) Get this parameter working locally as well - name: Retrieve cluster info
openshift_host: 'https://kubernetes.default.svc' kubernetes.core.k8s_cluster_info:
block: 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: test
@@ -12,7 +17,7 @@
register: openshift_auth_results register: openshift_auth_results
- name: Get the test User - name: Get the test User
community.kubernetes.k8s_info: kubernetes.core.k8s_info:
api_key: "{{ openshift_auth_results.openshift_auth.api_key }}" api_key: "{{ openshift_auth_results.openshift_auth.api_key }}"
host: '{{ openshift_host }}' host: '{{ openshift_host }}'
verify_ssl: false verify_ssl: false
@@ -35,7 +40,7 @@
verify_ssl: false verify_ssl: false
- name: Get the test user - name: Get the test user
community.kubernetes.k8s_info: kubernetes.core.k8s_info:
api_key: "{{ openshift_auth_results.openshift_auth.api_key }}" api_key: "{{ openshift_auth_results.openshift_auth.api_key }}"
host: '{{ openshift_host }}' host: '{{ openshift_host }}'
verify_ssl: false verify_ssl: false
@@ -0,0 +1,183 @@
---
- name: Process a template in the cluster
community.okd.openshift_process:
name: nginx-example
namespace: openshift # only needed if using a template already on the server
parameters:
NAMESPACE: openshift
NAME: test123
register: result
- name: Create the rendered resources
community.okd.k8s:
namespace: process-test
definition: '{{ item }}'
wait: yes
apply: yes
loop: '{{ result.resources }}'
- name: Delete the rendered resources
community.okd.k8s:
namespace: process-test
definition: '{{ item }}'
wait: yes
state: absent
loop: '{{ result.resources }}'
- name: Process a template and create the resources in the cluster
community.okd.openshift_process:
name: nginx-example
namespace: openshift # only needed if using a template already on the server
parameters:
NAMESPACE: openshift
NAME: test123
state: present
namespace_target: process-test
register: result
- name: Process a template and update the resources in the cluster
community.okd.openshift_process:
name: nginx-example
namespace: openshift # only needed if using a template already on the server
parameters:
NAMESPACE: openshift
NAME: test123
MEMORY_LIMIT: 1Gi
state: present
namespace_target: process-test
register: result
- name: Process a template and delete the resources in the cluster
community.okd.openshift_process:
name: nginx-example
namespace: openshift # only needed if using a template already on the server
parameters:
NAMESPACE: openshift
NAME: test123
state: absent
namespace_target: process-test
register: result
- name: Process a template with parameters from an env file and create the resources
community.okd.openshift_process:
name: nginx-example
namespace: openshift
namespace_target: process-test
parameter_file: '{{ files_dir }}/nginx.env'
state: present
wait: yes
- name: Process a template with parameters from an env file and delete the resources
community.okd.openshift_process:
name: nginx-example
namespace: openshift
namespace_target: process-test
parameter_file: '{{ files_dir }}/nginx.env'
state: absent
wait: yes
- name: Process a template with duplicate values
community.okd.openshift_process:
name: nginx-example
namespace: openshift # only needed if using a template already on the server
parameters:
NAME: test123
parameter_file: '{{ files_dir }}/nginx.env'
ignore_errors: yes
register: result
- name: Assert the expected failure occurred
assert:
that:
- result.msg is defined
- result.msg == "Duplicate value for 'NAME' detected in parameter file"
- name: Process a local template
community.okd.openshift_process:
src: '{{ files_dir }}/simple-template.yaml'
parameter_file: '{{ files_dir }}/example.env'
register: rendered
- name: Process a local template and create the resources
community.okd.openshift_process:
src: '{{ files_dir }}/simple-template.yaml'
parameter_file: '{{ files_dir }}/example.env'
namespace_target: process-test
state: present
register: result
- assert:
that: result is changed
- name: Create the processed resources
community.okd.k8s:
namespace: process-test
definition: '{{ item }}'
loop: '{{ rendered.resources }}'
register: result
- assert:
that: result is not changed
- name: Process a local template and create the resources
community.okd.openshift_process:
definition: "{{ lookup('template', files_dir + '/simple-template.yaml') | from_yaml }}"
parameter_file: '{{ files_dir }}/example.env'
namespace_target: process-test
state: present
register: result
- assert:
that: result is not changed
- name: Get the created configmap
kubernetes.core.k8s_info:
api_version: v1
kind: ConfigMap
name: example
namespace: process-test
register: templated_cm
- assert:
that:
- (templated_cm.resources | length) == 1
- templated_cm.resources.0.data.content is defined
- templated_cm.resources.0.data.content == "This is a long message that may take one or more lines to parse but should still work without issue"
- name: Create the Template resource
community.okd.k8s:
src: '{{ files_dir }}/simple-template.yaml'
namespace: process-test
- name: Process the template and create the resources
community.okd.openshift_process:
name: simple-example
namespace: process-test # only needed if using a template already on the server
namespace_target: process-test
parameter_file: '{{ files_dir }}/example.env'
state: present
register: result
- assert:
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 == ""
+240
View File
@@ -0,0 +1,240 @@
---
- name: Create Deployment
community.okd.k8s:
wait: yes
definition:
apiVersion: apps/v1
kind: Deployment
metadata:
name: hello-kubernetes
namespace: default
spec:
replicas: 3
selector:
matchLabels:
app: hello-kubernetes
template:
metadata:
labels:
app: hello-kubernetes
spec:
containers:
- name: hello-kubernetes
image: docker.io/openshift/hello-openshift
ports:
- containerPort: 8080
- name: Create Service
community.okd.k8s:
wait: yes
definition:
apiVersion: v1
kind: Service
metadata:
name: hello-kubernetes
namespace: default
spec:
ports:
- port: 80
targetPort: 8080
selector:
app: hello-kubernetes
- name: Create Route with fewest possible arguments
community.okd.openshift_route:
service: hello-kubernetes
namespace: default
register: route
- name: Attempt to hit http URL
uri:
url: 'http://{{ route.result.spec.host }}'
return_content: yes
until: result is successful
retries: 10
register: result
- name: Assert the page content is as expected
assert:
that:
- not result.redirected
- result.status == 200
- result.content == 'Hello OpenShift!\n'
- name: Delete route
community.okd.openshift_route:
name: '{{ route.result.metadata.name }}'
namespace: default
state: absent
wait: yes
- name: Create Route with custom name and wait
community.okd.openshift_route:
service: hello-kubernetes
namespace: default
name: test1
wait: yes
register: route
- name: Assert that the condition is properly set
assert:
that:
- route.duration is defined
- route.result.status.ingress.0.conditions.0.type == 'Admitted'
- route.result.status.ingress.0.conditions.0.status == 'True'
- name: Attempt to hit http URL
uri:
url: 'http://{{ route.result.spec.host }}'
return_content: yes
register: result
- name: Assert the page content is as expected
assert:
that:
- not result.redirected
- result.status == 200
- result.content == 'Hello OpenShift!\n'
- name: Delete route
community.okd.openshift_route:
name: '{{ route.result.metadata.name }}'
namespace: default
state: absent
wait: yes
- name: Create edge-terminated route that allows insecure traffic
community.okd.openshift_route:
service: hello-kubernetes
namespace: default
name: hello-kubernetes-https
tls:
insecure_policy: allow
termination: edge
register: route
- name: Attempt to hit http URL
uri:
url: 'http://{{ route.result.spec.host }}'
return_content: yes
until: result is successful
retries: 10
register: result
- name: Assert the page content is as expected
assert:
that:
- not result.redirected
- result.status == 200
- result.content == 'Hello OpenShift!\n'
- name: Attempt to hit https URL
uri:
url: 'https://{{ route.result.spec.host }}'
validate_certs: no
return_content: yes
until: result is successful
retries: 10
register: result
- name: Assert the page content is as expected
assert:
that:
- not result.redirected
- result.status == 200
- result.content == 'Hello OpenShift!\n'
- name: Alter edge-terminated route to redirect insecure traffic
community.okd.openshift_route:
service: hello-kubernetes
namespace: default
name: hello-kubernetes-https
tls:
insecure_policy: redirect
termination: edge
register: route
- name: Attempt to hit http URL
uri:
url: 'http://{{ route.result.spec.host }}'
return_content: yes
validate_certs: no
until:
- result is successful
- result.redirected
retries: 10
register: result
- name: Assert the page content is as expected
assert:
that:
- result.redirected
- result.status == 200
- result.content == 'Hello OpenShift!\n'
- name: Attempt to hit https URL
uri:
url: 'https://{{ route.result.spec.host }}'
validate_certs: no
return_content: yes
until: result is successful
retries: 10
register: result
- name: Assert the page content is as expected
assert:
that:
- not result.redirected
- result.status == 200
- result.content == 'Hello OpenShift!\n'
- name: Alter edge-terminated route with insecure traffic disabled
community.okd.openshift_route:
service: hello-kubernetes
namespace: default
name: hello-kubernetes-https
tls:
insecure_policy: disallow
termination: edge
register: route
- debug: var=route
- name: Attempt to hit https URL
uri:
url: 'https://{{ route.result.spec.host }}'
validate_certs: no
return_content: yes
until: result is successful
retries: 10
register: result
- name: Assert the page content is as expected
assert:
that:
- not result.redirected
- result.status == 200
- result.content == 'Hello OpenShift!\n'
- name: Attempt to hit http URL
uri:
url: 'http://{{ route.result.spec.host }}'
status_code: 503
until: result is successful
retries: 10
register: result
- debug: var=result
- name: Assert the page content is as expected
assert:
that:
- not result.redirected
- result.status == 503
- name: Delete route
community.okd.openshift_route:
name: '{{ route.result.metadata.name }}'
namespace: default
state: absent
wait: yes
+17
View File
@@ -61,3 +61,20 @@
- 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_route.yml
- block:
- name: Create namespace
community.okd.k8s:
api_version: v1
kind: Namespace
name: process-test
- import_tasks: tasks/openshift_process.yml
vars:
files_dir: '{{ playbook_dir }}/files'
always:
- name: Delete namespace
community.okd.k8s:
api_version: v1
kind: Namespace
name: process-test
state: absent
+2 -2
View File
@@ -71,7 +71,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
@@ -147,7 +147,7 @@ DOCUMENTATION = '''
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'
+10 -9
View File
@@ -22,7 +22,7 @@ DOCUMENTATION = '''
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 +36,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,8 +85,8 @@ 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"
''' '''
@@ -113,10 +113,11 @@ connections:
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 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.common import get_api_client
try: try:
from openshift.dynamic.exceptions import DynamicApiError from kubernetes.dynamic.exceptions import DynamicApiError
except ImportError: except ImportError:
pass pass
@@ -135,7 +136,7 @@ class InventoryModule(K8sInventoryModule):
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('name', self.get_default_host_name(client.configuration.host))
if connection.get('namespaces'): if connection.get('namespaces'):
namespaces = connection['namespaces'] namespaces = connection['namespaces']
@@ -144,7 +145,7 @@ class InventoryModule(K8sInventoryModule):
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:
+142 -85
View File
@@ -1,21 +1,16 @@
#!/usr/bin/python #!/usr/bin/python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# (c) 2018, Chris Houseknecht <@chouseknecht> # Copyright: (c) 2018, Chris Houseknecht <@chouseknecht>
# 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
# STARTREMOVE (downstream)
ANSIBLE_METADATA = {'metadata_version': '1.1', DOCUMENTATION = r'''
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
module: k8s module: k8s
@@ -26,29 +21,38 @@ author:
- "Fabian von Feilitzsch (@fabianvf)" - "Fabian von Feilitzsch (@fabianvf)"
description: description:
- Use the OpenShift Python client to perform CRUD operations on K8s objects. - Use the Kubernetes Python client to perform CRUD operations on K8s objects.
- Pass the object definition from a source file or inline. See examples for reading - Pass the object definition from a source file or inline. See examples for reading
files and using Jinja templates or vault-encrypted files. files and using Jinja templates or vault-encrypted files.
- Access to the full range of K8s APIs. - Access to the full range of K8s APIs.
- Use the M(k8s_info) module to obtain a list of items about an object of type C(kind) - Use the M(kubernetes.core.k8s_info) module to obtain a list of items about an object of type C(kind).
- Authenticate using either a config file, certificates, password or token. - Authenticate using either a config file, certificates, password or token.
- Supports check mode. - Supports check mode.
- Optimized for OKD/OpenShift Kubernetes flavors - Optimized for OKD/OpenShift Kubernetes flavors.
extends_documentation_fragment: extends_documentation_fragment:
- community.kubernetes.k8s_state_options - kubernetes.core.k8s_name_options
- community.kubernetes.k8s_name_options - kubernetes.core.k8s_resource_options
- community.kubernetes.k8s_resource_options - kubernetes.core.k8s_auth_options
- community.kubernetes.k8s_auth_options - kubernetes.core.k8s_wait_options
- kubernetes.core.k8s_delete_options
notes:
- If your OpenShift Python library is not 0.9.0 or newer and you are trying to
remove an item from an associative array/dictionary, for example a label or
an annotation, you will need to explicitly set the value of the item to be
removed to `null`. Simply deleting the entry in the dictionary will not
remove it from openshift or kubernetes.
options: options:
state:
description:
- Determines if an object should be created, patched, or deleted. When set to C(present), an object will be
created, if it does not already exist. If set to C(absent), an existing object will be deleted. If set to
C(present), an existing object will be patched, if its attributes differ from those specified using
I(resource_definition) or I(src).
- C(patched) state is an existing resource that has a given patch applied. If the resource doesn't exist, silently skip it (do not raise an error).
type: str
default: present
choices: [ absent, present, patched ]
force:
description:
- If set to C(yes), and I(state) is C(present), an existing object will be replaced.
type: bool
default: no
merge_type: merge_type:
description: description:
- Whether to override the default patch merge approach with a specific type. By default, the strategic - Whether to override the default patch merge approach with a specific type. By default, the strategic
@@ -56,65 +60,17 @@ options:
- For example, Custom Resource Definitions typically aren't updatable by the usual strategic merge. You may - For example, Custom Resource Definitions typically aren't updatable by the usual strategic merge. You may
want to use C(merge) if you see "strategic merge patch format is not supported" want to use C(merge) if you see "strategic merge patch format is not supported"
- See U(https://kubernetes.io/docs/tasks/run-application/update-api-object-kubectl-patch/#use-a-json-merge-patch-to-update-a-deployment) - See U(https://kubernetes.io/docs/tasks/run-application/update-api-object-kubectl-patch/#use-a-json-merge-patch-to-update-a-deployment)
- Requires openshift >= 0.6.2
- If more than one merge_type is given, the merge_types will be tried in order - If more than one merge_type is given, the merge_types will be tried in order
- If openshift >= 0.6.2, this defaults to C(['strategic-merge', 'merge']), which is ideal for using the same parameters - Defaults to C(['strategic-merge', 'merge']), which is ideal for using the same parameters
on resource kinds that combine Custom Resources and built-in resources. For openshift < 0.6.2, the default on resource kinds that combine Custom Resources and built-in resources.
is simply C(strategic-merge).
- mutually exclusive with C(apply) - mutually exclusive with C(apply)
- I(merge_type=json) is deprecated and will be removed in version 3.0.0. Please use M(kubernetes.core.k8s_json_patch) instead.
choices: choices:
- json - json
- merge - merge
- strategic-merge - strategic-merge
type: list type: list
elements: str elements: str
wait:
description:
- Whether to wait for certain resource kinds to end up in the desired state. By default the module exits once Kubernetes has
received the request
- Implemented for C(state=present) for C(Deployment), C(DaemonSet) and C(Pod), and for C(state=absent) for all resource kinds.
- For resource kinds without an implementation, C(wait) returns immediately unless C(wait_condition) is set.
default: no
type: bool
wait_sleep:
description:
- Number of seconds to sleep between checks.
default: 5
type: int
wait_timeout:
description:
- How long in seconds to wait for the resource to end up in the desired state. Ignored if C(wait) is not set.
default: 120
type: int
wait_condition:
description:
- Specifies a custom condition on the status to wait for. Ignored if C(wait) is not set or is set to False.
suboptions:
type:
type: str
description:
- The type of condition to wait for. For example, the C(Pod) resource will set the C(Ready) condition (among others)
- Required if you are specifying a C(wait_condition). If left empty, the C(wait_condition) field will be ignored.
- The possible types for a condition are specific to each resource type in Kubernetes. See the API documentation of the status field
for a given resource to see possible choices.
status:
type: str
description:
- The value of the status field in your desired condition.
- For example, if a C(Deployment) is paused, the C(Progressing) C(type) will have the C(Unknown) status.
choices:
- True
- False
- Unknown
default: "True"
reason:
type: str
description:
- The value of the reason field in your desired condition
- For example, if a C(Deployment) is paused, The C(Progressing) C(type) will have the C(DeploymentPaused) reason.
- The possible reasons in a condition are specific to each resource type in Kubernetes. See the API documentation of the status field
for a given resource to see possible choices.
type: dict
validate: validate:
description: description:
- how (if at all) to validate the resource definition against the kubernetes schema. - how (if at all) to validate the resource definition against the kubernetes schema.
@@ -140,6 +96,7 @@ options:
will only work if the same object is passed with state=absent (alternatively, just use state=absent with the name including will only work if the same object is passed with state=absent (alternatively, just use state=absent with the name including
the generated hash and append_hash=no) the generated hash and append_hash=no)
type: bool type: bool
default: false
apply: apply:
description: description:
- C(apply) compares the desired resource definition with the previously supplied resource definition, - C(apply) compares the desired resource definition with the previously supplied resource definition,
@@ -147,14 +104,47 @@ options:
- C(apply) works better with Services than 'force=yes' - C(apply) works better with Services than 'force=yes'
- mutually exclusive with C(merge_type) - mutually exclusive with C(merge_type)
type: bool type: bool
default: false
template:
description:
- Provide a valid YAML template definition file for an object when creating or updating.
- Value can be provided as string or dictionary.
- Mutually exclusive with C(src) and C(resource_definition).
- Template files needs to be present on the Ansible Controller's file system.
- Additional parameters can be specified using dictionary.
- 'Valid additional parameters - '
- 'C(newline_sequence) (str): Specify the newline sequence to use for templating files.
valid choices are "\n", "\r", "\r\n". Default value "\n".'
- 'C(block_start_string) (str): The string marking the beginning of a block.
Default value "{%".'
- 'C(block_end_string) (str): The string marking the end of a block.
Default value "%}".'
- 'C(variable_start_string) (str): The string marking the beginning of a print statement.
Default value "{{".'
- 'C(variable_end_string) (str): The string marking the end of a print statement.
Default value "}}".'
- 'C(trim_blocks) (bool): Determine when newlines should be removed from blocks. When set to C(yes) the first newline
after a block is removed (block, not variable tag!). Default value is true.'
- 'C(lstrip_blocks) (bool): Determine when leading spaces and tabs should be stripped.
When set to C(yes) leading spaces and tabs are stripped from the start of a line to a block.
This functionality requires Jinja 2.7 or newer. Default value is false.'
type: raw
version_added: '2.0.0'
continue_on_error:
description:
- Whether to continue on creation/deletion errors when multiple resources are defined.
- This has no effect on the validation step which is controlled by the C(validate.fail_on_error) parameter.
type: bool
default: False
version_added: 2.0.0
requirements: requirements:
- "python >= 2.7" - "python >= 3.6"
- "openshift >= 0.6" - "kubernetes >= 12.0.0"
- "PyYAML >= 3.11" - "PyYAML >= 3.11"
''' '''
EXAMPLES = ''' EXAMPLES = r'''
- name: Create a k8s namespace - name: Create a k8s namespace
community.okd.k8s: community.okd.k8s:
name: testing name: testing
@@ -227,7 +217,7 @@ EXAMPLES = '''
strict: yes strict: yes
''' '''
RETURN = ''' RETURN = r'''
result: result:
description: description:
- The created, patched, or otherwise present object. Will be empty in the case of a deletion. - The created, patched, or otherwise present object. Will be empty in the case of a deletion.
@@ -263,27 +253,35 @@ result:
returned: when C(wait) is true returned: when C(wait) is true
type: int type: int
sample: 48 sample: 48
error:
description: error while trying to create/delete the object.
returned: error
type: complex
''' '''
# ENDREMOVE (downstream)
import copy
import re import re
import operator import operator
import traceback import traceback
from functools import reduce from functools import reduce
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
try: try:
from ansible_collections.community.kubernetes.plugins.module_utils.raw import KubernetesRawModule from ansible_collections.kubernetes.core.plugins.module_utils.common import get_api_client, K8sAnsibleMixin
from ansible_collections.kubernetes.core.plugins.module_utils.args_common import (
NAME_ARG_SPEC, RESOURCE_ARG_SPEC, AUTH_ARG_SPEC, WAIT_ARG_SPEC, DELETE_OPTS_ARG_SPEC)
HAS_KUBERNETES_COLLECTION = True HAS_KUBERNETES_COLLECTION = True
except ImportError as e: except ImportError as e:
HAS_KUBERNETES_COLLECTION = False HAS_KUBERNETES_COLLECTION = False
k8s_collection_import_exception = e k8s_collection_import_exception = e
K8S_COLLECTION_ERROR = traceback.format_exc() K8S_COLLECTION_ERROR = traceback.format_exc()
from ansible.module_utils.basic import AnsibleModule as KubernetesRawModule
try: try:
import yaml import yaml
from openshift.dynamic.exceptions import DynamicApiError, NotFoundError, ForbiddenError from kubernetes.dynamic.exceptions import DynamicApiError, NotFoundError, ForbiddenError
except ImportError: except ImportError:
# Exceptions handled in common # Exceptions handled in common
pass pass
@@ -292,16 +290,73 @@ 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])?))") 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(KubernetesRawModule): class OKDRawModule(K8sAnsibleMixin):
def __init__(self, k8s_kind=None, *args, **kwargs):
mutually_exclusive = [
('resource_definition', 'src'),
('merge_type', 'apply'),
('template', 'resource_definition'),
('template', 'src'),
]
module = AnsibleModule(
argument_spec=self.argspec,
mutually_exclusive=mutually_exclusive,
supports_check_mode=True,
)
self.module = module
self.check_mode = self.module.check_mode
self.params = self.module.params
self.fail_json = self.module.fail_json
self.fail = self.module.fail_json
self.exit_json = self.module.exit_json
def __init__(self):
if not HAS_KUBERNETES_COLLECTION: if not HAS_KUBERNETES_COLLECTION:
self.fail_json( self.fail_json(
msg="The community.kubernetes collection must be installed", msg="The kubernetes.core collection must be installed",
exception=K8S_COLLECTION_ERROR, exception=K8S_COLLECTION_ERROR,
error=to_native(k8s_collection_import_exception) error=to_native(k8s_collection_import_exception)
) )
super(OKDRawModule, self).__init__()
super(OKDRawModule, self).__init__(module, *args, **kwargs)
self.client = get_api_client(module)
self.warnings = []
self.kind = k8s_kind or self.params.get('kind')
self.api_version = self.params.get('api_version')
self.name = self.params.get('name')
self.namespace = self.params.get('namespace')
self.check_library_version()
self.set_resource_definitions(module)
@property
def validate_spec(self):
return dict(
fail_on_error=dict(type='bool'),
version=dict(),
strict=dict(type='bool', default=True)
)
@property
def argspec(self):
argument_spec = copy.deepcopy(NAME_ARG_SPEC)
argument_spec.update(copy.deepcopy(RESOURCE_ARG_SPEC))
argument_spec.update(copy.deepcopy(AUTH_ARG_SPEC))
argument_spec.update(copy.deepcopy(WAIT_ARG_SPEC))
argument_spec['merge_type'] = dict(type='list', elements='str', choices=['json', 'merge', 'strategic-merge'])
argument_spec['validate'] = dict(type='dict', default=None, options=self.validate_spec)
argument_spec['append_hash'] = dict(type='bool', default=False)
argument_spec['apply'] = dict(type='bool', default=False)
argument_spec['template'] = dict(type='raw', default=None)
argument_spec['delete_options'] = dict(type='dict', default=None, options=copy.deepcopy(DELETE_OPTS_ARG_SPEC))
argument_spec['continue_on_error'] = dict(type='bool', default=False)
argument_spec['state'] = dict(default='present', choices=['present', 'absent', 'patched'])
argument_spec['force'] = dict(type='bool', default=False)
return argument_spec
def perform_action(self, resource, definition): def perform_action(self, resource, definition):
state = self.params.get('state', None) state = self.params.get('state', None)
@@ -396,7 +451,9 @@ class OKDRawModule(KubernetesRawModule):
image = existing['spec']['template']['spec']['containers'][old_container_index]['image'] image = existing['spec']['template']['spec']['containers'][old_container_index]['image']
definition['spec']['template']['spec']['containers'][new_container_index]['image'] = 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']) existing_index = self.get_index(trigger['imageChangeParams'],
[x.get('imageChangeParams') for x in existing_triggers],
['containerNames'])
if existing_index is not None: if existing_index is not None:
existing_image = existing_triggers[existing_index].get('imageChangeParams', {}).get('lastTriggeredImage') existing_image = existing_triggers[existing_index].get('imageChangeParams', {}).get('lastTriggeredImage')
if existing_image: if existing_image:
-1
View File
@@ -1 +0,0 @@
openshift_auth.py
+2 -4
View File
@@ -5,10 +5,8 @@
# 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 = r''' DOCUMENTATION = r'''
module: openshift_auth module: openshift_auth
@@ -72,7 +70,7 @@ options:
type: str type: str
requirements: requirements:
- python >= 2.7 - python >= 3.6
- urllib3 - urllib3
- requests - requests
- requests-oauthlib - requests-oauthlib
@@ -99,7 +97,7 @@ EXAMPLES = r'''
# Previous task provides the token/api_key, while all other parameters # Previous task provides the token/api_key, while all other parameters
# are taken from module_defaults # are taken from module_defaults
- name: Get a list of all pods from any namespace - name: Get a list of all pods from any namespace
community.kubernetes.k8s_info: kubernetes.core.k8s_info:
api_key: "{{ openshift_auth_results.openshift_auth.api_key }}" api_key: "{{ openshift_auth_results.openshift_auth.api_key }}"
kind: Pod kind: Pod
register: pod_list register: pod_list
+391
View File
@@ -0,0 +1,391 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Red Hat
# 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
# STARTREMOVE (downstream)
DOCUMENTATION = r'''
module: openshift_process
short_description: Process an OpenShift template.openshift.io/v1 Template
version_added: "0.3.0"
author: "Fabian von Feilitzsch (@fabianvf)"
description:
- Processes a specified OpenShift template with the provided template.
- Templates can be provided inline, from a file, or specified by name and namespace in the cluster.
- Analogous to `oc process`.
- For CRUD operations on Template resources themselves, see the community.okd.k8s module.
extends_documentation_fragment:
- kubernetes.core.k8s_auth_options
- kubernetes.core.k8s_wait_options
- kubernetes.core.k8s_resource_options
requirements:
- "python >= 3.6"
- "kubernetes >= 12.0.0"
- "PyYAML >= 3.11"
options:
name:
description:
- The name of the Template to process.
- The Template must be present in the cluster.
- When provided, I(namespace) is required.
- Mutually exclusive with I(resource_definition) or I(src)
type: str
namespace:
description:
- The namespace that the template can be found in.
type: str
namespace_target:
description:
- The namespace that resources should be created, updated, or deleted in.
- Only used when I(state) is present or absent.
parameters:
description:
- 'A set of key: value pairs that will be used to set/override values in the Template.'
- Corresponds to the `--param` argument to oc process.
type: dict
parameter_file:
description:
- A path to a file containing template parameter values to override/set values in the Template.
- Corresponds to the `--param-file` argument to oc process.
type: str
state:
description:
- Determines what to do with the rendered Template.
- The state I(rendered) will render the Template based on the provided parameters, and return the rendered
objects in the I(resources) field. These can then be referenced in future tasks.
- The state I(present) will cause the resources in the rendered Template to be created if they do not
already exist, and patched if they do.
- The state I(absent) will delete the resources in the rendered Template.
type: str
default: rendered
choices: [ absent, present, rendered ]
'''
EXAMPLES = r'''
- name: Process a template in the cluster
community.okd.openshift_process:
name: nginx-example
namespace: openshift # only needed if using a template already on the server
parameters:
NAMESPACE: openshift
NAME: test123
state: rendered
register: result
- name: Create the rendered resources using apply
community.okd.k8s:
namespace: default
definition: '{{ item }}'
wait: yes
apply: yes
loop: '{{ result.resources }}'
- name: Process a template with parameters from an env file and create the resources
community.okd.openshift_process:
name: nginx-example
namespace: openshift
namespace_target: default
parameter_file: 'files/nginx.env'
state: present
wait: yes
- name: Process a local template and create the resources
community.okd.openshift_process:
src: files/example-template.yaml
parameter_file: files/example.env
namespace_target: default
state: present
- name: Process a local template, delete the resources, and wait for them to terminate
community.okd.openshift_process:
src: files/example-template.yaml
parameter_file: files/example.env
namespace_target: default
state: absent
wait: yes
'''
RETURN = r'''
result:
description:
- The created, patched, or otherwise present object. Will be empty in the case of a deletion.
returned: on success when state is present or absent
type: complex
contains:
apiVersion:
description: The versioned schema of this representation of an object.
returned: success
type: str
kind:
description: Represents the REST resource this object represents.
returned: success
type: str
metadata:
description: Standard object metadata. Includes name, namespace, annotations, labels, etc.
returned: success
type: complex
contains:
name:
description: The name of the resource
type: str
namespace:
description: The namespace of the resource
type: str
spec:
description: Specific attributes of the object. Will vary based on the I(api_version) and I(kind).
returned: success
type: dict
status:
description: Current status details for the object.
returned: success
type: complex
contains:
conditions:
type: complex
description: Array of status conditions for the object. Not guaranteed to be present
items:
description: Returned only when multiple yaml documents are passed to src or resource_definition
returned: when resource_definition or src contains list of objects
type: list
duration:
description: elapsed time of task in seconds
returned: when C(wait) is true
type: int
sample: 48
resources:
type: complex
description:
- The rendered resources defined in the Template
returned: on success when state is rendered
contains:
apiVersion:
description: The versioned schema of this representation of an object.
returned: success
type: str
kind:
description: Represents the REST resource this object represents.
returned: success
type: str
metadata:
description: Standard object metadata. Includes name, namespace, annotations, labels, etc.
returned: success
type: complex
contains:
name:
description: The name of the resource
type: str
namespace:
description: The namespace of the resource
type: str
spec:
description: Specific attributes of the object. Will vary based on the I(api_version) and I(kind).
returned: success
type: dict
status:
description: Current status details for the object.
returned: success
type: dict
contains:
conditions:
type: complex
description: Array of status conditions for the object. Not guaranteed to be present
'''
# ENDREMOVE (downstream)
import re
import os
import copy
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
try:
from ansible_collections.kubernetes.core.plugins.module_utils.common import K8sAnsibleMixin, get_api_client
from ansible_collections.kubernetes.core.plugins.module_utils.args_common import (
AUTH_ARG_SPEC, RESOURCE_ARG_SPEC, WAIT_ARG_SPEC
)
HAS_KUBERNETES_COLLECTION = True
except ImportError as e:
HAS_KUBERNETES_COLLECTION = False
k8s_collection_import_exception = e
K8S_COLLECTION_ERROR = traceback.format_exc()
K8sAnsibleMixin = object
AUTH_ARG_SPEC = RESOURCE_ARG_SPEC = WAIT_ARG_SPEC = {}
try:
from kubernetes.dynamic.exceptions import DynamicApiError, NotFoundError
except ImportError:
pass
DOTENV_PARSER = re.compile(r"(?x)^(\s*(\#.*|\s*|(export\s+)?(?P<key>[A-z_][A-z0-9_.]*)=(?P<value>.+?)?)\s*)[\r\n]*$")
class OpenShiftProcess(K8sAnsibleMixin):
def __init__(self):
self.module = AnsibleModule(
argument_spec=self.argspec,
supports_check_mode=True,
)
self.fail_json = self.module.fail_json
self.exit_json = self.module.exit_json
if not HAS_KUBERNETES_COLLECTION:
self.module.fail_json(
msg="The kubernetes.core collection must be installed",
exception=K8S_COLLECTION_ERROR,
error=to_native(k8s_collection_import_exception)
)
super(OpenShiftProcess, self).__init__(self.module)
self.params = self.module.params
self.check_mode = self.module.check_mode
@property
def argspec(self):
spec = copy.deepcopy(AUTH_ARG_SPEC)
spec.update(copy.deepcopy(WAIT_ARG_SPEC))
spec.update(copy.deepcopy(RESOURCE_ARG_SPEC))
spec['state'] = dict(type='str', default='rendered', choices=['present', 'absent', 'rendered'])
spec['namespace'] = dict(type='str')
spec['namespace_target'] = dict(type='str')
spec['parameters'] = dict(type='dict')
spec['name'] = dict(type='str')
spec['parameter_file'] = dict(type='str')
return spec
def execute_module(self):
self.client = get_api_client(self.module)
v1_templates = self.find_resource('templates', 'template.openshift.io/v1', fail=True)
v1_processed_templates = self.find_resource('processedtemplates', 'template.openshift.io/v1', fail=True)
name = self.params.get('name')
namespace = self.params.get('namespace')
namespace_target = self.params.get('namespace_target')
definition = self.params.get('resource_definition')
src = self.params.get('src')
state = self.params.get('state')
parameters = self.params.get('parameters') or {}
parameter_file = self.params.get('parameter_file')
if (name and definition) or (name and src) or (src and definition):
self.fail_json("Only one of src, name, or definition may be provided")
if name and not namespace:
self.fail_json("namespace is required when name is set")
template = None
if src or definition:
self.set_resource_definitions(self.module)
if len(self.resource_definitions) < 1:
self.fail_json('Unable to load a Template resource from src or resource_definition')
elif len(self.resource_definitions) > 1:
self.fail_json('Multiple Template resources found in src or resource_definition, only one Template may be processed at a time')
template = self.resource_definitions[0]
template_namespace = template.get('metadata', {}).get('namespace')
namespace = template_namespace or namespace or namespace_target or 'default'
elif name and namespace:
try:
template = v1_templates.get(name=name, namespace=namespace).to_dict()
except DynamicApiError as exc:
self.fail_json(msg="Failed to retrieve Template with name '{0}' in namespace '{1}': {2}".format(name, namespace, exc.body),
error=exc.status, status=exc.status, reason=exc.reason)
except Exception as exc:
self.module.fail_json(msg="Failed to retrieve Template with name '{0}' in namespace '{1}': {2}".format(name, namespace, to_native(exc)),
error='', status='', reason='')
else:
self.fail_json("One of resource_definition, src, or name and namespace must be provided")
if parameter_file:
parameters = self.parse_dotenv_and_merge(parameters, parameter_file)
for k, v in parameters.items():
template = self.update_template_param(template, k, v)
result = {'changed': False}
try:
response = v1_processed_templates.create(body=template, namespace=namespace).to_dict()
except DynamicApiError as exc:
self.fail_json(msg="Server failed to render the Template: {0}".format(exc.body),
error=exc.status, status=exc.status, reason=exc.reason)
except Exception as exc:
self.module.fail_json(msg="Server failed to render the Template: {0}".format(to_native(exc)),
error='', status='', reason='')
result['message'] = ""
if "message" in response:
result['message'] = response['message']
result['resources'] = response['objects']
if state != 'rendered':
self.resource_definitions = response['objects']
self.kind = self.api_version = self.name = None
self.namespace = self.params.get('namespace_target')
self.append_hash = False
self.apply = False
self.params['validate'] = None
self.params['merge_type'] = None
super(OpenShiftProcess, self).execute_module()
self.module.exit_json(**result)
def update_template_param(self, template, k, v):
for i, param in enumerate(template['parameters']):
if param['name'] == k:
template['parameters'][i]['value'] = v
return template
return template
def parse_dotenv_and_merge(self, parameters, parameter_file):
path = os.path.normpath(parameter_file)
if not os.path.exists(path):
self.fail(msg="Error accessing {0}. Does the file exist?".format(path))
try:
with open(path, 'r') as f:
multiline = ''
for line in f.readlines():
line = line.strip()
if line.endswith('\\'):
multiline += ' '.join(line.rsplit('\\', 1))
continue
if multiline:
line = multiline + line
multiline = ''
match = DOTENV_PARSER.search(line)
if not match:
continue
match = match.groupdict()
if match.get('key'):
if match['key'] in parameters:
self.fail_json(msg="Duplicate value for '{0}' detected in parameter file".format(match['key']))
parameters[match['key']] = match['value']
except IOError as exc:
self.fail(msg="Error loading parameter file: {0}".format(exc))
return parameters
def main():
OpenShiftProcess().execute_module()
if __name__ == '__main__':
main()
+546
View File
@@ -0,0 +1,546 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Red Hat
# 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
# STARTREMOVE (downstream)
DOCUMENTATION = r'''
module: openshift_route
short_description: Expose a Service as an OpenShift Route.
version_added: "0.3.0"
author: "Fabian von Feilitzsch (@fabianvf)"
description:
- Looks up a Service and creates a new Route based on it.
- Analogous to `oc expose` and `oc create route` for creating Routes, but does not support creating Services.
- For creating Services from other resources, see kubernetes.core.k8s_expose
extends_documentation_fragment:
- kubernetes.core.k8s_auth_options
- kubernetes.core.k8s_wait_options
- kubernetes.core.k8s_state_options
requirements:
- "python >= 3.6"
- "kubernetes >= 12.0.0"
- "PyYAML >= 3.11"
options:
service:
description:
- The name of the service to expose.
- Required when I(state) is not absent.
type: str
aliases: ['svc']
namespace:
description:
- The namespace of the resource being targeted.
- The Route will be created in this namespace as well.
required: yes
type: str
labels:
description:
- Specify the labels to apply to the created Route.
- 'A set of key: value pairs.'
type: dict
name:
description:
- The desired name of the Route to be created.
- Defaults to the value of I(service)
type: str
hostname:
description:
- The hostname for the Route.
type: str
path:
description:
- The path for the Route
type: str
wildcard_policy:
description:
- The wildcard policy for the hostname.
- Currently only Subdomain is supported.
- If not provided, the default of None will be used.
choices:
- Subdomain
type: str
port:
description:
- Name or number of the port the Route will route traffic to.
type: str
tls:
description:
- TLS configuration for the newly created route.
- Only used when I(termination) is set.
type: dict
suboptions:
ca_certificate:
description:
- Path to a CA certificate file on the target host.
- Not supported when I(termination) is set to passthrough.
type: str
certificate:
description:
- Path to a certificate file on the target host.
- Not supported when I(termination) is set to passthrough.
type: str
destination_ca_certificate:
description:
- Path to a CA certificate file used for securing the connection.
- Only used when I(termination) is set to reencrypt.
- Defaults to the Service CA.
type: str
key:
description:
- Path to a key file on the target host.
- Not supported when I(termination) is set to passthrough.
type: str
insecure_policy:
description:
- Sets the InsecureEdgeTerminationPolicy for the Route.
- Not supported when I(termination) is set to reencrypt.
- When I(termination) is set to passthrough, only redirect is supported.
- If not provided, insecure traffic will be disallowed.
type: str
choices:
- allow
- redirect
- disallow
default: disallow
termination:
description:
- The termination type of the Route.
- If left empty no termination type will be set, and the route will be insecure.
- When set to insecure I(tls) will be ignored.
choices:
- edge
- passthrough
- reencrypt
- insecure
default: insecure
type: str
'''
EXAMPLES = r'''
- name: Create hello-world deployment
community.okd.k8s:
definition:
apiVersion: apps/v1
kind: Deployment
metadata:
name: hello-kubernetes
namespace: default
spec:
replicas: 3
selector:
matchLabels:
app: hello-kubernetes
template:
metadata:
labels:
app: hello-kubernetes
spec:
containers:
- name: hello-kubernetes
image: paulbouwer/hello-kubernetes:1.8
ports:
- containerPort: 8080
- name: Create Service for the hello-world deployment
community.okd.k8s:
definition:
apiVersion: v1
kind: Service
metadata:
name: hello-kubernetes
namespace: default
spec:
ports:
- port: 80
targetPort: 8080
selector:
app: hello-kubernetes
- name: Expose the insecure hello-world service externally
community.okd.openshift_route:
service: hello-kubernetes
namespace: default
insecure_policy: allow
register: route
'''
RETURN = r'''
result:
description:
- The Route object that was created or updated. Will be empty in the case of deletion.
returned: success
type: complex
contains:
apiVersion:
description: The versioned schema of this representation of an object.
returned: success
type: str
kind:
description: Represents the REST resource this object represents.
returned: success
type: str
metadata:
description: Standard object metadata. Includes name, namespace, annotations, labels, etc.
returned: success
type: complex
contains:
name:
description: The name of the created Route
type: str
namespace:
description: The namespace of the create Route
type: str
spec:
description: Specification for the Route
returned: success
type: complex
contains:
host:
description: Host is an alias/DNS that points to the service.
type: str
path:
description: Path that the router watches for, to route traffic for to the service.
type: str
port:
description: Defines a port mapping from a router to an endpoint in the service endpoints.
type: complex
contains:
targetPort:
description: The target port on pods selected by the service this route points to.
type: str
tls:
description: Defines config used to secure a route and provide termination.
type: complex
contains:
caCertificate:
description: Provides the cert authority certificate contents.
type: str
certificate:
description: Provides certificate contents.
type: str
destinationCACertificate:
description: Provides the contents of the ca certificate of the final destination.
type: str
insecureEdgeTerminationPolicy:
description: Indicates the desired behavior for insecure connections to a route.
type: str
key:
description: Provides key file contents.
type: str
termination:
description: Indicates termination type.
type: str
to:
description: Specifies the target that resolve into endpoints.
type: complex
contains:
kind:
description: The kind of target that the route is referring to. Currently, only 'Service' is allowed.
type: str
name:
description: Name of the service/target that is being referred to. e.g. name of the service.
type: str
weight:
description: Specifies the target's relative weight against other target reference objects.
type: int
wildcardPolicy:
description: Wildcard policy if any for the route.
type: str
status:
description: Current status details for the Route
returned: success
type: complex
contains:
ingress:
description: List of places where the route may be exposed.
type: complex
contains:
conditions:
description: Array of status conditions for the Route ingress.
type: complex
contains:
type:
description: The type of the condition. Currently only 'Ready'.
type: str
status:
description: The status of the condition. Can be True, False, Unknown.
type: str
host:
description: The host string under which the route is exposed.
type: str
routerCanonicalHostname:
description: The external host name for the router that can be used as a CNAME for the host requested for this route. May not be set.
type: str
routerName:
description: A name chosen by the router to identify itself.
type: str
wildcardPolicy:
description: The wildcard policy that was allowed where this route is exposed.
type: str
duration:
description: elapsed time of task in seconds
returned: when C(wait) is true
type: int
sample: 48
'''
# ENDREMOVE (downstream)
import copy
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
try:
from ansible_collections.kubernetes.core.plugins.module_utils.common import K8sAnsibleMixin, get_api_client
from ansible_collections.kubernetes.core.plugins.module_utils.args_common import (
AUTH_ARG_SPEC, WAIT_ARG_SPEC, COMMON_ARG_SPEC
)
HAS_KUBERNETES_COLLECTION = True
except ImportError as e:
HAS_KUBERNETES_COLLECTION = False
k8s_collection_import_exception = e
K8S_COLLECTION_ERROR = traceback.format_exc()
K8sAnsibleMixin = object
AUTH_ARG_SPEC = WAIT_ARG_SPEC = COMMON_ARG_SPEC = {}
try:
from kubernetes.dynamic.exceptions import DynamicApiError, NotFoundError
except ImportError:
pass
class OpenShiftRoute(K8sAnsibleMixin):
def __init__(self):
self.module = AnsibleModule(
argument_spec=self.argspec,
supports_check_mode=True,
)
self.fail_json = self.module.fail_json
if not HAS_KUBERNETES_COLLECTION:
self.module.fail_json(
msg="The kubernetes.core collection must be installed",
exception=K8S_COLLECTION_ERROR,
error=to_native(k8s_collection_import_exception)
)
super(OpenShiftRoute, self).__init__(self.module)
self.params = self.module.params
# TODO: should probably make it so that at least some of these aren't required for perform_action to work
# Or at least explicitly pass them in
self.append_hash = False
self.apply = False
self.check_mode = self.module.check_mode
self.warnings = []
self.params['merge_type'] = None
@property
def argspec(self):
spec = copy.deepcopy(AUTH_ARG_SPEC)
spec.update(copy.deepcopy(WAIT_ARG_SPEC))
spec.update(copy.deepcopy(COMMON_ARG_SPEC))
spec['service'] = dict(type='str', aliases=['svc'])
spec['namespace'] = dict(required=True, type='str')
spec['labels'] = dict(type='dict')
spec['name'] = dict(type='str')
spec['hostname'] = dict(type='str')
spec['path'] = dict(type='str')
spec['wildcard_policy'] = dict(choices=['Subdomain'], type='str')
spec['port'] = dict(type='str')
spec['tls'] = dict(type='dict', options=dict(
ca_certificate=dict(type='str'),
certificate=dict(type='str'),
destination_ca_certificate=dict(type='str'),
key=dict(type='str', no_log=False),
insecure_policy=dict(type='str', choices=['allow', 'redirect', 'disallow'], default='disallow'),
))
spec['termination'] = dict(choices=['edge', 'passthrough', 'reencrypt', 'insecure'], default='insecure')
return spec
def execute_module(self):
self.client = get_api_client(self.module)
v1_routes = self.find_resource('Route', 'route.openshift.io/v1', fail=True)
service_name = self.params.get('service')
namespace = self.params['namespace']
termination_type = self.params.get('termination')
if termination_type == 'insecure':
termination_type = None
state = self.params.get('state')
if state != 'absent' and not service_name:
self.fail_json("If 'state' is not 'absent' then 'service' must be provided")
# We need to do something a little wonky to wait if the user doesn't supply a custom condition
custom_wait = self.params.get('wait') and not self.params.get('wait_condition') and state != 'absent'
if custom_wait:
# Don't use default wait logic in perform_action
self.params['wait'] = False
route_name = self.params.get('name') or service_name
labels = self.params.get('labels')
hostname = self.params.get('hostname')
path = self.params.get('path')
wildcard_policy = self.params.get('wildcard_policy')
port = self.params.get('port')
if termination_type and self.params.get('tls'):
tls_ca_cert = self.params['tls'].get('ca_certificate')
tls_cert = self.params['tls'].get('certificate')
tls_dest_ca_cert = self.params['tls'].get('destination_ca_certificate')
tls_key = self.params['tls'].get('key')
tls_insecure_policy = self.params['tls'].get('insecure_policy')
if tls_insecure_policy == 'disallow':
tls_insecure_policy = None
else:
tls_ca_cert = tls_cert = tls_dest_ca_cert = tls_key = tls_insecure_policy = None
route = {
'apiVersion': 'route.openshift.io/v1',
'kind': 'Route',
'metadata': {
'name': route_name,
'namespace': namespace,
'labels': labels,
},
'spec': {}
}
if state != 'absent':
route['spec'] = self.build_route_spec(
service_name, namespace,
port=port,
wildcard_policy=wildcard_policy,
hostname=hostname,
path=path,
termination_type=termination_type,
tls_insecure_policy=tls_insecure_policy,
tls_ca_cert=tls_ca_cert,
tls_cert=tls_cert,
tls_key=tls_key,
tls_dest_ca_cert=tls_dest_ca_cert,
)
result = self.perform_action(v1_routes, route)
timeout = self.params.get('wait_timeout')
sleep = self.params.get('wait_sleep')
if custom_wait:
success, result['result'], result['duration'] = self._wait_for(v1_routes, route_name, namespace, wait_predicate, sleep, timeout, state)
self.module.exit_json(**result)
def build_route_spec(self, service_name, namespace, port=None, wildcard_policy=None, hostname=None, path=None, termination_type=None,
tls_insecure_policy=None, tls_ca_cert=None, tls_cert=None, tls_key=None, tls_dest_ca_cert=None):
v1_services = self.find_resource('Service', 'v1', fail=True)
try:
target_service = v1_services.get(name=service_name, namespace=namespace)
except NotFoundError:
if not port:
self.module.fail_json(msg="You need to provide the 'port' argument when exposing a non-existent service")
target_service = None
except DynamicApiError as exc:
self.module.fail_json(msg='Failed to retrieve service to be exposed: {0}'.format(exc.body),
error=exc.status, status=exc.status, reason=exc.reason)
except Exception as exc:
self.module.fail_json(msg='Failed to retrieve service to be exposed: {0}'.format(to_native(exc)),
error='', status='', reason='')
route_spec = {
'tls': {},
'to': {
'kind': 'Service',
'name': service_name,
},
'port': {
'targetPort': self.set_port(target_service, port),
},
'wildcardPolicy': wildcard_policy
}
# Want to conditionally add these so we don't overwrite what is automically added when nothing is provided
if termination_type:
route_spec['tls'] = dict(termination=termination_type.capitalize())
if tls_insecure_policy:
if termination_type == 'edge':
route_spec['tls']['insecureEdgeTerminationPolicy'] = tls_insecure_policy.capitalize()
elif termination_type == 'passthrough':
if tls_insecure_policy != 'redirect':
self.module.fail_json("'redirect' is the only supported insecureEdgeTerminationPolicy for passthrough routes")
route_spec['tls']['insecureEdgeTerminationPolicy'] = tls_insecure_policy.capitalize()
elif termination_type == 'reencrypt':
self.module.fail_json("'tls.insecure_policy' is not supported with reencrypt routes")
else:
route_spec['tls']['insecureEdgeTerminationPolicy'] = None
if tls_ca_cert:
if termination_type == 'passthrough':
self.module.fail_json("'tls.ca_certificate' is not supported with passthrough routes")
route_spec['tls']['caCertificate'] = tls_ca_cert
if tls_cert:
if termination_type == 'passthrough':
self.module.fail_json("'tls.certificate' is not supported with passthrough routes")
route_spec['tls']['certificate'] = tls_cert
if tls_key:
if termination_type == 'passthrough':
self.module.fail_json("'tls.key' is not supported with passthrough routes")
route_spec['tls']['key'] = tls_key
if tls_dest_ca_cert:
if termination_type != 'reencrypt':
self.module.fail_json("'destination_certificate' is only valid for reencrypt routes")
route_spec['tls']['destinationCACertificate'] = tls_dest_ca_cert
else:
route_spec['tls'] = None
if hostname:
route_spec['host'] = hostname
if path:
route_spec['path'] = path
return route_spec
def set_port(self, service, port_arg):
if port_arg:
return port_arg
for p in service.spec.ports:
if p.protocol == 'TCP':
if p.name is not None:
return p.name
return p.targetPort
return None
def wait_predicate(route):
if not(route.status and route.status.ingress):
return False
for ingress in route.status.ingress:
match = [x for x in ingress.conditions if x.type == 'Admitted']
if not match:
return False
match = match[0]
if match.status != "True":
return False
return True
def main():
OpenShiftRoute().execute_module()
if __name__ == '__main__':
main()
+2
View File
@@ -0,0 +1,2 @@
kubernetes>=12.0.0
requests-oauthlib
+3
View File
@@ -0,0 +1,3 @@
collections:
- name: kubernetes.core
version: '>=2.1.0,<2.2.0'
+1
View File
@@ -1,2 +1,3 @@
plugins/modules/k8s.py validate-modules:parameter-type-not-in-doc plugins/modules/k8s.py validate-modules:parameter-type-not-in-doc
plugins/modules/k8s.py validate-modules:return-syntax-error plugins/modules/k8s.py validate-modules:return-syntax-error
plugins/modules/openshift_process.py validate-modules:parameter-type-not-in-doc
+1
View File
@@ -1,2 +1,3 @@
plugins/modules/k8s.py validate-modules:parameter-type-not-in-doc plugins/modules/k8s.py validate-modules:parameter-type-not-in-doc
plugins/modules/k8s.py validate-modules:return-syntax-error plugins/modules/k8s.py validate-modules:return-syntax-error
plugins/modules/openshift_process.py validate-modules:parameter-type-not-in-doc
+3
View File
@@ -0,0 +1,3 @@
plugins/modules/k8s.py validate-modules:parameter-type-not-in-doc
plugins/modules/k8s.py validate-modules:return-syntax-error
plugins/modules/openshift_process.py validate-modules:parameter-type-not-in-doc
+1
View File
@@ -1 +1,2 @@
plugins/modules/k8s.py validate-modules:parameter-type-not-in-doc plugins/modules/k8s.py validate-modules:parameter-type-not-in-doc
plugins/modules/openshift_process.py validate-modules:parameter-type-not-in-doc