Cleanup GitHub workflows (#655)

* Cleanup gha

* test by removing matrix excludes

* Rename sanity tests

* trigger integration tests

* Fix ansible-lint workflow

* Fix concurrency

* Add ansible-lint config

* Add ansible-lint config

* Fix integration and lint issues

* integration wf

* fix yamllint issues

* fix yamllint issues

* update readme and add ignore-2.16.txt

* fix ansible-doc

* Add version

* Use /dev/random to generate random data

The GHA environment has difficultly generating entropy. Trying to read
from /dev/urandom just blocks forever. We don't care if the random data
is cryptographically secure; it's just garbage data for the test. Read
from /dev/random, instead. This is only used during the k8s_copy test
target.

This also removes the custom test module that was being used to generate
the files. It's not worth maintaining this for two task that can be
replaced with some simple command/shell tasks.

* Fix saniry errors

* test github_action fix

* Address review comments

* Remove default types

* review comments

* isort fixes

* remove tags

* Add setuptools to venv

* Test gh changes

* update changelog

* update ignore-2.16

* Fix indentation in inventory plugin example

* Update .github/workflows/integration-tests.yaml

* Update integration-tests.yaml

---------

Co-authored-by: Mike Graves <mgraves@redhat.com>
Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>
This commit is contained in:
GomathiselviS
2023-11-10 10:33:40 -05:00
committed by GitHub
parent 9e9962bc6c
commit b066a2dda3
80 changed files with 496 additions and 680 deletions

6
.ansible-lint Normal file
View File

@@ -0,0 +1,6 @@
---
profile: production
exclude_paths:
- tests/integration
- tests/sanity

21
.github/workflows/changelog.yaml vendored Normal file
View File

@@ -0,0 +1,21 @@
---
name: Changelog
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
on:
pull_request:
types:
- opened
- reopened
- labeled
- unlabeled
- synchronize
branches:
- main
- stable-*
jobs:
changelog:
uses: ansible-network/github_actions/.github/workflows/changelog.yml@main

View File

@@ -1,313 +0,0 @@
name: CI
concurrency:
group: ${{ github.head_ref }}
cancel-in-progress: true
on:
pull_request:
types:
- opened
- reopened
- labeled
- unlabeled
- synchronize
branches:
- main
- stable-*
tags:
- '*'
jobs:
changelog:
uses: ansible-network/github_actions/.github/workflows/changelog.yml@main
galaxy_importer:
uses: ansible-network/github_actions/.github/workflows/galaxy_importer.yml@main
linters:
uses: ansible-network/github_actions/.github/workflows/tox-linters.yml@main
sanity:
uses: ansible-network/github_actions/.github/workflows/sanity.yml@main
with:
matrix_include: "[]"
matrix_exclude: >-
[
{
"ansible-version": "stable-2.9"
},
{
"ansible-version": "stable-2.12",
"python-version": "3.7"
},
{
"ansible-version": "stable-2.12",
"python-version": "3.11"
},
{
"ansible-version": "stable-2.13",
"python-version": "3.7"
},
{
"ansible-version": "stable-2.13",
"python-version": "3.11"
},
{
"ansible-version": "stable-2.14",
"python-version": "3.7"
},
{
"ansible-version": "stable-2.14",
"python-version": "3.8"
},
{
"ansible-version": "stable-2.14",
"python-version": "3.11"
},
{
"ansible-version": "stable-2.15",
"python-version": "3.7"
},
{
"ansible-version": "stable-2.15",
"python-version": "3.8"
},
{
"ansible-version": "stable-2.15",
"python-version": "3.11"
},
{
"ansible-version": "milestone",
"python-version": "3.7"
},
{
"ansible-version": "milestone",
"python-version": "3.8"
},
{
"ansible-version": "devel",
"python-version": "3.7"
},
{
"ansible-version": "devel",
"python-version": "3.8"
}
]
unit-source:
uses: ansible-network/github_actions/.github/workflows/unit_source.yml@main
with:
matrix_exclude: >-
[
{
"python-version": "3.11"
},
{
"ansible-version": "stable-2.12",
"python-version": "3.7"
},
{
"ansible-version": "stable-2.13",
"python-version": "3.7"
},
{
"ansible-version": "stable-2.12",
"python-version": "3.8"
},
{
"ansible-version": "stable-2.13",
"python-version": "3.8"
},
{
"ansible-version": "stable-2.14",
"python-version": "3.7"
},
{
"ansible-version": "stable-2.14",
"python-version": "3.8"
},
{
"ansible-version": "stable-2.15",
"python-version": "3.7"
},
{
"ansible-version": "stable-2.15",
"python-version": "3.8"
},
{
"ansible-version": "milestone",
"python-version": "3.7"
},
{
"ansible-version": "milestone",
"python-version": "3.8"
},
{
"ansible-version": "devel",
"python-version": "3.7"
},
{
"ansible-version": "devel",
"python-version": "3.8"
}
]
collection_pre_install: ''
splitter:
env:
source_dir: "./source"
runs-on: ubuntu-latest
outputs:
test_targets: ${{ steps.display.outputs.test_targets }}
steps:
- name: Checkout the collection repository
uses: actions/checkout@v3
with:
path: ${{ env.source_dir }}
fetch-depth: "0"
- name: list changes for pull request
id: splitter
uses: ansible-network/github_actions/.github/actions/ansible_test_splitter@main
with:
collections_to_test: ${{ env.source_dir }}
total_jobs: 8
- name: display targets
id: display
run: echo "test_targets=${{ steps.splitter.outputs.test_targets }}" >> $GITHUB_OUTPUT
shell: bash
integration:
needs:
- splitter
env:
source: "./source"
cloud_common: "./cloudcommon"
ansible_posix: "./ansible_posix"
test_targets: ${{ needs.splitter.outputs.test_targets }}
runs-on: ubuntu-latest
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
ansible-version:
- stable-2.12
- milestone
- devel
python-version:
- "3.8"
- "3.9"
exclude:
- ansible-version: stable-2.9
python-version: 3.9
- ansible-version: stable-2.9
python-version: 3.10
- ansible-version: stable-2.9
python-version: 3.11
- ansible-version: stable-2.12
python-version: 3.11
- ansible-version: stable-2.13
python-version: 3.11
- ansible-version: stable-2.14
python-version: 3.8
- ansible-version: stable-2.15
python-version: 3.8
- ansible-version: milestone
python-version: 3.8
- ansible-version: devel
python-version: 3.8
enable-turbo-mode:
- true
- false
job-index: [1, 2, 3, 4, 5, 6, 7, 8]
name: "integration-py${{ matrix.python-version }}-${{ matrix.ansible-version }}-turbo-mode=${{ matrix.enable-turbo-mode }}-${{ matrix.job-index }}"
steps:
- name: Read ansible-test targets
id: read-targets
run: >-
echo "ansible_test_targets=$(echo "${{ env.test_targets }}" | sed s/';'/'\n'/g |
grep "kubernetes.core-${{ matrix.job-index }}" | cut -d ':' -f2 | sed s/','/' '/g)" >> $GITHUB_OUTPUT
shell: bash
- name: Display targets
run: >-
echo "targets to test: $ANSIBLE_TARGETS"
shell: bash
env:
ANSIBLE_TARGETS: ${{ steps.read-targets.outputs.ansible_test_targets }}
- name: Checkout kubernetes.core repository
uses: actions/checkout@v3
with:
path: ${{ env.source }}
fetch-depth: "0"
if: steps.read-targets.outputs.ansible_test_targets != ''
- name: checkout ansible-collections/cloud.common
uses: ansible-network/github_actions/.github/actions/checkout_dependency@main
with:
repository: ansible-collections/cloud.common
path: ${{ env.cloud_common }}
ref: main
if: steps.read-targets.outputs.ansible_test_targets != ''
- name: checkout ansible-collections/ansible.posix
uses: ansible-network/github_actions/.github/actions/checkout_dependency@main
with:
repository: ansible-collections/ansible.posix
path: ${{ env.ansible_posix }}
ref: main
if: steps.read-targets.outputs.ansible_test_targets != ''
- name: install kubernetes.core collection
id: install-collection
uses: ansible-network/github_actions/.github/actions/build_install_collection@main
with:
install_python_dependencies: true
source_path: ${{ env.source }}
if: steps.read-targets.outputs.ansible_test_targets != ''
- name: install cloud.common collection
uses: ansible-network/github_actions/.github/actions/build_install_collection@main
with:
install_python_dependencies: true
source_path: ${{ env.cloud_common }}
if: steps.read-targets.outputs.ansible_test_targets != ''
- name: install ansible.posix collection
uses: ansible-network/github_actions/.github/actions/build_install_collection@main
with:
install_python_dependencies: true
source_path: ${{ env.ansible_posix }}
if: steps.read-targets.outputs.ansible_test_targets != ''
- name: create kubernetes cluster
uses: helm/kind-action@v1.4.0
if: steps.read-targets.outputs.ansible_test_targets != ''
- name: Run integration tests
uses: ansible-network/github_actions/.github/actions/ansible_test_integration@main
with:
collection_path: ${{ steps.install-collection.outputs.collection_path }}
python_version: ${{ matrix.python-version }}
ansible_version: ${{ matrix.ansible-version }}
ansible_test_targets: ${{ steps.read-targets.outputs.ansible_test_targets }}
ansible_test_environment: |
ENABLE_TURBO_MODE=${{ matrix.enable-turbo-mode }}
if: steps.read-targets.outputs.ansible_test_targets != ''
all_green:
if: ${{ always() }}
needs:
- changelog
- linters
- sanity
- unit-source
- integration
runs-on: ubuntu-latest
steps:
- run: >-
python -c "assert set([
'${{ needs.changelog.result }}',
'${{ needs.linters.result }}',
'${{ needs.unit-source.result }}',
'${{ needs.integration.result }}'
]) == {'success'}"
- run: >-
python -c "assert '${{ needs.sanity.result }}'
in ['success', 'failure']"

