Compare commits

...
17 Commits
Author SHA1 Message Date
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
Jeff GeerlingandGitHub 6942cd6756 Prepare to publish 0.2.0 release to Galaxy (#39)
* Issue #38: Add version_added to new openshift_auth module.

* Fixes #38: Prepare for 0.2.0 release on Galaxy.
2020-09-24 20:56:18 +00:00
Jeff GeerlingandGitHub b7e341842d Fixes #36: Add contribution guide. (#37)
* Fixes #36: Add contribution guide.

* Pin Ansible release to 2.9.x for OpenShift CI.
2020-09-24 17:37:30 +00:00
Fabian von FeilitzschandGitHub 037f8b1f4f Move k8s_auth library from community.kubernetes to openshift_auth (#33)
* Add openshift_auth module

* add task to print out config

* Attempt to configure auth

* Update molecule/default/tasks/openshift_auth.yml

* fix sanity test and use incluster address for now

* Get integration tests passing locally

* Give test user cluster-level admin permissions

* Use a less verbose resource for testing

* Add alias to k8s_auth for backwards compatibility
2020-09-21 18:15:53 -04:00
Fabian von FeilitzschandGitHub f52d63c83f Don't update image field when we can't manage it (#29)
* If deploymentconfigs are configured to trigger on image stream updates don't try to replace image field

* First pass at parsing the trigger annotation

* First draft of IS idempotence tests

* Found even more not idempotent stuff

* Separate handling of annotation and dc spec

* handle malformed annotations

* refactor incluster integration test to catch last flake

* Add proper DNS01 regex for container names

* fix broken conditional for trigger annotations

* Handle namespace field that is added to trigger

* deduplicate shared code

* Set namespace in incluster script

* Give high permissions to test pod

* Still working on permissions issues in prow

* Fix inventory test

* add namespace to watch

* run in default namespace

* fix recursive call

* Fix ansible collection path for downstream test

* Clone the proper ansible collection
2020-09-17 13:21:00 -04:00
Fabian von FeilitzschandGitHub 1339e2bdf7 combine incluster-integration and separate regular integration scripts (#23)
* combine incluster-integration and separate regular integration scripts

* Fixup Makefile

* make downstream test use venv if docker isn't an option
2020-09-09 14:12:04 -04:00
Andrew BlockandGitHub 80ae2e6b1e Route API Group (#27) 2020-09-08 11:56:19 -04:00
40 changed files with 2555 additions and 210 deletions
+5 -5
View File
@@ -49,9 +49,9 @@ 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 test-sanity TEST_ARGS='--python ${{ matrix.python }}' run: make upstream-test-sanity TEST_ARGS='--python ${{ matrix.python }}'
working-directory: ./ansible_collections/community/okd working-directory: ./ansible_collections/community/okd
### ###
@@ -93,7 +93,7 @@ jobs:
# # OPTIONAL If your integration test requires Python libraries or modules from other collections # # OPTIONAL If your integration test requires Python libraries or modules from other collections
# # Install them like this # # Install them like this
# - name: Install collection dependencies # - name: Install collection dependencies
# run: ansible-galaxy collection install community.kubernetes -p . # run: ansible-galaxy collection install kubernetes.core -p .
# # Run the integration tests # # Run the integration tests
# - name: Run integration test # - name: Run integration test
@@ -111,7 +111,7 @@ jobs:
# fail_ci_if_error: false # 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:
@@ -135,7 +135,7 @@ 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 downstream-test-sanity run: make downstream-test-sanity
working-directory: ./ansible_collections/community/okd working-directory: ./ansible_collections/community/okd
+50
View File
@@ -5,6 +5,56 @@ OKD Collection Release Notes
.. contents:: Topics .. contents:: Topics
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
======
Major Changes
-------------
- openshift_auth - new module (migrated from k8s_auth in community.kubernetes) (https://github.com/ansible-collections/community.okd/pull/33).
Minor Changes
-------------
- Add a contribution guide (https://github.com/ansible-collections/community.okd/pull/37).
- Use the API Group APIVersion for the `Route` object (https://github.com/ansible-collections/community.okd/pull/27).
New Modules
-----------
- openshift_auth - Authenticate to OpenShift clusters which require an explicit login step
v0.1.0 v0.1.0
====== ======
+65
View File
@@ -0,0 +1,65 @@
# Contributing
## Getting Started
General information about setting up your Python environment, testing modules,
Ansible coding styles, and more can be found in the [Ansible Community Guide](
https://docs.ansible.com/ansible/latest/community/index.html).
## Kubernetes Collections
### community.okd
This collection contains modules and plugins contributed and maintained by the Ansible Kubernetes
community.
New modules and plugins developed by the community should be proposed to `community.okd`.
## Submitting Issues
All software has bugs, and the `community.okd` collection is no exception. When you find a bug,
you can help tremendously by [telling us about it](https://github.com/ansible-collections/community.okd/issues/new/choose).
If you should discover that the bug you're trying to file already exists in an issue,
you can help by verifying the behavior of the reported bug with a comment in that
issue, or by reporting any additional information.
## Pull Requests
All modules MUST have integration tests for new features.
Bug fixes for modules that currently have integration tests SHOULD have tests added.
New modules should be submitted to the [community.okd](https://github.com/ansible-collections/community.okd) collection and MUST have integration tests.
Expected test criteria:
* Resource creation under check mode
* Resource creation
* Resource creation again (idempotency) under check mode
* Resource creation again (idempotency)
* Resource modification under check mode
* Resource modification
* Resource modification again (idempotency) under check mode
* Resource modification again (idempotency)
* Resource deletion under check mode
* Resource deletion
* Resource deletion (of a non-existent resource) under check mode
* Resource deletion (of a non-existent resource)
Where modules have multiple parameters we recommend running through the 4-step modification cycle for each parameter the module accepts, as well as a modification cycle where as most, if not all, parameters are modified at the same time.
For general information on running the integration tests see the
[Integration Tests page of the Module Development Guide](https://docs.ansible.com/ansible/devel/dev_guide/testing_integration.html#testing-integration),
especially the section on configuration for cloud tests. For questions about writing tests the Ansible Kubernetes community can be found on Freenode IRC as detailed below.
### Code of Conduct
The `community.okd` collection follows the Ansible project's
[Code of Conduct](https://docs.ansible.com/ansible/devel/community/code_of_conduct.html).
Please read and familiarize yourself with this document.
### IRC
Our IRC channels may require you to register your nickname. If you receive an error when you connect, see
[Freenode's Nickname Registration guide](https://freenode.net/kb/answer/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.
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.
+11 -16
View File
@@ -1,5 +1,5 @@
# Also needs to be updated in galaxy.yml # Also needs to be updated in galaxy.yml
VERSION = 0.1.0 VERSION = 1.0.1
# To run sanity tests in a venv, set SANITY_TEST_ARGS to '--venv' # To run sanity tests in a venv, set SANITY_TEST_ARGS to '--venv'
SANITY_TEST_ARGS ?= --docker --color SANITY_TEST_ARGS ?= --docker --color
@@ -12,27 +12,23 @@ build: clean
ansible-galaxy collection build ansible-galaxy collection build
install-kubernetes-src: install-kubernetes-src:
mkdir -p ansible_collections/community/kubernetes ansible-galaxy collection install -p ansible_collections kubernetes.core
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 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
test-sanity: install test-integration-incluster:
cd ansible_collections/community/okd && ansible-test sanity --exclude ci/ -v $(SANITY_TEST_ARGS) ./ci/incluster_integration.sh
test-integration: install test-sanity: upstream-test-sanity downstream-test-sanity
test-integration: upstream-test-integration downstream-test-integration
upstream-test-integration: install
molecule test molecule test
test-integration-incluster: test-integration-incluster-upstream test-integration-incluster-downstream upstream-test-sanity: install
cd ansible_collections/community/okd && ansible-test sanity --exclude ci/ -v $(SANITY_TEST_ARGS)
test-integration-incluster-upstream:
./ci/incluster_integration_upstream.sh
test-integration-incluster-downstream:
./ci/incluster_integration_downstream.sh
downstream-test-sanity: downstream-test-sanity:
./ci/downstream.sh -s ./ci/downstream.sh -s
@@ -42,4 +38,3 @@ downstream-test-integration:
downstream-build: downstream-build:
./ci/downstream.sh -b ./ci/downstream.sh -b
+19 -5
View File
@@ -1,10 +1,11 @@
# 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.
## Included content ## Included content
@@ -16,8 +17,13 @@ Click on the name of a plugin or module to view that content's documentation:
- [openshift](https://docs.ansible.com/ansible/2.10/collections/community/kubernetes/openshift_inventory.html) - [openshift](https://docs.ansible.com/ansible/2.10/collections/community/kubernetes/openshift_inventory.html)
- **Modules**: - **Modules**:
- [k8s](https://docs.ansible.com/ansible/2.10/collections/community/kubernetes/k8s_inventory.html) - [k8s](https://docs.ansible.com/ansible/2.10/collections/community/kubernetes/k8s_inventory.html)
- [openshift_auth](https://github.com/ansible-collections/community.okd/blob/main/plugins/modules/openshift_auth.py)
- [openshift_process](https://github.com/ansible-collections/community.okd/blob/main/plugins/modules/openshift_process.py)
- [openshift_route](https://github.com/ansible-collections/community.okd/blob/main/plugins/modules/openshift_route.py)
> **Note**: These documentation links currently link to older module versions. For the latest module documentation, please use `ansible-doc` in the CLI. > **Note**: Some of these documentation links currently link to older module versions. For the latest module documentation, please use `ansible-doc` in the CLI.
<!--- ENDREMOVE --->
## Installation and Usage ## Installation and Usage
@@ -33,7 +39,7 @@ 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.1.0 version: 1.0.1
``` ```
### Installing the OpenShift Python Library ### Installing the OpenShift Python Library
@@ -56,10 +62,13 @@ 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.
See [Contributing to community.okd](CONTRIBUTING.md).
The `tests` directory contains configuration for running sanity tests using [`ansible-test`](https://docs.ansible.com/ansible/latest/dev_guide/testing_integration.html). The `tests` directory contains configuration for running sanity tests using [`ansible-test`](https://docs.ansible.com/ansible/latest/dev_guide/testing_integration.html).
You can run the `ansible-test` sanity tests with the command: You can run the `ansible-test` sanity tests with the command:
@@ -97,7 +106,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` and this README's `requirements.yml` example 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`.
@@ -106,6 +119,7 @@ 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
+49
View File
@@ -26,3 +26,52 @@ releases:
- 7-molecule-tests.yml - 7-molecule-tests.yml
- 8-stale-bot.yml - 8-stale-bot.yml
release_date: '2020-09-04' release_date: '2020-09-04'
0.2.0:
changes:
major_changes:
- openshift_auth - new module (migrated from k8s_auth in community.kubernetes)
(https://github.com/ansible-collections/community.okd/pull/33).
minor_changes:
- Add a contribution guide (https://github.com/ansible-collections/community.okd/pull/37).
- Use the API Group APIVersion for the `Route` object (https://github.com/ansible-collections/community.okd/pull/27).
fragments:
- 27-route-api-group.yml
- 33-add-k8s_auth.yml
- 36-contribution-guide.yml
modules:
- description: Authenticate to OpenShift clusters which require an explicit login
step
name: openshift_auth
namespace: ''
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'
@@ -0,0 +1,3 @@
---
minor_changes:
- Use the API Group APIVersion for the `Route` object (https://github.com/ansible-collections/community.okd/pull/27).
+3
View File
@@ -0,0 +1,3 @@
---
major_changes:
- openshift_auth - new module (migrated from k8s_auth in community.kubernetes) (https://github.com/ansible-collections/community.okd/pull/33).
@@ -0,0 +1,3 @@
---
minor_changes:
- Add a contribution guide (https://github.com/ansible-collections/community.okd/pull/37).
@@ -0,0 +1,3 @@
---
major_changes:
- Add openshift_route module for creating routes from services (https://github.com/ansible-collections/community.okd/pull/40).
@@ -0,0 +1,3 @@
---
major_changes:
- Add openshift_process module for template rendering and optional application of rendered resources (https://github.com/ansible-collections/community.okd/pull/44).
@@ -0,0 +1,3 @@
---
minor_changes:
- Released version 1 to Automation Hub as redhat.openshift (https://github.com/ansible-collections/community.okd/issues/51).
@@ -0,0 +1,3 @@
---
bugfixes:
- Generate downstream redhat.openshift documentation (https://github.com/ansible-collections/community.okd/pull/59).
+1 -1
View File
@@ -17,7 +17,7 @@ RUN yum install -y \
&& 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 \ openshift \
ansible \ ansible==2.9.* \
molecule \ molecule \
&& yum clean all \ && yum clean all \
&& rm -rf $HOME/.cache \ && rm -rf $HOME/.cache \
+91 -40
View File
@@ -1,4 +1,4 @@
#!/bin/bash -eu #!/bin/bash -e
# Script to dual-home the upstream and downstream Collection in a single repo # Script to dual-home the upstream and downstream Collection in a single repo
# #
@@ -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="1.0.1"
KEEP_DOWNSTREAM_TMPDIR="${KEEP_DOWNSTREAM_TMPDIR:-''}" KEEP_DOWNSTREAM_TMPDIR="${KEEP_DOWNSTREAM_TMPDIR:-''}"
_build_dir="" _build_dir=""
@@ -31,15 +31,22 @@ 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" for okd_file in ${OKD_sed_files[@]}; do sed -i.bak "s/OKD/OpenShift/g" "${okd_file}"; done
sed -i "s/^VERSION\:/VERSION: ${DOWNSTREAM_VERSION}/" "${_build_dir}/Makefile"
sed -i "s/name\:.*$/name: openshift/" "${_build_dir}/galaxy.yml" sed -i.bak "s/============================/==================================/" "${_build_dir}/CHANGELOG.rst"
sed -i "s/namespace\:.*$/namespace: redhat/" "${_build_dir}/galaxy.yml" sed -i.bak "s/Ansible Galaxy/Automation Hub/" "${_build_dir}/README.md"
sed -i "s/Kubernetes/OpenShift/g" "${_build_dir}/galaxy.yml" sed -i.bak "s/community-okd/redhat-openshift/" "${_build_dir}/Makefile"
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/^VERSION\:/VERSION: ${DOWNSTREAM_VERSION}/" "${_build_dir}/Makefile"
find ${_build_dir} -type f -exec sed -i "s/community\.okd/redhat\.openshift/g" {} \; 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()
@@ -70,9 +77,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,34 +127,62 @@ 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="${_build_dir}/collections/"
local temp_fragments_json="${_tmp_dir}/fragments.json"
local temp_start="${_tmp_dir}/startfile.txt"
local temp_end="${_tmp_dir}/endfile.txt"
local rendered_fragments="./rendereddocfragments.txt"
# 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}"
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 '0,/ENDREMOVE/d' "${module_py}" > "${temp_end}"
cat "${temp_start}" "${rendered_fragments}" "${temp_end}" > "${module_py}"
cat "${module_py}"
done
rm -f "${rendered_fragments}"
rm -fr "${install_collections_dir}"
popd
}
f_install_kubernetes_core()
{
f_log_info "${FUNCNAME[0]}"
local install_collections_dir="${_tmp_dir}/ansible_collections" local install_collections_dir="${_tmp_dir}/ansible_collections"
mkdir -p "${community_k8s_tmpdir}"
pushd "${_tmp_dir}" pushd "${_tmp_dir}"
# curl -L \ ansible-galaxy collection install -p "${install_collections_dir}" kubernetes.core
# https://github.com/ansible-collections/community.kubernetes/archive/main.tar.gz \
# | 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/maxamillion/community.kubernetes "${community_k8s_tmpdir}"
pushd "${community_k8s_tmpdir}"
git checkout downstream/fix_collection_name
make downstream-build
ansible-galaxy collection install -p "${install_collections_dir}" "${community_k8s_tmpdir}"/kubernetes-core-*.tar.gz
popd
popd popd
} }
@@ -156,6 +200,7 @@ f_common_steps()
f_prep f_prep
f_create_collection_dir_structure f_create_collection_dir_structure
f_text_sub f_text_sub
f_handle_doc_fragments_workaround
} }
# Run the test sanity scanerio # Run the test sanity scanerio
@@ -163,14 +208,20 @@ 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 f_install_kubernetes_core
pushd "${_build_dir}" || return pushd "${_build_dir}" || return
ansible-galaxy collection build ansible-galaxy collection build
f_log_info "SANITY TEST PWD: ${PWD}" f_log_info "SANITY TEST PWD: ${PWD}"
## Can't do this because the upstream community.kubernetes dependency logic ## Can't do this because the upstream kubernetes.core dependency logic
## is bound as a Makefile dep to the test-sanity target ## is bound as a Makefile dep to the test-sanity target
#SANITY_TEST_ARGS="--docker --color --python 3.6" make test-sanity #SANITY_TEST_ARGS="--docker --color --python 3.6" make test-sanity
ansible-test sanity --docker -v --exclude ci/ --color --python 3.6 # Run tests in docker if available, venv otherwise
if command -v docker &> /dev/null
then
ansible-test sanity --docker -v --exclude ci/ --color --python 3.6
else
ansible-test sanity --venv -v --exclude ci/ --color --python 3.6
fi
popd || return popd || return
f_cleanup f_cleanup
} }
@@ -180,10 +231,10 @@ 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 f_install_kubernetes_core
pushd "${_build_dir}" || return pushd "${_build_dir}" || return
f_log_info "INTEGRATION TEST WD: ${PWD}" f_log_info "INTEGRATION TEST WD: ${PWD}"
make test-integration-incluster OVERRIDE_COLLECTION_PATH="${_tmp_dir}" molecule test
popd || return popd || return
f_cleanup f_cleanup
} }
@@ -197,7 +248,7 @@ f_build_option()
f_log_info "BUILD WD: ${PWD}" f_log_info "BUILD WD: ${PWD}"
# FIXME # FIXME
# This doesn't work because we end up either recursively curl'ing # This doesn't work because we end up either recursively curl'ing
# community.kubernetes and redoing the text replacement over and over # kubernetes.core and redoing the text replacement over and over
# #
# make build # make build
ansible-galaxy collection build ansible-galaxy collection build
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env python
import json
import yaml
import sys
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', '')
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")
@@ -2,6 +2,8 @@
set -x set -x
NAMESPACE=${NAMESPACE:-default}
# IMAGE_FORMAT is in the form $registry/$org/$image:$$component, ie # IMAGE_FORMAT is in the form $registry/$org/$image:$$component, ie
# quay.io/openshift/release:$component # quay.io/openshift/release:$component
# To test with your own image, build and push the test image # To test with your own image, build and push the test image
@@ -14,6 +16,15 @@ eval IMAGE=$IMAGE_FORMAT
PULL_POLICY=${PULL_POLICY:-IfNotPresent} PULL_POLICY=${PULL_POLICY:-IfNotPresent}
if ! oc get namespace $NAMESPACE
then
oc create namespace $NAMESPACE
fi
oc project $NAMESPACE
oc adm policy add-cluster-role-to-user cluster-admin -z default
oc adm policy who-can create projectrequests
echo "Deleting test job if it exists" echo "Deleting test job if it exists"
oc delete job molecule-integration-test --wait --ignore-not-found oc delete job molecule-integration-test --wait --ignore-not-found
@@ -40,22 +51,36 @@ spec:
parallelism: 1 parallelism: 1
EOF EOF
function wait_for_success { function check_success {
oc wait --for=condition=complete job/molecule-integration-test --timeout 5m oc wait --for=condition=complete job/molecule-integration-test --timeout 5s -n $NAMESPACE \
echo "Molecule integration tests ran successfully" && oc logs job/molecule-integration-test \
exit 0 && echo "Molecule integration tests ran successfully" \
&& return 0
return 1
} }
function wait_for_failure { function check_failure {
oc wait --for=condition=failed job/molecule-integration-test --timeout 5m 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..." \
exit 1 && return 0
return 1
} }
# Ensure the child processes are killed runtime="15 minute"
trap 'kill -SIGTERM 0' SIGINT EXIT endtime=$(date -ud "$runtime" +%s)
echo "Waiting for test job to complete" echo "Waiting for test job to complete"
wait_for_success & while [[ $(date -u +%s) -le $endtime ]]
wait_for_failure do
if check_success
then
exit 0
elif check_failure
then
exit 1
fi
sleep 10
done
exit 1
-61
View File
@@ -1,61 +0,0 @@
#!/bin/bash
set -x
# IMAGE_FORMAT is in the form $registry/$org/$image:$$component, ie
# quay.io/openshift/release:$component
# To test with your own image, build and push the test image
# (using the Dockerfile in ci/Dockerfile)
# and set the IMAGE_FORMAT environment variable so that it properly
# resolves to your image. For example, quay.io/mynamespace/$component
# would resolve to quay.io/mynamespace/molecule-test-runner
component='molecule-test-runner'
eval IMAGE=$IMAGE_FORMAT
PULL_POLICY=${PULL_POLICY:-IfNotPresent}
echo "Deleting test job if it exists"
oc delete job molecule-integration-test --wait --ignore-not-found
echo "Creating molecule test job"
cat << EOF | oc create -f -
---
apiVersion: batch/v1
kind: Job
metadata:
name: molecule-integration-test
spec:
template:
spec:
containers:
- name: test-runner
image: ${IMAGE}
imagePullPolicy: ${PULL_POLICY}
command:
- make
- downstream-test-integration
restartPolicy: Never
backoffLimit: 2
completions: 1
parallelism: 1
EOF
function wait_for_success {
oc wait --for=condition=complete job/molecule-integration-test --timeout 5m
echo "Molecule integration tests ran successfully"
exit 0
}
function wait_for_failure {
oc wait --for=condition=failed job/molecule-integration-test --timeout 5m
oc logs job/molecule-integration-test
echo "Molecule integration tests failed, see logs for more information..."
exit 1
}
# Ensure the child processes are killed
trap 'kill -SIGTERM 0' SIGINT EXIT
echo "Waiting for test job to complete"
wait_for_success &
wait_for_failure
+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: '>=1.1.1'
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.1.0 version: 1.0.1
+66 -29
View File
@@ -5,6 +5,8 @@
gather_facts: no gather_facts: no
vars: vars:
ansible_python_interpreter: '{{ virtualenv_interpreter }}' ansible_python_interpreter: '{{ virtualenv_interpreter }}'
vars_files:
- vars/main.yml
tasks: tasks:
# OpenShift Resources # OpenShift Resources
- name: Create a project - name: Create a project
@@ -22,41 +24,76 @@
- name: Create deployment config - name: Create deployment config
community.okd.k8s: community.okd.k8s:
state: present state: present
inline: &dc name: hello-world
apiVersion: v1 namespace: testing
kind: DeploymentConfig definition: '{{ okd_dc_template }}'
metadata:
name: hello-world
labels:
app: galaxy
service: hello-world
namespace: testing
spec:
template:
metadata:
labels:
app: galaxy
service: hello-world
spec:
containers:
- name: hello-world
image: python
command:
- python
- '-m'
- http.server
env:
- name: TEST
value: test
replicas: 1
strategy:
type: Recreate
wait: yes wait: yes
wait_condition: wait_condition:
type: Available type: Available
status: True status: True
vars:
k8s_pod_name: hello-world
k8s_pod_image: python
k8s_pod_command:
- python
- '-m'
- http.server
k8s_pod_env:
- name: TEST
value: test
okd_dc_triggers:
- type: ConfigChange
register: output register: output
- name: Show output - name: Show output
debug: debug:
var: output var: output
- vars:
image: docker.io/python
image_name: python
image_tag: latest
k8s_pod_image: python
k8s_pod_command:
- python
- '-m'
- http.server
namespace: idempotence-testing
block:
- name: Create a namespace
community.okd.k8s:
name: '{{ namespace }}'
kind: Namespace
api_version: v1
- name: Create imagestream
community.okd.k8s:
namespace: '{{ namespace }}'
definition: '{{ okd_imagestream_template }}'
- name: Create DeploymentConfig to reference ImageStream
community.okd.k8s:
name: '{{ k8s_pod_name }}'
namespace: '{{ namespace }}'
definition: '{{ okd_dc_template }}'
vars:
k8s_pod_name: is-idempotent-dc
- name: Create Deployment to reference ImageStream
community.okd.k8s:
name: '{{ k8s_pod_name }}'
namespace: '{{ namespace }}'
definition: '{{ k8s_deployment_template | combine(metadata) }}'
vars:
k8s_pod_annotations:
"alpha.image.policy.openshift.io/resolve-names": "*"
k8s_pod_name: is-idempotent-deployment
annotation:
- from:
kind: ImageStreamTag
name: "{{ image_name }}:{{ image_tag}}}"
fieldPath: 'spec.template.spec.containers[?(@.name=="{{ k8s_pod_name }}")].image}'
metadata:
metadata:
annotations:
image.openshift.io/triggers: '{{ annotation | to_json }}'
+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
@@ -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: ''
+4 -1
View File
@@ -9,6 +9,9 @@ platforms:
- k8s - k8s
provisioner: provisioner:
name: ansible name: ansible
log: true
options:
vvv: True
config_options: config_options:
inventory: inventory:
enable_plugins: community.okd.openshift enable_plugins: community.okd.openshift
@@ -26,7 +29,7 @@ provisioner:
playbook_namespace: molecule-tests playbook_namespace: molecule-tests
env: env:
ANSIBLE_FORCE_COLOR: 'true' ANSIBLE_FORCE_COLOR: 'true'
ANSIBLE_COLLECTIONS_PATHS: ${MOLECULE_PROJECT_DIRECTORY} ANSIBLE_COLLECTIONS_PATHS: ${OVERRIDE_COLLECTION_PATH:-$MOLECULE_PROJECT_DIRECTORY}
verifier: verifier:
name: ansible name: ansible
lint: | lint: |
+43
View File
@@ -15,3 +15,46 @@
virtualenv: "{{ virtualenv }}" virtualenv: "{{ virtualenv }}"
virtualenv_command: "{{ virtualenv_command }}" virtualenv_command: "{{ virtualenv_command }}"
virtualenv_site_packages: no virtualenv_site_packages: no
- name: 'Configure htpasswd secret (username: test, password: testing123)'
community.okd.k8s:
definition:
apiVersion: v1
kind: Secret
metadata:
name: htpass-secret
namespace: openshift-config
stringData:
htpasswd: "test:$2y$05$zgjczyp96jCIp//CGmnWiefhd7G3l54IdsZoV4IwA1UWtd04L0lE2"
- name: Configure htpasswd identity provider
community.okd.k8s:
definition:
apiVersion: config.openshift.io/v1
kind: OAuth
metadata:
name: cluster
spec:
identityProviders:
- name: htpasswd_provider
mappingMethod: claim
type: HTPasswd
htpasswd:
fileData:
name: htpass-secret
- name: Create ClusterRoleBinding for test user
community.okd.k8s:
definition:
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: test-cluster-reader
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: cluster-reader
subjects:
- apiGroup: rbac.authorization.k8s.io
kind: User
name: test
+51
View File
@@ -0,0 +1,51 @@
---
- vars:
# TODO(fabianvf) Get this parameter working locally as well
openshift_host: 'https://kubernetes.default.svc'
block:
- name: Log in (obtain access token)
community.okd.openshift_auth:
username: test
password: testing123
host: '{{ openshift_host }}'
verify_ssl: false
register: openshift_auth_results
- name: Get the test User
kubernetes.core.k8s_info:
api_key: "{{ openshift_auth_results.openshift_auth.api_key }}"
host: '{{ openshift_host }}'
verify_ssl: false
kind: User
api_version: user.openshift.io/v1
name: test
register: user_result
- name: assert that the user was found
assert:
that: (user_result.resources | length) == 1
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 }}"
host: '{{ openshift_host }}'
verify_ssl: false
- name: Get the test user
kubernetes.core.k8s_info:
api_key: "{{ openshift_auth_results.openshift_auth.api_key }}"
host: '{{ openshift_host }}'
verify_ssl: false
kind: User
name: test
api_version: user.openshift.io/v1
register: failed_user_result
ignore_errors: yes
# TODO(fabianvf) determine why token is not being rejected, maybe add more info to return
# - name: assert that the user was not found
# assert:
# that: (failed_user_result.resources | length) == 0
@@ -0,0 +1,164 @@
---
- 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
+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
+94
View File
@@ -0,0 +1,94 @@
---
k8s_pod_annotations: {}
k8s_pod_metadata:
labels:
app: '{{ k8s_pod_name }}'
annotations: '{{ k8s_pod_annotations }}'
k8s_pod_spec:
serviceAccount: "{{ k8s_pod_service_account }}"
containers:
- image: "{{ k8s_pod_image }}"
imagePullPolicy: Always
name: "{{ k8s_pod_name }}"
command: "{{ k8s_pod_command }}"
readinessProbe:
initialDelaySeconds: 15
exec:
command:
- /bin/true
resources: "{{ k8s_pod_resources }}"
ports: "{{ k8s_pod_ports }}"
env: "{{ k8s_pod_env }}"
k8s_pod_service_account: default
k8s_pod_resources:
limits:
cpu: "100m"
memory: "100Mi"
k8s_pod_command: []
k8s_pod_ports: []
k8s_pod_env: []
k8s_pod_template:
metadata: "{{ k8s_pod_metadata }}"
spec: "{{ k8s_pod_spec }}"
k8s_deployment_spec:
template: '{{ k8s_pod_template }}'
selector:
matchLabels:
app: '{{ k8s_pod_name }}'
replicas: 1
k8s_deployment_template:
apiVersion: apps/v1
kind: Deployment
spec: '{{ k8s_deployment_spec }}'
okd_dc_triggers:
- type: ConfigChange
- type: ImageChange
imageChangeParams:
automatic: true
containerNames:
- '{{ k8s_pod_name }}'
from:
kind: ImageStreamTag
name: '{{ image_name }}:{{ image_tag }}'
okd_dc_spec:
template: '{{ k8s_pod_template }}'
triggers: '{{ okd_dc_triggers }}'
replicas: 1
strategy:
type: Recreate
okd_dc_template:
apiVersion: v1
kind: DeploymentConfig
spec: '{{ okd_dc_spec }}'
okd_imagestream_template:
apiVersion: image.openshift.io/v1
kind: ImageStream
metadata:
name: '{{ image_name }}'
spec:
lookupPolicy:
local: true
tags:
- annotations: null
from:
kind: DockerImage
name: '{{ image }}'
name: '{{ image_tag }}'
referencePolicy:
type: Source
image_tag: latest
+19
View File
@@ -59,3 +59,22 @@
virtualenv_site_packages: no virtualenv_site_packages: no
- import_tasks: tasks/validate_not_installed.yml - import_tasks: tasks/validate_not_installed.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
+1 -1
View File
@@ -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'
+2 -2
View File
@@ -113,7 +113,7 @@ 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
try: try:
from openshift.dynamic.exceptions import DynamicApiError from openshift.dynamic.exceptions import DynamicApiError
@@ -151,7 +151,7 @@ class InventoryModule(K8sInventoryModule):
self.get_routes_for_namespace(client, name, namespace) self.get_routes_for_namespace(client, name, namespace)
def get_routes_for_namespace(self, client, name, namespace): def get_routes_for_namespace(self, client, name, namespace):
v1_route = client.resources.get(api_version='v1', kind='Route') v1_route = client.resources.get(api_version='route.openshift.io/v1', kind='Route')
try: try:
obj = v1_route.get(namespace=namespace) obj = v1_route.get(namespace=namespace)
except DynamicApiError as exc: except DynamicApiError as exc:
+125 -22
View File
@@ -6,15 +6,9 @@
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',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = ''' DOCUMENTATION = '''
module: k8s module: k8s
@@ -36,10 +30,10 @@ description:
- 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_state_options
- community.kubernetes.k8s_name_options - kubernetes.core.k8s_name_options
- community.kubernetes.k8s_resource_options - kubernetes.core.k8s_resource_options
- community.kubernetes.k8s_auth_options - kubernetes.core.k8s_auth_options
notes: notes:
- If your OpenShift Python library is not 0.9.0 or newer and you are trying to - If your OpenShift Python library is not 0.9.0 or newer and you are trying to
@@ -112,8 +106,8 @@ options:
description: description:
- The value of the reason field in your desired condition - 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. - 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 - The possible reasons in a condition are specific to each resource type in Kubernetes.
for a given resource to see possible choices. See the API documentation of the status field for a given resource to see possible choices.
type: dict type: dict
validate: validate:
description: description:
@@ -264,13 +258,17 @@ result:
type: int type: int
sample: 48 sample: 48
''' '''
# ENDREMOVE (downstream)
import re
import operator
import traceback import traceback
from functools import reduce
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.raw import KubernetesRawModule
HAS_KUBERNETES_COLLECTION = True HAS_KUBERNETES_COLLECTION = True
except ImportError as e: except ImportError as e:
HAS_KUBERNETES_COLLECTION = False HAS_KUBERNETES_COLLECTION = False
@@ -279,18 +277,22 @@ except ImportError as e:
from ansible.module_utils.basic import AnsibleModule as KubernetesRawModule from ansible.module_utils.basic import AnsibleModule as KubernetesRawModule
try: try:
import yaml
from openshift.dynamic.exceptions import DynamicApiError, NotFoundError, ForbiddenError from openshift.dynamic.exceptions import DynamicApiError, NotFoundError, ForbiddenError
except ImportError: except ImportError:
# Exceptions handled in common # Exceptions handled in common
pass pass
TRIGGER_ANNOTATION = 'image.openshift.io/triggers'
TRIGGER_CONTAINER = re.compile(r"(?P<path>.*)\[((?P<index>[0-9]+)|\?\(@\.name==[\"'\\]*(?P<name>[a-z0-9]([-a-z0-9]*[a-z0-9])?))")
class OKDRawModule(KubernetesRawModule): class OKDRawModule(KubernetesRawModule):
def __init__(self): 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)
) )
@@ -301,17 +303,118 @@ class OKDRawModule(KubernetesRawModule):
name = definition['metadata'].get('name') name = definition['metadata'].get('name')
namespace = definition['metadata'].get('namespace') namespace = definition['metadata'].get('namespace')
if definition['kind'] in ['Project', 'ProjectRequest'] and state != 'absent': if state != 'absent':
if resource.kind in ['Project', 'ProjectRequest']:
try:
resource.get(name, namespace)
except (NotFoundError, ForbiddenError):
return self.create_project_request(definition)
except DynamicApiError as exc:
self.fail_json(msg='Failed to retrieve requested object: {0}'.format(exc.body),
error=exc.status, status=exc.status, reason=exc.reason)
try: try:
resource.get(name, namespace) existing = resource.get(name=name, namespace=namespace).to_dict()
except (NotFoundError, ForbiddenError): except Exception:
return self.create_project_request(definition) existing = None
except DynamicApiError as exc:
self.fail_json(msg='Failed to retrieve requested object: {0}'.format(exc.body), if existing:
error=exc.status, status=exc.status, reason=exc.reason) if resource.kind == 'DeploymentConfig':
if definition.get('spec', {}).get('triggers'):
definition = self.resolve_imagestream_triggers(existing, definition)
elif existing['metadata'].get('annotations', {}).get(TRIGGER_ANNOTATION):
definition = self.resolve_imagestream_trigger_annotation(existing, definition)
return super(OKDRawModule, self).perform_action(resource, definition) return super(OKDRawModule, self).perform_action(resource, definition)
@staticmethod
def get_index(desired, objects, keys):
""" Iterates over keys, returns the first object from objects where the value of the key
matches the value in desired
"""
for i, item in enumerate(objects):
if item and all([desired.get(key, True) == item.get(key, False) for key in keys]):
return i
def resolve_imagestream_trigger_annotation(self, existing, definition):
def get_from_fields(d, fields):
try:
return reduce(operator.getitem, fields, d)
except Exception:
return None
def set_from_fields(d, fields, value):
get_from_fields(d, fields[:-1])[fields[-1]] = value
if TRIGGER_ANNOTATION in definition['metadata'].get('annotations', {}).keys():
triggers = yaml.safe_load(definition['metadata']['annotations'][TRIGGER_ANNOTATION] or '[]')
else:
triggers = yaml.safe_load(existing['metadata'].get('annotations', '{}').get(TRIGGER_ANNOTATION, '[]'))
if not isinstance(triggers, list):
return definition
for trigger in triggers:
if trigger.get('fieldPath'):
parsed = self.parse_trigger_fieldpath(trigger['fieldPath'])
path = parsed.get('path', '').split('.')
if path:
existing_containers = get_from_fields(existing, path)
new_containers = get_from_fields(definition, path)
if parsed.get('name'):
existing_index = self.get_index({'name': parsed['name']}, existing_containers, ['name'])
new_index = self.get_index({'name': parsed['name']}, new_containers, ['name'])
elif parsed.get('index') is not None:
existing_index = new_index = int(parsed['index'])
else:
existing_index = new_index = None
if existing_index is not None and new_index is not None:
if existing_index < len(existing_containers) and new_index < len(new_containers):
set_from_fields(definition, path + [new_index, 'image'], get_from_fields(existing, path + [existing_index, 'image']))
return definition
def resolve_imagestream_triggers(self, existing, definition):
existing_triggers = existing.get('spec', {}).get('triggers')
new_triggers = definition['spec']['triggers']
existing_containers = existing.get('spec', {}).get('template', {}).get('spec', {}).get('containers', [])
new_containers = definition.get('spec', {}).get('template', {}).get('spec', {}).get('containers', [])
for i, trigger in enumerate(new_triggers):
if trigger.get('type') == 'ImageChange' and trigger.get('imageChangeParams'):
names = trigger['imageChangeParams'].get('containerNames', [])
for name in names:
old_container_index = self.get_index({'name': name}, existing_containers, ['name'])
new_container_index = self.get_index({'name': name}, new_containers, ['name'])
if old_container_index is not None and new_container_index is not None:
image = existing['spec']['template']['spec']['containers'][old_container_index]['image']
definition['spec']['template']['spec']['containers'][new_container_index]['image'] = image
existing_index = self.get_index(trigger['imageChangeParams'],
[x.get('imageChangeParams') for x in existing_triggers],
['containerNames'])
if existing_index is not None:
existing_image = existing_triggers[existing_index].get('imageChangeParams', {}).get('lastTriggeredImage')
if existing_image:
definition['spec']['triggers'][i]['imageChangeParams']['lastTriggeredImage'] = existing_image
existing_from = existing_triggers[existing_index].get('imageChangeParams', {}).get('from', {})
new_from = trigger['imageChangeParams'].get('from', {})
existing_namespace = existing_from.get('namespace')
existing_name = existing_from.get('name', False)
new_name = new_from.get('name', True)
add_namespace = existing_namespace and 'namespace' not in new_from.keys() and existing_name == new_name
if add_namespace:
definition['spec']['triggers'][i]['imageChangeParams']['from']['namespace'] = existing_from['namespace']
return definition
def parse_trigger_fieldpath(self, expression):
parsed = TRIGGER_CONTAINER.search(expression).groupdict()
if parsed.get('index'):
parsed['index'] = int(parsed['index'])
return parsed
def create_project_request(self, definition): def create_project_request(self, definition):
definition['kind'] = 'ProjectRequest' definition['kind'] = 'ProjectRequest'
result = {'changed': False, 'result': {}} result = {'changed': False, 'result': {}}
+1
View File
@@ -0,0 +1 @@
openshift_auth.py
+363
View File
@@ -0,0 +1,363 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2018, KubeVirt Team <@kubevirt>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r'''
module: openshift_auth
short_description: Authenticate to OpenShift clusters which require an explicit login step
version_added: "0.2.0"
author:
- KubeVirt Team (@kubevirt)
- Fabian von Feilitzsch (@fabianvf)
description:
- This module handles authenticating to OpenShift clusters requiring I(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 C(k8s) module (and other
resource–specific modules) by utilizing the C(host), C(username) and C(password) parameters. Please
consult your preferred module's documentation for more details.
options:
state:
description:
- If set to I(present) connect to the API server using the URL specified in C(host) and attempt to log in.
- If set to I(absent) attempt to log out by revoking the authentication token specified in C(api_key).
default: present
choices:
- present
- absent
type: str
host:
description:
- Provide a URL for accessing the API server.
required: true
type: str
username:
description:
- Provide a username for authenticating with the API server.
type: str
password:
description:
- Provide a password for authenticating with the API server.
type: str
ca_cert:
description:
- "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."
aliases: [ ssl_ca_cert ]
type: path
validate_certs:
description:
- "Whether or not to verify the API server's SSL certificates."
type: bool
default: true
aliases: [ verify_ssl ]
api_key:
description:
- When C(state) is set to I(absent), this specifies the token to revoke.
type: str
requirements:
- python >= 2.7
- urllib3
- requests
- requests-oauthlib
'''
EXAMPLES = r'''
- 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 }}"
'''
# Returned value names need to match k8s modules parameter names, to make it
# easy to pass returned values of openshift_auth to other k8s modules.
# Discussion: https://github.com/ansible/ansible/pull/50807#discussion_r248827899
RETURN = r'''
openshift_auth:
description: OpenShift authentication facts.
returned: success
type: complex
contains:
api_key:
description: Authentication token.
returned: success
type: str
host:
description: URL for accessing the API server.
returned: success
type: str
ca_cert:
description: Path to a CA certificate file used to verify connection to the API server.
returned: success
type: str
validate_certs:
description: "Whether or not to verify the API server's SSL certificates."
returned: success
type: bool
username:
description: Username for authenticating with the API server.
returned: success
type: str
k8s_auth:
description: Same as returned openshift_auth. Kept only for backwards compatibility
returned: success
type: complex
contains:
api_key:
description: Authentication token.
returned: success
type: str
host:
description: URL for accessing the API server.
returned: success
type: str
ca_cert:
description: Path to a CA certificate file used to verify connection to the API server.
returned: success
type: str
validate_certs:
description: "Whether or not to verify the API server's SSL certificates."
returned: success
type: bool
username:
description: Username for authenticating with the API server.
returned: success
type: str
'''
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.six.moves.urllib_parse import urlparse, parse_qs, urlencode
# 3rd party imports
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
try:
from requests_oauthlib import OAuth2Session
HAS_REQUESTS_OAUTH = True
except ImportError:
HAS_REQUESTS_OAUTH = False
try:
from urllib3.util import make_headers
HAS_URLLIB3 = True
except ImportError:
HAS_URLLIB3 = False
K8S_AUTH_ARG_SPEC = {
'state': {
'default': 'present',
'choices': ['present', 'absent'],
},
'host': {'required': True},
'username': {},
'password': {'no_log': True},
'ca_cert': {'type': 'path', 'aliases': ['ssl_ca_cert']},
'validate_certs': {
'type': 'bool',
'default': True,
'aliases': ['verify_ssl']
},
'api_key': {'no_log': True},
}
class OpenShiftAuthModule(AnsibleModule):
def __init__(self):
AnsibleModule.__init__(
self,
argument_spec=K8S_AUTH_ARG_SPEC,
required_if=[
('state', 'present', ['username', 'password']),
('state', 'absent', ['api_key']),
]
)
if not HAS_REQUESTS:
self.fail("This module requires the python 'requests' package. Try `pip install requests`.")
if not HAS_REQUESTS_OAUTH:
self.fail("This module requires the python 'requests-oauthlib' package. Try `pip install requests-oauthlib`.")
if not HAS_URLLIB3:
self.fail("This module requires the python 'urllib3' package. Try `pip install urllib3`.")
def execute_module(self):
state = self.params.get('state')
verify_ssl = self.params.get('validate_certs')
ssl_ca_cert = self.params.get('ca_cert')
self.auth_username = self.params.get('username')
self.auth_password = self.params.get('password')
self.auth_api_key = self.params.get('api_key')
self.con_host = self.params.get('host')
# python-requests takes either a bool or a path to a ca file as the 'verify' param
if verify_ssl and ssl_ca_cert:
self.con_verify_ca = ssl_ca_cert # path
else:
self.con_verify_ca = verify_ssl # bool
# Get needed info to access authorization APIs
self.openshift_discover()
if state == 'present':
new_api_key = self.openshift_login()
result = dict(
host=self.con_host,
validate_certs=verify_ssl,
ca_cert=ssl_ca_cert,
api_key=new_api_key,
username=self.auth_username,
)
else:
self.openshift_logout()
result = dict()
# return k8s_auth as well for backwards compatibility
self.exit_json(changed=False, openshift_auth=result, k8s_auth=result)
def openshift_discover(self):
url = '{0}/.well-known/oauth-authorization-server'.format(self.con_host)
ret = requests.get(url, verify=self.con_verify_ca)
if ret.status_code != 200:
self.fail_request("Couldn't find OpenShift's OAuth API", method='GET', url=url,
reason=ret.reason, status_code=ret.status_code)
try:
oauth_info = ret.json()
self.openshift_auth_endpoint = oauth_info['authorization_endpoint']
self.openshift_token_endpoint = oauth_info['token_endpoint']
except Exception:
self.fail_json(msg="Something went wrong discovering OpenShift OAuth details.",
exception=traceback.format_exc())
def openshift_login(self):
os_oauth = OAuth2Session(client_id='openshift-challenging-client')
authorization_url, state = os_oauth.authorization_url(self.openshift_auth_endpoint,
state="1", code_challenge_method='S256')
auth_headers = make_headers(basic_auth='{0}:{1}'.format(self.auth_username, self.auth_password))
# Request authorization code using basic auth credentials
ret = os_oauth.get(
authorization_url,
headers={'X-Csrf-Token': state, 'authorization': auth_headers.get('authorization')},
verify=self.con_verify_ca,
allow_redirects=False
)
if ret.status_code != 302:
self.fail_request("Authorization failed.", method='GET', url=authorization_url,
reason=ret.reason, status_code=ret.status_code)
# In here we have `code` and `state`, I think `code` is the important one
qwargs = {}
for k, v in parse_qs(urlparse(ret.headers['Location']).query).items():
qwargs[k] = v[0]
qwargs['grant_type'] = 'authorization_code'
# Using authorization code given to us in the Location header of the previous request, request a token
ret = os_oauth.post(
self.openshift_token_endpoint,
headers={
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
# This is just base64 encoded 'openshift-challenging-client:'
'Authorization': 'Basic b3BlbnNoaWZ0LWNoYWxsZW5naW5nLWNsaWVudDo='
},
data=urlencode(qwargs),
verify=self.con_verify_ca
)
if ret.status_code != 200:
self.fail_request("Failed to obtain an authorization token.", method='POST',
url=self.openshift_token_endpoint,
reason=ret.reason, status_code=ret.status_code)
return ret.json()['access_token']
def openshift_logout(self):
url = '{0}/apis/oauth.openshift.io/v1/oauthaccesstokens/{1}'.format(self.con_host, self.auth_api_key)
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer {0}'.format(self.auth_api_key)
}
json = {
"apiVersion": "oauth.openshift.io/v1",
"kind": "DeleteOptions"
}
requests.delete(url, headers=headers, json=json, verify=self.con_verify_ca)
# Ignore errors, the token will time out eventually anyway
def fail(self, msg=None):
self.fail_json(msg=msg)
def fail_request(self, msg, **kwargs):
req_info = {}
for k, v in kwargs.items():
req_info['req_' + k] = v
self.fail_json(msg=msg, **req_info)
def main():
module = OpenShiftAuthModule()
try:
module.execute_module()
except Exception as e:
module.fail_json(msg=str(e), exception=traceback.format_exc())
if __name__ == '__main__':
main()
+389
View File
@@ -0,0 +1,389 @@
#!/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 >= 2.7"
- "openshift >= 0.11.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, 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 openshift.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.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 = self.get_api_client()
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()
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'] = 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()
+545
View File
@@ -0,0 +1,545 @@
#!/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 >= 2.7"
- "openshift >= 0.11.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, 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 openshift.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.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'),
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 = self.get_api_client()
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()
+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
+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