14
.github/workflows/galaxy-import.yaml vendored Normal file
View File

@@ -0,0 +1,14 @@
name: galaxy-import
concurrency:
group: ${{ github.head_ref }}
cancel-in-progress: true
on:
pull_request:
branches:
- main
- stable-*
jobs:
galaxy_importer:
uses: ansible-network/github_actions/.github/workflows/galaxy_importer.yml@main

141
.github/workflows/integration-tests.yaml vendored Normal file
View File

@@ -0,0 +1,141 @@
name: Integration tests
on:
pull_request:
types:
- opened
- reopened
- labeled
- unlabeled
- synchronize
branches:
- main
- stable-*
jobs:
splitter:
env:
source_dir: "./source"
runs-on: ubuntu-latest
outputs:
test_targets: ${{ steps.display.outputs.test_targets }}
steps:
- name: Checkout the collection repository
uses: actions/checkout@v3
with:
path: ${{ env.source_dir }}
fetch-depth: "0"
- name: list changes for pull request
id: splitter
uses: ansible-network/github_actions/.github/actions/ansible_test_splitter@main
with:
collections_to_test: ${{ env.source_dir }}
total_jobs: 8
- name: display targets
id: display
run: echo "test_targets=${{ steps.splitter.outputs.test_targets }}" >> $GITHUB_OUTPUT
shell: bash
integration:
needs:
- splitter
if: ${{ needs.splitter.outputs.test_targets != '' }}
env:
source: "./source"
cloud_common: "./cloudcommon"
ansible_posix: "./ansible_posix"
test_targets: ${{ needs.splitter.outputs.test_targets }}
runs-on: ubuntu-latest
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
ansible-version:
- milestone
python-version:
- "3.12"
enable-turbo-mode:
- true
- false
job-index: [1, 2, 3, 4, 5, 6, 7, 8]
name: "integration-py${{ matrix.python-version }}-${{ matrix.ansible-version }}-turbo-mode=${{ matrix.enable-turbo-mode }}-${{ matrix.job-index }}"
steps:
- name: Read ansible-test targets
id: read-targets
run: >-
echo "ansible_test_targets=$(echo "${{ env.test_targets }}" | sed s/';'/'\n'/g |
grep "kubernetes.core-${{ matrix.job-index }}" | cut -d ':' -f2 | sed s/','/' '/g)" >> $GITHUB_OUTPUT
shell: bash
- name: Display targets
run: >-
echo "targets to test: $ANSIBLE_TARGETS"
shell: bash
env:
ANSIBLE_TARGETS: ${{ steps.read-targets.outputs.ansible_test_targets }}
- name: Checkout kubernetes.core repository
uses: actions/checkout@v3
with:
path: ${{ env.source }}
ref: ${{ github.event.pull_request.head.sha }}
- name: Set up Python ${{ env.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
# install ansible
- name: Install ansible-core (${{ matrix.ansible-version }})
run: >-
python3 -m pip install
https://github.com/ansible/ansible/archive/${{ matrix.ansible-version }}.tar.gz
--disable-pip-version-check
shell: bash
- name: Build and install collection
id: install-src
uses: ansible-network/github_actions/.github/actions/build_install_collection@main
with:
install_python_dependencies: true
source_path: ${{ env.source }}
- name: checkout ansible-collections/cloud.common
uses: ansible-network/github_actions/.github/actions/checkout_dependency@main
with:
repository: ansible-collections/cloud.common
path: ${{ env.cloud_common }}
ref: main
- name: checkout ansible-collections/ansible.posix
uses: ansible-network/github_actions/.github/actions/checkout_dependency@main
with:
repository: ansible-collections/ansible.posix
path: ${{ env.ansible_posix }}
ref: main
- name: install cloud.common collection
uses: ansible-network/github_actions/.github/actions/build_install_collection@main
with:
install_python_dependencies: true
source_path: ${{ env.cloud_common }}
- name: install ansible.posix collection
uses: ansible-network/github_actions/.github/actions/build_install_collection@main
with:
install_python_dependencies: true
source_path: ${{ env.ansible_posix }}
- name: create kubernetes cluster
uses: helm/kind-action@v1.4.0
- name: Run integration tests
uses: ansible-network/github_actions/.github/actions/ansible_test_integration@main
with:
collection_path: ${{ steps.install-src.outputs.collection_path }}
python_version: ${{ matrix.python-version }}
ansible_version: ${{ matrix.ansible-version }}
ansible_test_targets: ${{ steps.read-targets.outputs.ansible_test_targets }}
ansible_test_environment: |
ENABLE_TURBO_MODE=${{ matrix.enable-turbo-mode }}

24
.github/workflows/linters.yaml vendored Normal file
View File

@@ -0,0 +1,24 @@
---
name: Linters
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
on:
pull_request:
branches:
- main
- stable-*
tags:
- '*'
jobs:
linters:
uses: ansible-network/github_actions/.github/workflows/tox-linters.yml@main
ansible-lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run ansible-lint
uses: ansible/ansible-lint@v6.21.0

15
.github/workflows/sanity-tests.yaml vendored Normal file
View File

@@ -0,0 +1,15 @@
---
name: Sanity tests
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
on:
pull_request:
branches:
- main
- stable-*
jobs:
sanity:
uses: ansible-network/github_actions/.github/workflows/sanity.yml@main

14
.github/workflows/unit-tests.yaml vendored Normal file
View File

@@ -0,0 +1,14 @@
name: Unit tests
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
on:
pull_request:
branches:
- main
- stable-*
jobs:
unit-source:
uses: ansible-network/github_actions/.github/workflows/unit_source.yml@main

View File

@@ -9,7 +9,7 @@ The collection includes a variety of Ansible content to help automate the manage
<!--start requires_ansible--> <!--start requires_ansible-->
## Ansible version compatibility ## Ansible version compatibility
This collection has been tested against following Ansible versions: **>=2.9.17**. This collection has been tested against following Ansible versions: **>=2.14.0**.
For collections that support Ansible 2.9, please ensure you update your `network_os` to use the For collections that support Ansible 2.9, please ensure you update your `network_os` to use the
fully qualified collection name (for example, `cisco.ios.ios`). fully qualified collection name (for example, `cisco.ios.ios`).

View File

@@ -0,0 +1,5 @@
---
trivial:
- organize the workflows and pin ansible-lint to 6.21.x.
breaking_changes:
- Remove support for ansible-core < 2.14

View File

@@ -8,6 +8,7 @@ kubernetes.core.kubectl
**Execute tasks in pods running on Kubernetes.** **Execute tasks in pods running on Kubernetes.**
Version added: 1.2.1
.. contents:: .. contents::
:local: :local:

View File

@@ -9,8 +9,8 @@ authors:
- mmazur (https://github.com/mmazur) - mmazur (https://github.com/mmazur)
- jamescassell (https://github.com/jamescassell) - jamescassell (https://github.com/jamescassell)
description: Kubernetes Collection for Ansible. description: Kubernetes Collection for Ansible.
documentation: '' documentation: ""
homepage: '' homepage: ""
issues: https://github.com/ansible-collections/kubernetes.core/issues issues: https://github.com/ansible-collections/kubernetes.core/issues
license_file: LICENSE license_file: LICENSE
namespace: kubernetes namespace: kubernetes
@@ -28,4 +28,4 @@ tags:
version: 2.4.0 version: 2.4.0
build_ignore: build_ignore:
- .DS_Store - .DS_Store
- '*.tar.gz' - "*.tar.gz"

View File

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

View File

@@ -8,21 +8,21 @@ from __future__ import absolute_import, division, print_function
__metaclass__ = type __metaclass__ = type
import copy import copy
import traceback
import os import os
from contextlib import contextmanager
import platform import platform
import traceback
from contextlib import contextmanager
from ansible.config.manager import ensure_type from ansible.config.manager import ensure_type
from ansible.errors import ( from ansible.errors import (
AnsibleError,
AnsibleFileNotFound,
AnsibleAction, AnsibleAction,
AnsibleActionFail, AnsibleActionFail,
AnsibleError,
AnsibleFileNotFound,
) )
from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.module_utils.parsing.convert_bool import boolean from ansible.module_utils.parsing.convert_bool import boolean
from ansible.module_utils.six import string_types, iteritems from ansible.module_utils.six import iteritems, string_types
from ansible.module_utils._text import to_text, to_bytes, to_native
from ansible.plugins.action import ActionBase from ansible.plugins.action import ActionBase
@@ -55,7 +55,6 @@ ENV_KUBECONFIG_PATH_SEPARATOR = ";" if platform.system() == "Windows" else ":"
class ActionModule(ActionBase): class ActionModule(ActionBase):
TRANSFERS_FILES = True TRANSFERS_FILES = True
DEFAULT_NEWLINE_SEQUENCE = "\n" DEFAULT_NEWLINE_SEQUENCE = "\n"

View File

@@ -172,18 +172,18 @@ DOCUMENTATION = r"""
aliases: [ kubectl_verify_ssl ] aliases: [ kubectl_verify_ssl ]
""" """
import json
import os import os
import os.path import os.path
import shutil import shutil
import subprocess import subprocess
import tempfile import tempfile
import json
from ansible.parsing.yaml.loader import AnsibleLoader
from ansible.errors import AnsibleError, AnsibleFileNotFound from ansible.errors import AnsibleError, AnsibleFileNotFound
from ansible.module_utils.six.moves import shlex_quote
from ansible.module_utils._text import to_bytes from ansible.module_utils._text import to_bytes
from ansible.plugins.connection import ConnectionBase, BUFSIZE from ansible.module_utils.six.moves import shlex_quote
from ansible.parsing.yaml.loader import AnsibleLoader
from ansible.plugins.connection import BUFSIZE, ConnectionBase
from ansible.utils.display import Display from ansible.utils.display import Display
display = Display() display = Display()

View File

@@ -12,7 +12,6 @@ __metaclass__ = type
class ModuleDocFragment(object): class ModuleDocFragment(object):
DOCUMENTATION = r""" DOCUMENTATION = r"""
options: options:
binary_path: binary_path:

View File

@@ -11,7 +11,6 @@ __metaclass__ = type
class ModuleDocFragment(object): class ModuleDocFragment(object):
DOCUMENTATION = r""" DOCUMENTATION = r"""
options: options:
host: host:

View File

@@ -11,7 +11,6 @@ __metaclass__ = type
class ModuleDocFragment(object): class ModuleDocFragment(object):
DOCUMENTATION = r""" DOCUMENTATION = r"""
options: options:
delete_options: delete_options:

View File

@@ -11,7 +11,6 @@ __metaclass__ = type
class ModuleDocFragment(object): class ModuleDocFragment(object):
DOCUMENTATION = r""" DOCUMENTATION = r"""
options: options:
api_version: api_version:

View File

@@ -11,7 +11,6 @@ __metaclass__ = type
class ModuleDocFragment(object): class ModuleDocFragment(object):
DOCUMENTATION = r""" DOCUMENTATION = r"""
options: options:
resource_definition: resource_definition:

View File

@@ -11,7 +11,6 @@ __metaclass__ = type
class ModuleDocFragment(object): class ModuleDocFragment(object):
DOCUMENTATION = r""" DOCUMENTATION = r"""
options: options:
replicas: replicas:

View File

@@ -11,7 +11,6 @@ __metaclass__ = type
class ModuleDocFragment(object): class ModuleDocFragment(object):
DOCUMENTATION = r""" DOCUMENTATION = r"""
options: options:
state: state:

View File

@@ -11,7 +11,6 @@ __metaclass__ = type
class ModuleDocFragment(object): class ModuleDocFragment(object):
DOCUMENTATION = r""" DOCUMENTATION = r"""
options: options:
wait: wait:

View File

@@ -98,32 +98,33 @@ DOCUMENTATION = """
- "PyYAML >= 3.11" - "PyYAML >= 3.11"
""" """
EXAMPLES = """ EXAMPLES = r"""
# File must be named k8s.yaml or k8s.yml # File must be named k8s.yaml or k8s.yml
# Authenticate with token, and return all pods and services for all namespaces - name: Authenticate with token, and return all pods and services for all namespaces
plugin: kubernetes.core.k8s plugin: kubernetes.core.k8s
connections: connections:
- host: https://192.168.64.4:8443 - host: https://192.168.64.4:8443
api_key: xxxxxxxxxxxxxxxx api_key: xxxxxxxxxxxxxxxx
validate_certs: false validate_certs: false
# Use default config (~/.kube/config) file and active context, and return objects for a specific namespace - name: Use default config (~/.kube/config) file and active context, and return objects for a specific namespace
plugin: kubernetes.core.k8s plugin: kubernetes.core.k8s
connections: connections:
- namespaces: - namespaces:
- testing - testing
# Use a custom config file, and a specific context. - name: Use a custom config file, and a specific context.
plugin: kubernetes.core.k8s plugin: kubernetes.core.k8s
connections: connections:
- kubeconfig: /path/to/config - kubeconfig: /path/to/config
context: 'awx/192-168-64-4:8443/developer' context: 'awx/192-168-64-4:8443/developer'
""" """
import json import json
from ansible.errors import AnsibleError from ansible.errors import AnsibleError
from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable, Constructable
from ansible_collections.kubernetes.core.plugins.module_utils.common import ( from ansible_collections.kubernetes.core.plugins.module_utils.common import (
HAS_K8S_MODULE_HELPER, HAS_K8S_MODULE_HELPER,
k8s_import_exception, k8s_import_exception,
@@ -131,7 +132,6 @@ from ansible_collections.kubernetes.core.plugins.module_utils.common import (
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
get_api_client, get_api_client,
) )
from ansible.plugins.inventory import BaseInventoryPlugin, Constructable, Cacheable
try: try:
from kubernetes.dynamic.exceptions import DynamicApiError from kubernetes.dynamic.exceptions import DynamicApiError
@@ -193,7 +193,6 @@ class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
self.fetch_objects(connections) self.fetch_objects(connections)
def fetch_objects(self, connections): def fetch_objects(self, connections):
if connections: if connections:
if not isinstance(connections, list): if not isinstance(connections, list):
raise K8sInventoryException("Expecting connections to be a list.") raise K8sInventoryException("Expecting connections to be a list.")

View File

@@ -179,7 +179,6 @@ import os
from ansible.errors import AnsibleError from ansible.errors import AnsibleError
from ansible.module_utils.common._collections_compat import KeysView from ansible.module_utils.common._collections_compat import KeysView
from ansible.module_utils.common.validation import check_type_bool from ansible.module_utils.common.validation import check_type_bool
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
get_api_client, get_api_client,
) )
@@ -214,7 +213,6 @@ except ImportError as e:
class KubernetesLookup(object): class KubernetesLookup(object):
def __init__(self): def __init__(self):
if not HAS_K8S_MODULE_HELPER: if not HAS_K8S_MODULE_HELPER:
raise Exception( raise Exception(
"Requires the Kubernetes Python client. Try `pip install kubernetes`. Detail: {0}".format( "Requires the Kubernetes Python client. Try `pip install kubernetes`. Detail: {0}".format(

View File

@@ -64,13 +64,12 @@ RETURN = """
key1: val1 key1: val1
""" """
from ansible.errors import AnsibleLookupError
from ansible.plugins.lookup import LookupBase
from ansible.module_utils.common.process import get_bin_path
import subprocess import subprocess
from ansible.errors import AnsibleLookupError
from ansible.module_utils.common.process import get_bin_path
from ansible.plugins.lookup import LookupBase
def get_binary_from_path(name, opt_dirs=None): def get_binary_from_path(name, opt_dirs=None):
opt_arg = {} opt_arg = {}

View File

@@ -14,9 +14,9 @@ except TypeError:
if enable_turbo_mode: if enable_turbo_mode:
try: try:
from ansible_collections.cloud.common.plugins.module_utils.turbo.module import ( from ansible_collections.cloud.common.plugins.module_utils.turbo.module import ( # noqa: F401
AnsibleTurboModule as AnsibleModule, AnsibleTurboModule as AnsibleModule,
) # noqa: F401 )
AnsibleModule.collection_name = "kubernetes.core" AnsibleModule.collection_name = "kubernetes.core"
except ImportError: except ImportError:

View File

@@ -17,8 +17,8 @@ from __future__ import absolute_import, division, print_function
__metaclass__ = type __metaclass__ = type
from collections import OrderedDict
import json import json
from collections import OrderedDict
from ansible.module_utils.common.dict_transformations import dict_merge from ansible.module_utils.common.dict_transformations import dict_merge
from ansible_collections.kubernetes.core.plugins.module_utils.exceptions import ( from ansible_collections.kubernetes.core.plugins.module_utils.exceptions import (
@@ -31,7 +31,6 @@ from ansible_collections.kubernetes.core.plugins.module_utils.version import (
LooseVersion, LooseVersion,
) )
try: try:
from kubernetes.dynamic.exceptions import NotFoundError from kubernetes.dynamic.exceptions import NotFoundError
except ImportError: except ImportError:

View File

@@ -13,15 +13,18 @@
# limitations under the License. # limitations under the License.
import hashlib
import json import json
import os import os
from collections import defaultdict
import hashlib
import tempfile import tempfile
from collections import defaultdict
from functools import partial from functools import partial
import kubernetes.dynamic import kubernetes.dynamic
import kubernetes.dynamic.discovery import kubernetes.dynamic.discovery
from ansible_collections.kubernetes.core.plugins.module_utils.client.resource import (
ResourceList,
)
from kubernetes import __version__ from kubernetes import __version__
from kubernetes.dynamic.exceptions import ( from kubernetes.dynamic.exceptions import (
ResourceNotFoundError, ResourceNotFoundError,
@@ -29,10 +32,6 @@ from kubernetes.dynamic.exceptions import (
ServiceUnavailableError, ServiceUnavailableError,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.client.resource import (
ResourceList,
)
class Discoverer(kubernetes.dynamic.discovery.Discoverer): class Discoverer(kubernetes.dynamic.discovery.Discoverer):
def __init__(self, client, cache_file): def __init__(self, client, cache_file):

View File

@@ -20,17 +20,20 @@ from __future__ import absolute_import, division, print_function
__metaclass__ = type __metaclass__ = type
import base64 import base64
import time
import os
import traceback
import sys
import hashlib import hashlib
import os
import sys
import time
import traceback
from datetime import datetime from datetime import datetime
from tempfile import NamedTemporaryFile from tempfile import NamedTemporaryFile
from ansible_collections.kubernetes.core.plugins.module_utils.version import ( from ansible.module_utils._text import to_bytes, to_native, to_text
LooseVersion, from ansible.module_utils.basic import missing_required_lib
) from ansible.module_utils.common.dict_transformations import dict_merge
from ansible.module_utils.parsing.convert_bool import boolean
from ansible.module_utils.six import iteritems, string_types
from ansible.module_utils.urls import Request
from ansible_collections.kubernetes.core.plugins.module_utils.args_common import ( from ansible_collections.kubernetes.core.plugins.module_utils.args_common import (
AUTH_ARG_MAP, AUTH_ARG_MAP,
AUTH_ARG_SPEC, AUTH_ARG_SPEC,
@@ -42,27 +45,23 @@ from ansible_collections.kubernetes.core.plugins.module_utils.hashes import (
from ansible_collections.kubernetes.core.plugins.module_utils.selector import ( from ansible_collections.kubernetes.core.plugins.module_utils.selector import (
LabelSelectorFilter, LabelSelectorFilter,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.version import (
from ansible.module_utils.basic import missing_required_lib LooseVersion,
from ansible.module_utils.six import iteritems, string_types )
from ansible.module_utils._text import to_native, to_bytes, to_text
from ansible.module_utils.common.dict_transformations import dict_merge
from ansible.module_utils.parsing.convert_bool import boolean
from ansible.module_utils.urls import Request
K8S_IMP_ERR = None K8S_IMP_ERR = None
try: try:
import kubernetes import kubernetes
from kubernetes.dynamic.exceptions import ( from kubernetes.dynamic.exceptions import (
BadRequestError,
ConflictError,
DynamicApiError,
ForbiddenError,
KubernetesValidateMissing,
MethodNotAllowedError,
NotFoundError, NotFoundError,
ResourceNotFoundError, ResourceNotFoundError,
ResourceNotUniqueError, ResourceNotUniqueError,
DynamicApiError,
ConflictError,
ForbiddenError,
MethodNotAllowedError,
BadRequestError,
KubernetesValidateMissing,
) )
HAS_K8S_MODULE_HELPER = True HAS_K8S_MODULE_HELPER = True
@@ -819,7 +818,7 @@ class K8sAnsibleMixin(object):
try: try:
self.client = get_api_client(self.module) self.client = get_api_client(self.module)
# Hopefully the kubernetes client will provide its own exception class one day # Hopefully the kubernetes client will provide its own exception class one day
except (urllib3.exceptions.RequestError) as e: except urllib3.exceptions.RequestError as e:
self.fail_json(msg="Couldn't connect to Kubernetes: %s" % str(e)) self.fail_json(msg="Couldn't connect to Kubernetes: %s" % str(e))
flattened_definitions = [] flattened_definitions = []
@@ -837,7 +836,7 @@ class K8sAnsibleMixin(object):
resource = self.find_resource(kind, api_version, fail=True) resource = self.find_resource(kind, api_version, fail=True)
flattened_definitions.append((resource, definition)) flattened_definitions.append((resource, definition))
for (resource, definition) in flattened_definitions: for resource, definition in flattened_definitions:
kind = definition.get("kind", self.kind) kind = definition.get("kind", self.kind)
api_version = definition.get("apiVersion", self.api_version) api_version = definition.get("apiVersion", self.api_version)
definition = self.set_defaults(resource, definition) definition = self.set_defaults(resource, definition)

View File

@@ -18,25 +18,26 @@ from __future__ import absolute_import, division, print_function
__metaclass__ = type __metaclass__ = type
import os import os
from tempfile import TemporaryFile, NamedTemporaryFile
from select import select
from abc import ABCMeta, abstractmethod
import tarfile import tarfile
from abc import ABCMeta, abstractmethod
from select import select
from tempfile import NamedTemporaryFile, TemporaryFile
from ansible.module_utils._text import to_native
# from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import AnsibleModule # from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import AnsibleModule
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import (
CoreException, CoreException,
) )
from ansible.module_utils._text import to_native
try: try:
from kubernetes.client.api import core_v1_api from kubernetes.client.api import core_v1_api
from kubernetes.stream import stream from kubernetes.stream import stream
from kubernetes.stream.ws_client import ( from kubernetes.stream.ws_client import (
STDOUT_CHANNEL,
STDERR_CHANNEL,
ERROR_CHANNEL,
ABNF, ABNF,
ERROR_CHANNEL,
STDERR_CHANNEL,
STDOUT_CHANNEL,
) )
except ImportError: except ImportError:
pass pass

View File

@@ -19,8 +19,8 @@ from __future__ import absolute_import, division, print_function
__metaclass__ = type __metaclass__ = type
import json
import hashlib import hashlib
import json
try: try:
import string import string
@@ -37,7 +37,7 @@ except ImportError:
def sorted_dict(unsorted_dict): def sorted_dict(unsorted_dict):
result = OrderedDict() result = OrderedDict()
for (k, v) in sorted(unsorted_dict.items()): for k, v in sorted(unsorted_dict.items()):
if isinstance(v, dict): if isinstance(v, dict):
v = sorted_dict(v) v = sorted_dict(v)
result[k] = v result[k] = v

View File

@@ -7,19 +7,18 @@ from __future__ import absolute_import, division, print_function
__metaclass__ = type __metaclass__ = type
import copy
import json
import os import os
import re
import tempfile import tempfile
import traceback import traceback
import re
import json
import copy
from ansible.module_utils.basic import missing_required_lib from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.six import string_types from ansible.module_utils.six import string_types
from ansible_collections.kubernetes.core.plugins.module_utils.version import ( from ansible_collections.kubernetes.core.plugins.module_utils.version import (
LooseVersion, LooseVersion,
) )
from ansible.module_utils.basic import AnsibleModule
try: try:
import yaml import yaml
@@ -84,7 +83,6 @@ class AnsibleHelmModule(object):
""" """
def __init__(self, **kwargs): def __init__(self, **kwargs):
self._module = None self._module = None
if "module" in kwargs: if "module" in kwargs:
self._module = kwargs.get("module") self._module = kwargs.get("module")
@@ -184,7 +182,6 @@ class AnsibleHelmModule(object):
) )
def get_helm_version(self): def get_helm_version(self):
command = self.get_helm_binary() + " version" command = self.get_helm_binary() + " version"
rc, out, err = self.run_command(command) rc, out, err = self.run_command(command)
m = re.match(r'version.BuildInfo{Version:"v([0-9\.]*)",', out) m = re.match(r'version.BuildInfo{Version:"v([0-9\.]*)",', out)
@@ -216,7 +213,6 @@ class AnsibleHelmModule(object):
return yaml.safe_load(out) return yaml.safe_load(out)
def parse_yaml_content(self, content): def parse_yaml_content(self, content):
if not HAS_YAML: if not HAS_YAML:
self.fail_json(msg=missing_required_lib("yaml"), exception=HAS_YAML) self.fail_json(msg=missing_required_lib("yaml"), exception=HAS_YAML)
@@ -228,7 +224,6 @@ class AnsibleHelmModule(object):
) )
def get_manifest(self, release_name): def get_manifest(self, release_name):
command = [ command = [
self.get_helm_binary(), self.get_helm_binary(),
"get", "get",
@@ -241,7 +236,6 @@ class AnsibleHelmModule(object):
return self.parse_yaml_content(out) return self.parse_yaml_content(out)
def get_notes(self, release_name): def get_notes(self, release_name):
command = [ command = [
self.get_helm_binary(), self.get_helm_binary(),
"get", "get",

View File

@@ -1,12 +1,11 @@
# Copyright: (c) 2021, Red Hat | Ansible # Copyright: (c) 2021, Red Hat | Ansible
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
import os
import hashlib import hashlib
import os
from typing import Any, Dict, List, Optional from typing import Any, Dict, List, Optional
from ansible.module_utils.six import iteritems, string_types from ansible.module_utils.six import iteritems, string_types
from ansible_collections.kubernetes.core.plugins.module_utils.args_common import ( from ansible_collections.kubernetes.core.plugins.module_utils.args_common import (
AUTH_ARG_MAP, AUTH_ARG_MAP,
AUTH_ARG_SPEC, AUTH_ARG_SPEC,

View File

@@ -1,15 +1,12 @@
import traceback import traceback
from typing import Optional from typing import Optional
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.common.text.converters import to_text
from ansible_collections.kubernetes.core.plugins.module_utils.version import ( from ansible_collections.kubernetes.core.plugins.module_utils.version import (
LooseVersion, LooseVersion,
) )
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.basic import missing_required_lib
from ansible.module_utils.common.text.converters import to_text
class AnsibleK8SModule: class AnsibleK8SModule:
"""A base module class for K8S modules. """A base module class for K8S modules.

View File

@@ -2,7 +2,7 @@
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
import os import os
from typing import cast, Dict, Iterable, List, Optional, Union from typing import Dict, Iterable, List, Optional, Union, cast
from ansible.module_utils.six import string_types from ansible.module_utils.six import string_types
from ansible.module_utils.urls import Request from ansible.module_utils.urls import Request

View File

@@ -4,12 +4,12 @@
from typing import Dict from typing import Dict
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
get_api_client, get_api_client,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import (
CoreException, CoreException,
ResourceTimeout,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.resource import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.resource import (
create_definitions, create_definitions,
@@ -19,9 +19,6 @@ from ansible_collections.kubernetes.core.plugins.module_utils.k8s.service import
diff_objects, diff_objects,
hide_fields, hide_fields,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import (
ResourceTimeout,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.waiter import exists from ansible_collections.kubernetes.core.plugins.module_utils.k8s.waiter import exists
from ansible_collections.kubernetes.core.plugins.module_utils.selector import ( from ansible_collections.kubernetes.core.plugins.module_utils.selector import (
LabelSelectorFilter, LabelSelectorFilter,

View File

@@ -4,36 +4,30 @@
import copy import copy
from typing import Any, Dict, List, Optional, Tuple from typing import Any, Dict, List, Optional, Tuple
from ansible.module_utils.common.dict_transformations import dict_merge
from ansible_collections.kubernetes.core.plugins.module_utils.hashes import ( from ansible_collections.kubernetes.core.plugins.module_utils.hashes import (
generate_hash, generate_hash,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.core import requires
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.waiter import (
Waiter,
exists,
resource_absent,
get_waiter,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.core import (
requires,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import (
CoreException, CoreException,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.waiter import (
from ansible.module_utils.common.dict_transformations import dict_merge Waiter,
exists,
get_waiter,
resource_absent,
)
try: try:
from kubernetes.dynamic.exceptions import ( from kubernetes.dynamic.exceptions import (
NotFoundError, BadRequestError,
ResourceNotFoundError,
ResourceNotUniqueError,
ConflictError, ConflictError,
ForbiddenError, ForbiddenError,
MethodNotAllowedError, MethodNotAllowedError,
BadRequestError, NotFoundError,
ResourceNotFoundError,
ResourceNotUniqueError,
) )
except ImportError: except ImportError:
# Handled in module setup # Handled in module setup

View File

@@ -3,7 +3,6 @@ from functools import partial
from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Union from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Union
from ansible.module_utils.parsing.convert_bool import boolean from ansible.module_utils.parsing.convert_bool import boolean
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import (
CoreException, CoreException,
) )

View File

@@ -18,12 +18,11 @@ from __future__ import absolute_import, division, print_function
__metaclass__ = type __metaclass__ = type
from kubernetes.dynamic import DynamicClient
from ansible_collections.kubernetes.core.plugins.module_utils.apply import k8s_apply from ansible_collections.kubernetes.core.plugins.module_utils.apply import k8s_apply
from ansible_collections.kubernetes.core.plugins.module_utils.exceptions import ( from ansible_collections.kubernetes.core.plugins.module_utils.exceptions import (
ApplyException, ApplyException,
) )
from kubernetes.dynamic import DynamicClient
class K8SDynamicClient(DynamicClient): class K8SDynamicClient(DynamicClient):

View File

@@ -16,7 +16,6 @@ import re
class Selector(object): class Selector(object):
equality_based_operators = ("==", "!=", "=") equality_based_operators = ("==", "!=", "=")
def __init__(self, data): def __init__(self, data):

View File

@@ -393,10 +393,11 @@ command:
sample: helm upgrade ... sample: helm upgrade ...
""" """
import copy
import re import re
import tempfile import tempfile
import traceback import traceback
import copy
from ansible_collections.kubernetes.core.plugins.module_utils.version import ( from ansible_collections.kubernetes.core.plugins.module_utils.version import (
LooseVersion, LooseVersion,
) )
@@ -877,7 +878,6 @@ def main():
changed = True changed = True
else: else:
helm_diff_version = get_plugin_version("diff") helm_diff_version = get_plugin_version("diff")
if helm_diff_version and ( if helm_diff_version and (
not chart_repo_url not chart_repo_url

View File

@@ -137,8 +137,8 @@ status:
version_added: "2.4.0" version_added: "2.4.0"
""" """
import traceback
import copy import copy
import traceback
try: try:
import yaml import yaml

View File

@@ -109,6 +109,7 @@ rc:
""" """
import copy import copy
from ansible_collections.kubernetes.core.plugins.module_utils.helm import ( from ansible_collections.kubernetes.core.plugins.module_utils.helm import (
AnsibleHelmModule, AnsibleHelmModule,
parse_helm_plugin_list, parse_helm_plugin_list,

View File

@@ -71,9 +71,10 @@ rc:
""" """
import copy import copy
from ansible_collections.kubernetes.core.plugins.module_utils.helm import ( from ansible_collections.kubernetes.core.plugins.module_utils.helm import (
parse_helm_plugin_list,
AnsibleHelmModule, AnsibleHelmModule,
parse_helm_plugin_list,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.helm_args_common import ( from ansible_collections.kubernetes.core.plugins.module_utils.helm_args_common import (
HELM_AUTH_ARG_SPEC, HELM_AUTH_ARG_SPEC,
@@ -82,7 +83,6 @@ from ansible_collections.kubernetes.core.plugins.module_utils.helm_args_common i
def main(): def main():
argument_spec = copy.deepcopy(HELM_AUTH_ARG_SPEC) argument_spec = copy.deepcopy(HELM_AUTH_ARG_SPEC)
argument_spec.update( argument_spec.update(
dict( dict(

View File

@@ -166,8 +166,8 @@ msg:
sample: 'Repository already have a repository named bitnami' sample: 'Repository already have a repository named bitnami'
""" """
import traceback
import copy import copy
import traceback
try: try:
import yaml import yaml

View File

@@ -278,10 +278,10 @@ EXAMPLES = r"""
kubernetes.core.k8s: kubernetes.core.k8s:
state: present state: present
template: template:
- path: '/testing/deployment_one.j2' - path: '/testing/deployment_one.j2'
- path: '/testing/deployment_two.j2' - path: '/testing/deployment_two.j2'
variable_start_string: '[[' variable_start_string: '[['
variable_end_string: ']]' variable_end_string: ']]'
- name: fail on validation errors - name: fail on validation errors
kubernetes.core.k8s: kubernetes.core.k8s:
@@ -423,10 +423,10 @@ from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule impo
) )
from ansible_collections.kubernetes.core.plugins.module_utils.args_common import ( from ansible_collections.kubernetes.core.plugins.module_utils.args_common import (
AUTH_ARG_SPEC, AUTH_ARG_SPEC,
WAIT_ARG_SPEC, DELETE_OPTS_ARG_SPEC,
NAME_ARG_SPEC, NAME_ARG_SPEC,
RESOURCE_ARG_SPEC, RESOURCE_ARG_SPEC,
DELETE_OPTS_ARG_SPEC, WAIT_ARG_SPEC,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.core import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.core import (
AnsibleK8SModule, AnsibleK8SModule,

View File

@@ -154,15 +154,15 @@ except ImportError:
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import ( from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
AnsibleModule, AnsibleModule,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.args_common import (
AUTH_ARG_SPEC,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.core import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.core import (
AnsibleK8SModule, AnsibleK8SModule,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import (
CoreException, CoreException,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.args_common import (
AUTH_ARG_SPEC,
)
def execute_module(module, client): def execute_module(module, client):

View File

@@ -139,9 +139,18 @@ result:
import copy import copy
from ansible.module_utils._text import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import ( from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
AnsibleModule, AnsibleModule,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.args_common import (
AUTH_ARG_SPEC,
)
from ansible_collections.kubernetes.core.plugins.module_utils.copy import (
K8SCopyFromPod,
K8SCopyToPod,
check_pod,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
get_api_client, get_api_client,
) )
@@ -155,16 +164,6 @@ from ansible_collections.kubernetes.core.plugins.module_utils.k8s.service import
K8sService, K8sService,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.args_common import (
AUTH_ARG_SPEC,
)
from ansible_collections.kubernetes.core.plugins.module_utils.copy import (
K8SCopyFromPod,
K8SCopyToPod,
check_pod,
)
from ansible.module_utils._text import to_native
def argspec(): def argspec():
argument_spec = copy.deepcopy(AUTH_ARG_SPEC) argument_spec = copy.deepcopy(AUTH_ARG_SPEC)

View File

@@ -113,7 +113,7 @@ EXAMPLES = r"""
state: drain state: drain
name: foo name: foo
delete_options: delete_options:
terminate_grace_period: 900 terminate_grace_period: 900
- name: Mark node "foo" as schedulable. - name: Mark node "foo" as schedulable.
kubernetes.core.k8s_drain: kubernetes.core.k8s_drain:
@@ -132,7 +132,6 @@ EXAMPLES = r"""
pod_selectors: pod_selectors:
- 'app!=csi-attacher' - 'app!=csi-attacher'
- 'app!=csi-provisioner' - 'app!=csi-provisioner'
""" """
RETURN = r""" RETURN = r"""
@@ -146,8 +145,9 @@ result:
import copy import copy
import time import time
import traceback import traceback
from datetime import datetime from datetime import datetime
from ansible.module_utils._text import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import ( from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
AnsibleModule, AnsibleModule,
) )
@@ -164,12 +164,10 @@ from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions imp
CoreException, CoreException,
) )
from ansible.module_utils._text import to_native
try: try:
from kubernetes.client.api import core_v1_api from kubernetes.client.api import core_v1_api
from kubernetes.client.models import V1DeleteOptions, V1ObjectMeta
from kubernetes.client.exceptions import ApiException from kubernetes.client.exceptions import ApiException
from kubernetes.client.models import V1DeleteOptions, V1ObjectMeta
except ImportError: except ImportError:
# ImportError are managed by the common module already. # ImportError are managed by the common module already.
pass pass
@@ -430,7 +428,6 @@ class K8sDrainAnsible(object):
return dict(result=" ".join(result)) return dict(result=" ".join(result))
def patch_node(self, unschedulable): def patch_node(self, unschedulable):
body = {"spec": {"unschedulable": unschedulable}} body = {"spec": {"unschedulable": unschedulable}}
try: try:
self._api_instance.patch_node( self._api_instance.patch_node(
@@ -442,7 +439,6 @@ class K8sDrainAnsible(object):
) )
def execute_module(self): def execute_module(self):
state = self._module.params.get("state") state = self._module.params.get("state")
name = self._module.params.get("name") name = self._module.params.get("name")
try: try:

View File

@@ -131,27 +131,27 @@ except ImportError:
# ImportError are managed by the common module already. # ImportError are managed by the common module already.
pass pass
from ansible.module_utils._text import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import ( from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
AnsibleModule, AnsibleModule,
) )
from ansible.module_utils._text import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.common import ( from ansible_collections.kubernetes.core.plugins.module_utils.common import (
AUTH_ARG_SPEC, AUTH_ARG_SPEC,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.core import (
AnsibleK8SModule,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
get_api_client, get_api_client,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.core import (
AnsibleK8SModule,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import (
CoreException, CoreException,
) )
try: try:
from kubernetes.client.apis import core_v1_api from kubernetes.client.apis import core_v1_api
from kubernetes.stream import stream
from kubernetes.client.exceptions import ApiException from kubernetes.client.exceptions import ApiException
from kubernetes.stream import stream
except ImportError: except ImportError:
# ImportError are managed by the common module already. # ImportError are managed by the common module already.
pass pass

View File

@@ -165,12 +165,12 @@ from ansible_collections.kubernetes.core.plugins.module_utils.args_common import
AUTH_ARG_SPEC, AUTH_ARG_SPEC,
WAIT_ARG_SPEC, WAIT_ARG_SPEC,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.core import (
AnsibleK8SModule,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
get_api_client, get_api_client,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.core import (
AnsibleK8SModule,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import (
CoreException, CoreException,
) )

View File

@@ -127,8 +127,8 @@ error:
import copy import copy
import traceback import traceback
from ansible.module_utils.basic import missing_required_lib
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
from ansible.module_utils.basic import missing_required_lib
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import ( from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
AnsibleModule, AnsibleModule,
) )
@@ -152,7 +152,6 @@ from ansible_collections.kubernetes.core.plugins.module_utils.k8s.waiter import
get_waiter, get_waiter,
) )
try: try:
from kubernetes.dynamic.exceptions import DynamicApiError from kubernetes.dynamic.exceptions import DynamicApiError
except ImportError: except ImportError:

View File

@@ -6,7 +6,6 @@
from __future__ import absolute_import, division, print_function from __future__ import absolute_import, division, print_function
__metaclass__ = type __metaclass__ = type
@@ -151,14 +150,13 @@ except ImportError:
pass pass
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import ( from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
AnsibleModule, AnsibleModule,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.args_common import ( from ansible_collections.kubernetes.core.plugins.module_utils.args_common import (
AUTH_ARG_SPEC, AUTH_ARG_SPEC,
RESOURCE_ARG_SPEC,
NAME_ARG_SPEC, NAME_ARG_SPEC,
RESOURCE_ARG_SPEC,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
get_api_client, get_api_client,
@@ -170,15 +168,15 @@ from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions imp
CoreException, CoreException,
ResourceTimeout, ResourceTimeout,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.resource import (
create_definitions,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.service import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.service import (
diff_objects, diff_objects,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.waiter import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.waiter import (
get_waiter, get_waiter,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.resource import (
create_definitions,
)
SCALE_ARG_SPEC = { SCALE_ARG_SPEC = {
"replicas": {"type": "int", "required": True}, "replicas": {"type": "int", "required": True},

View File

@@ -143,7 +143,6 @@ result:
""" """
import copy import copy
from collections import defaultdict from collections import defaultdict
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import ( from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
@@ -154,25 +153,24 @@ from ansible_collections.kubernetes.core.plugins.module_utils.args_common import
COMMON_ARG_SPEC, COMMON_ARG_SPEC,
RESOURCE_ARG_SPEC, RESOURCE_ARG_SPEC,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.core import (
AnsibleK8SModule,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
get_api_client, get_api_client,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.core import (
AnsibleK8SModule,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import (
CoreException, CoreException,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.service import (
K8sService,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.resource import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.resource import (
create_definitions, create_definitions,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.runner import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.runner import (
perform_action, perform_action,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.service import (
K8sService,
)
SERVICE_ARG_SPEC = { SERVICE_ARG_SPEC = {
"apply": {"type": "bool", "default": False}, "apply": {"type": "bool", "default": False},

View File

@@ -127,7 +127,6 @@ result:
import copy import copy
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import ( from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
AnsibleModule, AnsibleModule,
) )

View File

@@ -48,9 +48,10 @@ EXAMPLES = r"""
RETURN = r""" RETURN = r"""
""" """
import subprocess
import json import json
import subprocess
import time import time
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule

View File

@@ -52,12 +52,12 @@ result:
""" """
import re import re
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.kubernetes.core.plugins.module_utils.version import ( from ansible_collections.kubernetes.core.plugins.module_utils.version import (
LooseVersion, LooseVersion,
) )
from ansible.module_utils.basic import AnsibleModule
def main(): def main():
module = AnsibleModule( module = AnsibleModule(

View File

@@ -1,93 +0,0 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2021, Aubin Bikouo <@abikouo>
# 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: k8s_create_file
short_description: Create large file with a defined size.
author:
- Aubin Bikouo (@abikouo)
description:
- This module is used to validate k8s_cp module.
options:
path:
description:
- The destination path for the file to create.
type: path
required: yes
size:
description:
- The size of the output file in MB.
type: int
default: 400
binary:
description:
- If this flag is set to yes, the generated file content binary data.
type: bool
default: False
"""
EXAMPLES = r"""
- name: create 150MB file
k8s_diff:
path: large_file.txt
size: 150
"""
RETURN = r"""
"""
import os
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
def execute_module(module):
try:
size = module.params.get("size") * 1024 * 1024
path = module.params.get("path")
write_mode = "w"
if module.params.get("binary"):
content = os.urandom(size)
write_mode = "wb"
else:
content = ""
count = 0
while len(content) < size:
content += "This file has been generated using ansible: {0}\n".format(
count
)
count += 1
with open(path, write_mode) as f:
f.write(content)
module.exit_json(changed=True, size=len(content))
except Exception as e:
module.fail_json(msg="failed to create file due to: {0}".format(to_native(e)))
def main():
argument_spec = {}
argument_spec["size"] = {"type": "int", "default": 400}
argument_spec["path"] = {"type": "path", "required": True}
argument_spec["binary"] = {"type": "bool", "default": False}
module = AnsibleModule(argument_spec=argument_spec)
execute_module(module)
if __name__ == "__main__":
main()

View File

@@ -89,10 +89,10 @@ EXAMPLES = r"""
RETURN = r""" RETURN = r"""
""" """
import os
import filecmp import filecmp
import os
from tempfile import NamedTemporaryFile, TemporaryDirectory from tempfile import NamedTemporaryFile, TemporaryDirectory
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule
@@ -157,7 +157,6 @@ def compare_directories(dir1, dir2):
def execute_module(module): def execute_module(module):
args = module.params.get("args") args = module.params.get("args")
local_path = module.params.get("local_path") local_path = module.params.get("local_path")
namespace = module.params.get("namespace") namespace = module.params.get("namespace")

View File

@@ -10,16 +10,13 @@
path: "{{ test_directory }}" path: "{{ test_directory }}"
state: directory state: directory
- name: create large text file - name: Create a large text file
k8s_create_file: ansible.builtin.shell:
path: "{{ test_directory }}/large_text_file.txt" cmd: base64 /dev/random | head -c 150M > {{ test_directory }}/large_text_file.txt
size: 150
- name: create large binary file - name: Create a large binary file
k8s_create_file: ansible.builtin.command:
path: "{{ test_directory }}/large_bin_file.bin" cmd: dd if=/dev/random of={{ test_directory }}/large_bin_file.bin bs=1M count=200
size: 200
binary: true
# Copy large text file from/to local filesystem to Pod # Copy large text file from/to local filesystem to Pod
- name: copy large file into remote Pod - name: copy large file into remote Pod

View File

@@ -52,6 +52,7 @@
name: name:
- kubernetes - kubernetes
- kubernetes-validate - kubernetes-validate
- setuptools
virtualenv: "{{ virtualenv }}" virtualenv: "{{ virtualenv }}"
virtualenv_command: "{{ virtualenv_command }}" virtualenv_command: "{{ virtualenv_command }}"
virtualenv_site_packages: false virtualenv_site_packages: false

View File

@@ -78,7 +78,6 @@ from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import
class K8SInventoryTestModule(AnsibleModule): class K8SInventoryTestModule(AnsibleModule):
def __init__(self): def __init__(self):
argument_spec = dict( argument_spec = dict(
kube_config=dict(required=True, type="path"), kube_config=dict(required=True, type="path"),
dest_dir=dict(required=True, type="path"), dest_dir=dict(required=True, type="path"),
@@ -88,7 +87,6 @@ class K8SInventoryTestModule(AnsibleModule):
self.execute_module() self.execute_module()
def execute_module(self): def execute_module(self):
dest_dir = os.path.abspath(self.params.get("dest_dir")) dest_dir = os.path.abspath(self.params.get("dest_dir"))
kubeconfig_path = self.params.get("kube_config") kubeconfig_path = self.params.get("kube_config")
if not os.path.isdir(dest_dir): if not os.path.isdir(dest_dir):

View File

@@ -3,16 +3,19 @@ plugins/module_utils/client/discovery.py import-3.7!skip
plugins/module_utils/client/discovery.py import-3.8!skip plugins/module_utils/client/discovery.py import-3.8!skip
plugins/module_utils/client/discovery.py import-3.9!skip plugins/module_utils/client/discovery.py import-3.9!skip
plugins/module_utils/client/discovery.py import-3.10!skip plugins/module_utils/client/discovery.py import-3.10!skip
plugins/module_utils/client/discovery.py import-3.11!skip
plugins/module_utils/client/resource.py import-3.6!skip plugins/module_utils/client/resource.py import-3.6!skip
plugins/module_utils/client/resource.py import-3.7!skip plugins/module_utils/client/resource.py import-3.7!skip
plugins/module_utils/client/resource.py import-3.8!skip plugins/module_utils/client/resource.py import-3.8!skip
plugins/module_utils/client/resource.py import-3.9!skip plugins/module_utils/client/resource.py import-3.9!skip
plugins/module_utils/client/resource.py import-3.10!skip plugins/module_utils/client/resource.py import-3.10!skip
plugins/module_utils/client/resource.py import-3.11!skip
plugins/module_utils/k8sdynamicclient.py import-3.6!skip plugins/module_utils/k8sdynamicclient.py import-3.6!skip
plugins/module_utils/k8sdynamicclient.py import-3.7!skip plugins/module_utils/k8sdynamicclient.py import-3.7!skip
plugins/module_utils/k8sdynamicclient.py import-3.8!skip plugins/module_utils/k8sdynamicclient.py import-3.8!skip
plugins/module_utils/k8sdynamicclient.py import-3.9!skip plugins/module_utils/k8sdynamicclient.py import-3.9!skip
plugins/module_utils/k8sdynamicclient.py import-3.10!skip plugins/module_utils/k8sdynamicclient.py import-3.10!skip
plugins/module_utils/k8sdynamicclient.py import-3.11!skip
plugins/modules/k8s.py validate-modules:parameter-type-not-in-doc plugins/modules/k8s.py validate-modules:parameter-type-not-in-doc
plugins/modules/k8s_scale.py validate-modules:parameter-type-not-in-doc plugins/modules/k8s_scale.py validate-modules:parameter-type-not-in-doc
plugins/modules/k8s_service.py validate-modules:parameter-type-not-in-doc plugins/modules/k8s_service.py validate-modules:parameter-type-not-in-doc

View File

@@ -0,0 +1,40 @@
plugins/module_utils/client/discovery.py import-3.6!skip
plugins/module_utils/client/discovery.py import-3.7!skip
plugins/module_utils/client/discovery.py import-3.8!skip
plugins/module_utils/client/discovery.py import-3.9!skip
plugins/module_utils/client/discovery.py import-3.10!skip
plugins/module_utils/client/discovery.py import-3.11!skip
plugins/module_utils/client/discovery.py import-3.12!skip
plugins/module_utils/client/resource.py import-3.6!skip
plugins/module_utils/client/resource.py import-3.7!skip
plugins/module_utils/client/resource.py import-3.8!skip
plugins/module_utils/client/resource.py import-3.9!skip
plugins/module_utils/client/resource.py import-3.10!skip
plugins/module_utils/client/resource.py import-3.11!skip
plugins/module_utils/client/resource.py import-3.12!skip
plugins/module_utils/k8sdynamicclient.py import-3.6!skip
plugins/module_utils/k8sdynamicclient.py import-3.7!skip
plugins/module_utils/k8sdynamicclient.py import-3.8!skip
plugins/module_utils/k8sdynamicclient.py import-3.9!skip
plugins/module_utils/k8sdynamicclient.py import-3.10!skip
plugins/module_utils/k8sdynamicclient.py import-3.11!skip
plugins/module_utils/k8sdynamicclient.py import-3.12!skip
plugins/module_utils/version.py pylint!skip
plugins/modules/k8s.py validate-modules:parameter-type-not-in-doc
plugins/modules/k8s_scale.py validate-modules:parameter-type-not-in-doc
plugins/modules/k8s_service.py validate-modules:parameter-type-not-in-doc
tests/unit/module_utils/fixtures/definitions.yml yamllint!skip
tests/unit/module_utils/fixtures/deployments.yml yamllint!skip
tests/integration/targets/k8s_delete/files/deployments.yaml yamllint!skip
tests/unit/module_utils/fixtures/pods.yml yamllint!skip
tests/integration/targets/helm/files/appversionless-chart-v2/templates/configmap.yaml yamllint!skip
tests/integration/targets/helm/files/appversionless-chart/templates/configmap.yaml yamllint!skip
tests/integration/targets/helm/files/test-chart-v2/templates/configmap.yaml yamllint!skip
tests/integration/targets/helm/files/test-chart/templates/configmap.yaml yamllint!skip
tests/integration/targets/helm_diff/files/test-chart/templates/configmap.yaml yamllint!skip
tests/integration/targets/k8s_scale/files/deployment.yaml yamllint!skip
tests/sanity/refresh_ignore_files shebang!skip
plugins/modules/k8s.py validate-modules:return-syntax-error
plugins/modules/k8s_scale.py validate-modules:return-syntax-error
plugins/modules/k8s_service.py validate-modules:return-syntax-error
plugins/modules/k8s_taint.py validate-modules:return-syntax-error

View File

@@ -523,9 +523,6 @@ tests/unit/modules/test_module_helm.py compile-3.5!skip
tests/unit/action/test_remove_omit.py compile-2.6!skip tests/unit/action/test_remove_omit.py compile-2.6!skip
tests/unit/action/test_remove_omit.py compile-2.7!skip tests/unit/action/test_remove_omit.py compile-2.7!skip
tests/unit/action/test_remove_omit.py compile-3.5!skip tests/unit/action/test_remove_omit.py compile-3.5!skip
tests/integration/targets/k8s_copy/library/k8s_create_file.py compile-2.6!skip
tests/integration/targets/k8s_copy/library/k8s_create_file.py compile-2.7!skip
tests/integration/targets/k8s_copy/library/k8s_create_file.py compile-3.5!skip
tests/integration/targets/k8s_copy/library/kubectl_file_compare.py compile-2.6!skip tests/integration/targets/k8s_copy/library/kubectl_file_compare.py compile-2.6!skip
tests/integration/targets/k8s_copy/library/kubectl_file_compare.py compile-2.7!skip tests/integration/targets/k8s_copy/library/kubectl_file_compare.py compile-2.7!skip
tests/integration/targets/k8s_copy/library/kubectl_file_compare.py compile-3.5!skip tests/integration/targets/k8s_copy/library/kubectl_file_compare.py compile-3.5!skip
@@ -577,7 +574,6 @@ plugins/module_utils/k8s/client.py pylint!skip
plugins/module_utils/k8s/runner.py pylint!skip plugins/module_utils/k8s/runner.py pylint!skip
plugins/module_utils/k8s/service.py pylint!skip plugins/module_utils/k8s/service.py pylint!skip
plugins/module_utils/k8s/exceptions.py pylint!skip plugins/module_utils/k8s/exceptions.py pylint!skip
tests/integration/targets/k8s_copy/library/k8s_create_file.py pylint!skip
tests/integration/targets/k8s_copy/library/kubectl_file_compare.py pylint!skip tests/integration/targets/k8s_copy/library/kubectl_file_compare.py pylint!skip
tests/integration/targets/setup_kubeconfig/library/test_inventory_read_credentials.py pylint!skip tests/integration/targets/setup_kubeconfig/library/test_inventory_read_credentials.py pylint!skip
tests/integration/targets/helm/library/helm_test_version.py pylint!skip tests/integration/targets/helm/library/helm_test_version.py pylint!skip

View File

@@ -2,10 +2,8 @@
import itertools import itertools
from pathlib import Path from pathlib import Path
# Mapping of Ansible versions to supported Python versions # Mapping of Ansible versions to supported Python versions
ANSIBLE_VERSIONS = { ANSIBLE_VERSIONS = {
"2.9": ["3.6", "3.7", "3.8"], "2.9": ["3.6", "3.7", "3.8"],

View File

@@ -7,6 +7,7 @@ from __future__ import absolute_import, division, print_function
__metaclass__ = type __metaclass__ = type
from datetime import datetime from datetime import datetime
from ansible_collections.kubernetes.core.plugins.action.k8s_info import RemoveOmit from ansible_collections.kubernetes.core.plugins.action.k8s_info import RemoveOmit

View File

@@ -6,12 +6,11 @@ import json
import sys import sys
from io import BytesIO from io import BytesIO
import pytest
import ansible.module_utils.basic import ansible.module_utils.basic
from ansible.module_utils.six import string_types import pytest
from ansible.module_utils._text import to_bytes from ansible.module_utils._text import to_bytes
from ansible.module_utils.common._collections_compat import MutableMapping from ansible.module_utils.common._collections_compat import MutableMapping
from ansible.module_utils.six import string_types
@pytest.fixture @pytest.fixture

View File

@@ -18,8 +18,8 @@ from __future__ import absolute_import, division, print_function
__metaclass__ = type __metaclass__ = type
from ansible_collections.kubernetes.core.plugins.module_utils.apply import ( from ansible_collections.kubernetes.core.plugins.module_utils.apply import (
merge,
apply_patch, apply_patch,
merge,
) )
tests = [ tests = [

View File

@@ -1,14 +1,14 @@
import os
import base64 import base64
import os
import tempfile import tempfile
import yaml
import mock
from mock import MagicMock
import mock
import yaml
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
_create_auth_spec, _create_auth_spec,
_create_configuration, _create_configuration,
) )
from mock import MagicMock
TEST_HOST = "test-host" TEST_HOST = "test-host"
TEST_SSL_HOST = "https://test-host" TEST_SSL_HOST = "https://test-host"

View File

@@ -6,7 +6,6 @@ import json
import kubernetes import kubernetes
import pytest import pytest
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.core import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.core import (
AnsibleK8SModule, AnsibleK8SModule,
) )

View File

@@ -14,19 +14,17 @@
import pytest import pytest
from kubernetes.client import ApiClient
from kubernetes.dynamic import Resource
from ansible_collections.kubernetes.core.plugins.module_utils.k8sdynamicclient import (
K8SDynamicClient,
)
from ansible_collections.kubernetes.core.plugins.module_utils.client.discovery import ( from ansible_collections.kubernetes.core.plugins.module_utils.client.discovery import (
LazyDiscoverer, LazyDiscoverer,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.client.resource import ( from ansible_collections.kubernetes.core.plugins.module_utils.client.resource import (
ResourceList, ResourceList,
) )
from ansible_collections.kubernetes.core.plugins.module_utils.k8sdynamicclient import (
K8SDynamicClient,
)
from kubernetes.client import ApiClient
from kubernetes.dynamic import Resource
@pytest.fixture(scope="module") @pytest.fixture(scope="module")

View File

@@ -7,18 +7,17 @@ from __future__ import absolute_import, division, print_function
__metaclass__ = type __metaclass__ = type
import os.path import os.path
import yaml import random
import string
import tempfile import tempfile
from unittest.mock import MagicMock
import pytest import pytest
import yaml
from ansible_collections.kubernetes.core.plugins.module_utils.helm import ( from ansible_collections.kubernetes.core.plugins.module_utils.helm import (
AnsibleHelmModule, AnsibleHelmModule,
write_temp_kubeconfig, write_temp_kubeconfig,
) )
from unittest.mock import MagicMock
import random
import string
@pytest.fixture() @pytest.fixture()
@@ -114,7 +113,6 @@ def test_write_temp_kubeconfig_with_kubeconfig():
def test_module_get_helm_binary_from_params(): def test_module_get_helm_binary_from_params():
helm_binary_path = MagicMock() helm_binary_path = MagicMock()
helm_sys_binary_path = MagicMock() helm_sys_binary_path = MagicMock()
@@ -129,7 +127,6 @@ def test_module_get_helm_binary_from_params():
def test_module_get_helm_binary_from_system(): def test_module_get_helm_binary_from_system():
helm_sys_binary_path = MagicMock() helm_sys_binary_path = MagicMock()
module = MagicMock() module = MagicMock()
module.params = {} module.params = {}
@@ -140,7 +137,6 @@ def test_module_get_helm_binary_from_system():
def test_module_get_helm_plugin_list(_ansible_helm_module): def test_module_get_helm_plugin_list(_ansible_helm_module):
_ansible_helm_module.run_helm_command = MagicMock() _ansible_helm_module.run_helm_command = MagicMock()
_ansible_helm_module.run_helm_command.return_value = (0, "output", "error") _ansible_helm_module.run_helm_command.return_value = (0, "output", "error")
@@ -156,7 +152,6 @@ def test_module_get_helm_plugin_list(_ansible_helm_module):
def test_module_get_helm_plugin_list_failure(_ansible_helm_module): def test_module_get_helm_plugin_list_failure(_ansible_helm_module):
_ansible_helm_module.run_helm_command = MagicMock() _ansible_helm_module.run_helm_command = MagicMock()
_ansible_helm_module.run_helm_command.return_value = (-1, "output", "error") _ansible_helm_module.run_helm_command.return_value = (-1, "output", "error")
@@ -175,7 +170,6 @@ def test_module_get_helm_plugin_list_failure(_ansible_helm_module):
@pytest.mark.parametrize("no_values", [True, False]) @pytest.mark.parametrize("no_values", [True, False])
@pytest.mark.parametrize("get_all", [True, False]) @pytest.mark.parametrize("get_all", [True, False])
def test_module_get_values(_ansible_helm_module, no_values, get_all): def test_module_get_values(_ansible_helm_module, no_values, get_all):
expected = {"test": "units"} expected = {"test": "units"}
output = "---\ntest: units\n" output = "---\ntest: units\n"
@@ -211,7 +205,6 @@ def test_module_get_values(_ansible_helm_module, no_values, get_all):
], ],
) )
def test_module_get_helm_version(_ansible_helm_module, output, expected): def test_module_get_helm_version(_ansible_helm_module, output, expected):
_ansible_helm_module.run_command = MagicMock() _ansible_helm_module.run_command = MagicMock()
_ansible_helm_module.run_command.return_value = (0, output, "error") _ansible_helm_module.run_command.return_value = (0, output, "error")
@@ -224,7 +217,6 @@ def test_module_get_helm_version(_ansible_helm_module, output, expected):
def test_module_run_helm_command(_ansible_helm_module): def test_module_run_helm_command(_ansible_helm_module):
error = "".join( error = "".join(
random.choice(string.ascii_letters + string.digits) for x in range(10) random.choice(string.ascii_letters + string.digits) for x in range(10)
) )
@@ -252,7 +244,6 @@ def test_module_run_helm_command(_ansible_helm_module):
@pytest.mark.parametrize("fails_on_error", [True, False]) @pytest.mark.parametrize("fails_on_error", [True, False])
def test_module_run_helm_command_failure(_ansible_helm_module, fails_on_error): def test_module_run_helm_command_failure(_ansible_helm_module, fails_on_error):
error = "".join( error = "".join(
random.choice(string.ascii_letters + string.digits) for x in range(10) random.choice(string.ascii_letters + string.digits) for x in range(10)
) )
@@ -311,7 +302,6 @@ def test_module_run_helm_command_failure(_ansible_helm_module, fails_on_error):
], ],
) )
def test_module_prepare_helm_environment(params, env_update, kubeconfig): def test_module_prepare_helm_environment(params, env_update, kubeconfig):
module = MagicMock() module = MagicMock()
module.params = params module.params = params
@@ -355,7 +345,6 @@ def test_module_prepare_helm_environment(params, env_update, kubeconfig):
def test_module_prepare_helm_environment_with_validate_certs( def test_module_prepare_helm_environment_with_validate_certs(
helm_version, is_env_var_set helm_version, is_env_var_set
): ):
module = MagicMock() module = MagicMock()
module.params = {"validate_certs": False} module.params = {"validate_certs": False}
@@ -387,7 +376,6 @@ def test_module_prepare_helm_environment_with_validate_certs(
], ],
) )
def test_module_prepare_helm_environment_with_ca_cert(helm_version, is_env_var_set): def test_module_prepare_helm_environment_with_ca_cert(helm_version, is_env_var_set):
ca_cert = "".join( ca_cert = "".join(
random.choice(string.ascii_letters + string.digits) for i in range(50) random.choice(string.ascii_letters + string.digits) for i in range(50)
) )
@@ -441,7 +429,6 @@ def test_module_prepare_helm_environment_with_ca_cert(helm_version, is_env_var_s
], ],
) )
def test_module_get_helm_set_values_args(set_values, expected): def test_module_get_helm_set_values_args(set_values, expected):
module = MagicMock() module = MagicMock()
module.params = {} module.params = {}
module.fail_json.side_effect = SystemExit(1) module.fail_json.side_effect = SystemExit(1)

View File

@@ -1,12 +1,11 @@
import pytest
from copy import deepcopy from copy import deepcopy
from unittest.mock import Mock from unittest.mock import Mock
from kubernetes.dynamic.resource import ResourceInstance import pytest
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.runner import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.runner import (
perform_action, perform_action,
) )
from kubernetes.dynamic.resource import ResourceInstance
definition = { definition = {
"apiVersion": "v1", "apiVersion": "v1",

View File

@@ -1,14 +1,12 @@
from unittest.mock import Mock from unittest.mock import Mock
import pytest import pytest
from kubernetes.dynamic.resource import ResourceInstance, Resource
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.service import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.service import (
K8sService, K8sService,
diff_objects, diff_objects,
) )
from kubernetes.dynamic.exceptions import NotFoundError from kubernetes.dynamic.exceptions import NotFoundError
from kubernetes.dynamic.resource import Resource, ResourceInstance
pod_definition = { pod_definition = {
"apiVersion": "v1", "apiVersion": "v1",

View File

@@ -5,20 +5,19 @@ from unittest.mock import Mock
import pytest import pytest
import yaml import yaml
from kubernetes.dynamic.resource import ResourceInstance
from kubernetes.dynamic.exceptions import NotFoundError
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.waiter import ( from ansible_collections.kubernetes.core.plugins.module_utils.k8s.waiter import (
DummyWaiter,
Waiter,
clock, clock,
custom_condition, custom_condition,
deployment_ready, deployment_ready,
DummyWaiter,
exists, exists,
get_waiter, get_waiter,
pod_ready, pod_ready,
resource_absent, resource_absent,
Waiter,
) )
from kubernetes.dynamic.exceptions import NotFoundError
from kubernetes.dynamic.resource import ResourceInstance
def resources(filepath): def resources(filepath):

View File

@@ -7,14 +7,13 @@ from __future__ import absolute_import, division, print_function
__metaclass__ = type __metaclass__ = type
import unittest import unittest
from unittest.mock import patch from unittest.mock import patch
from ansible.module_utils import basic from ansible.module_utils import basic
from ansible_collections.kubernetes.core.plugins.modules import helm_template from ansible_collections.kubernetes.core.plugins.modules import helm_template
from ansible_collections.kubernetes.core.tests.unit.utils.ansible_module_mock import ( from ansible_collections.kubernetes.core.tests.unit.utils.ansible_module_mock import (
AnsibleFailJson,
AnsibleExitJson, AnsibleExitJson,
AnsibleFailJson,
exit_json, exit_json,
fail_json, fail_json,
get_bin_path, get_bin_path,

View File

@@ -7,14 +7,13 @@ from __future__ import absolute_import, division, print_function
__metaclass__ = type __metaclass__ = type
import unittest import unittest
from unittest.mock import MagicMock, call, patch
from unittest.mock import MagicMock, patch, call
from ansible.module_utils import basic from ansible.module_utils import basic
from ansible_collections.kubernetes.core.plugins.modules import helm from ansible_collections.kubernetes.core.plugins.modules import helm
from ansible_collections.kubernetes.core.tests.unit.utils.ansible_module_mock import ( from ansible_collections.kubernetes.core.tests.unit.utils.ansible_module_mock import (
AnsibleFailJson,
AnsibleExitJson, AnsibleExitJson,
AnsibleFailJson,
exit_json, exit_json,
fail_json, fail_json,
get_bin_path, get_bin_path,

33
tox.ini
View File

@@ -2,6 +2,9 @@
minversion = 1.4.2 minversion = 1.4.2
skipsdist = True skipsdist = True
[common]
format_dirs = {toxinidir}/plugins {toxinidir}/tests
[testenv:integration] [testenv:integration]
install_command = pip install {opts} {packages} install_command = pip install {opts} {packages}
@@ -27,19 +30,33 @@ commands =
black -v --check --diff {toxinidir}/plugins {toxinidir}/tests black -v --check --diff {toxinidir}/plugins {toxinidir}/tests
[testenv:black] [testenv:black]
depends =
flynt, isort
deps = deps =
{[testenv:black_check]deps} black >=23.0, <24.0
commands = commands =
black -v {posargs:{toxinidir}/plugins {toxinidir}/tests} black -v {[common]format_dirs}
[testenv:isort]
deps =
isort
commands =
isort --profile black {[common]format_dirs}
[testenv:flynt]
deps =
flynt
commands =
flynt {[common]format_dirs}
[testenv:linters] [testenv:linters]
deps = deps =
yamllint {[testenv:black]deps}
{[testenv:isort]deps}
flake8 flake8
{[testenv:black_check]deps} yamllint
commands = commands =
{[testenv:black_check]commands} black -v --check {toxinidir}/plugins {toxinidir}/tests
isort --profile black --check-only --diff {toxinidir}/plugins {toxinidir}/tests
flake8 {posargs} {toxinidir}/plugins {toxinidir}/tests
yamllint -s {toxinidir} yamllint -s {toxinidir}
flake8 {toxinidir}