Compare commits

..
2 Commits
Author SHA1 Message Date
bd0a376451 kubevirt.core collection cross testing (#731) (#736)
* Initial

* update python version

* update python version

* checkout local version of collection

* add integration job

* indent

* Set workflow as non blocking

(cherry picked from commit c0666a5137)

Co-authored-by: Bikouo Aubin <79859644+abikouo@users.noreply.github.com>
2024-05-31 09:47:10 +02:00
Bikouo AubinandGitHub f22ffcab18 Prepare release 4.0.0 (#727)
* Prepare release 4.0.0

* update documentation
2024-05-28 11:37:32 +02:00
271 changed files with 3738 additions and 13683 deletions
-3
View File
@@ -2,8 +2,5 @@
profile: production
exclude_paths:
- .ansible/
- .github/
- tests/integration
- tests/unit
- tests/sanity
-8
View File
@@ -1,8 +0,0 @@
# https://docs.ansible.com/ansible-lint/docs/rules/
# no-changed-when is not requried for examples
plugins/connection/kubectl.py no-changed-when
# false positive result
plugins/connection/kubectl.py var-naming[no-reserved]
plugins/connection/kubectl.py jinja[invalid]
# collection EE metadata is not an ansible-builder definition file
meta/execution-environment.yml schema[execution-environment]
+60
View File
@@ -0,0 +1,60 @@
---
# Configuration for probot-stale - https://github.com/probot/stale
# Number of days of inactivity before an Issue or Pull Request becomes stale
daysUntilStale: 90
# Number of days of inactivity before an Issue or Pull Request with the stale
# label is closed. Set to false to disable. If disabled, issues still need to be
# closed manually, but will remain marked as stale.
daysUntilClose: 30
# Only issues or pull requests with all of these labels are check if stale.
# Defaults to `[]` (disabled)
onlyLabels: []
# Issues or Pull Requests with these labels will never be considered stale. Set
# to `[]` to disable
exemptLabels:
- security
- planned
- priority/critical
- lifecycle/frozen
- verified
# Set to true to ignore issues in a project (defaults to false)
exemptProjects: false
# Set to true to ignore issues in a milestone (defaults to false)
exemptMilestones: true
# Set to true to ignore issues with an assignee (defaults to false)
exemptAssignees: false
# Label to use when marking as stale
staleLabel: lifecycle/stale
# Limit the number of actions per hour, from 1-30. Default is 30
limitPerRun: 30
pulls:
markComment: |-
PRs go stale after 90 days of inactivity.
If there is no further activity, the PR will be closed in another 30 days.
unmarkComment: >-
This pull request is no longer stale.
closeComment: >-
This pull request has been closed due to inactivity.
issues:
markComment: |-
Issues go stale after 90 days of inactivity.
If there is no further activity, the issue will be closed in another 30 days.
unmarkComment: >-
This issue is no longer stale.
closeComment: >-
This issue has been closed due to inactivity.
-121
View File
@@ -1,121 +0,0 @@
---
name: all_green
concurrency:
group: ${{ github.head_ref || github.ref }}
cancel-in-progress: true
on: # yamllint disable-line rule:truthy
pull_request:
types:
- opened
- reopened
- synchronize
branches:
- main
- stable-*
push:
branches:
- main
- stable-*
jobs:
security-check:
if: github.event_name == 'pull_request'
uses: ./.github/workflows/security-check.yaml
linters:
if: github.event_name == 'pull_request'
uses: ./.github/workflows/linters.yaml
sanity:
uses: ./.github/workflows/sanity-tests.yaml
units:
uses: ./.github/workflows/unit-tests.yaml
coverage:
name: Unit test coverage
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
path: ansible_collections/kubernetes/core
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Run unit tests with coverage
working-directory: ansible_collections/kubernetes/core
env:
PYTHONPATH: ${{ github.workspace }}
run: |
python -m pip install --upgrade pip
python -m pip install ansible-compat
python -m pip install https://github.com/ansible/ansible/archive/stable-2.19.tar.gz
# Same deps as the units matrix (build_install_collection); do not use
# tests/unit/requirements.txt — its kubernetes pin breaks test_core.py.
python -m pip install -r requirements.txt -r test-requirements.txt
python -m coverage run --source=plugins -m pytest tests/unit \
--ansible-host-pattern localhost
python -m coverage xml -o coverage.xml
- name: Upload coverage artifact
uses: actions/upload-artifact@v4
with:
name: coverage
path: ansible_collections/kubernetes/core/coverage.xml
all_green:
if: ${{ always() }}
needs:
- security-check
- linters
- sanity
- units
- coverage
runs-on: ubuntu-latest
steps:
- run: |
python -c "
import sys
required = ['sanity', 'units', 'coverage']
if '${{ github.event_name }}' == 'pull_request':
required = ['security-check', 'linters', 'sanity', 'units', 'coverage']
results = {
'security-check': '${{ needs.security-check.result }}',
'linters': '${{ needs.linters.result }}',
'sanity': '${{ needs.sanity.result }}',
'units': '${{ needs.units.result }}',
'coverage': '${{ needs.coverage.result }}',
}
for name in required:
if results[name] == 'failure':
print(f'all_green: required job failed: {name} results={results}', file=sys.stderr)
sys.exit(1)
# cancel-in-progress superseded this run; do not fail (newer run is authoritative)
if any(v == 'cancelled' for v in results.values()):
print(
'all_green: one or more jobs cancelled (usually concurrency); skipping strict gate.',
results,
)
sys.exit(0)
not_ok = [j for j in required if results[j] != 'success']
if not_ok:
print(f'all_green: required jobs not success: {not_ok} results={results}', file=sys.stderr)
sys.exit(1)
for job, status in results.items():
if job not in required and status not in ('success', 'skipped'):
print(f'all_green: unexpected {job}={status} results={results}', file=sys.stderr)
sys.exit(1)
print('all_green OK', results)
"
-20
View File
@@ -1,20 +0,0 @@
---
name: Run collection certification checks
permissions:
contents: read
on:
pull_request:
branches:
- main
- stable-*
workflow_dispatch:
concurrency:
group: cert-ver-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
call:
uses: ansible-collections/partner-certification-checker/.github/workflows/certification-reusable.yml@f4bf7ba4d3f008b2db8fc6a812fa3f89fdf42c2e # v4.1.0
@@ -0,0 +1,127 @@
name: Integration tests Kubevirt
on:
pull_request:
types:
- opened
- reopened
- synchronize
branches:
- main
- stable-*
jobs:
splitter:
continue-on-error: true
env:
kubernetes: "./kubernetes"
kubevirt: "./kubevirt"
py_version: 3.9
runs-on: ubuntu-latest
outputs:
test_targets: ${{ steps.splitter.outputs.kubevirt_targets }}
steps:
- name: Checkout kubernetes.core repository
uses: actions/checkout@v3
with:
path: ${{ env.kubernetes }}
ref: ${{ github.event.pull_request.head.sha }}
- name: Checkout the kubevirt.core collection
uses: actions/checkout@v3
with:
repository: kubevirt/kubevirt.core
path: ${{ env.kubevirt }}
- name: "Set up Python ${{ env.py_version }}"
uses: actions/setup-python@v4
with:
python-version: "${{ env.py_version }}"
- name: List targets from kubevirt.core collection
id: splitter
run: python ${{ env.kubernetes }}/tools/kubevirt_list_targets.py ${{ env.kubevirt }}
shell: bash
integration:
if: ${{ needs.splitter.outputs.test_targets != '' }}
name: "integration-kubevirt-${{ matrix.test-target }}"
runs-on: ubuntu-latest
continue-on-error: true
needs:
- splitter
env:
kubernetes: "./kubernetes"
kubevirt: "./kubevirt"
ansible_version: milestone
python_version: 3.12
strategy:
fail-fast: false
matrix:
test-target: ${{ fromJson(needs.splitter.outputs.test_targets) }}
steps:
- name: Checkout kubernetes.core repository
uses: actions/checkout@v4
with:
path: ${{ env.kubernetes }}
ref: ${{ github.event.pull_request.head.sha }}
- name: Checkout kubevirt.core repository
uses: actions/checkout@v4
with:
repository: kubevirt/kubevirt.core
path: ${{ env.kubevirt }}
ref: main
# Install ansible
- name: Install ansible-core (${{ env.ansible_version }})
run: >-
python3 -m pip install
https://github.com/ansible/ansible/archive/${{ env.ansible_version }}.tar.gz
--disable-pip-version-check
shell: bash
- name: Build and install kubevirt.core collection
id: install-kubevirt
uses: ansible-network/github_actions/.github/actions/build_install_collection@main
with:
install_python_dependencies: true
source_path: ${{ env.kubevirt }}
- name: Build and install kubernetes.core collection
id: install-kubernetes
uses: ansible-network/github_actions/.github/actions/build_install_collection@main
with:
install_python_dependencies: true
source_path: ${{ env.kubernetes }}
- name: Install kind / kubectl
uses: helm/kind-action@v1.9.0
with:
version: v0.22.0
install_only: true
- name: Deploy kubevirt
run: >-
${{ env.kubevirt }}/hack/e2e-setup.sh \
-v \
--configure-inotify-limits \
--configure-secondary-network \
--deploy-kubevirt \
--deploy-kubevirt-cdi \
--deploy-kubevirt-common-instancetypes \
--deploy-cnao \
--create-cluster \
--create-nad
env:
KIND: kind
KUBECTL: kubectl
- name: Run integration tests
uses: ansible-network/github_actions/.github/actions/ansible_test_integration@main
with:
collection_path: ${{ steps.install-kubevirt.outputs.collection_path }}
python_version: ${{ env.python_version }}
ansible_version: ${{ env.ansible_version }}
ansible_test_targets: ${{ matrix.test-target }}
env:
ANSIBLE_COLLECTIONS_PATHS: /home/runner/collections
+8 -39
View File
@@ -26,7 +26,6 @@ jobs:
with:
path: ${{ env.source_dir }}
fetch-depth: "0"
ref: ${{ github.event.pull_request.head.sha }}
- name: list changes for pull request
id: splitter
@@ -51,33 +50,18 @@ jobs:
source: "./source"
cloud_common: "./cloudcommon"
ansible_posix: "./ansible_posix"
community_general: "./community_general"
strategy:
fail-fast: false
matrix:
# Ref must match a branch/tag on github.com/ansible/ansible (e.g. stable-2.18, not 2.18).
#
ansible-version: ["stable-2.18", "stable-2.21", "milestone"]
enable-turbo-mode: [true, false]
python-version: ["3.12", "3.13"]
exclude:
# stable-2.18 is used mainly because turbo mode, no reason to test it with turbo mode disabled
- ansible-version: "stable-2.18"
enable-turbo-mode: false
# turbo mode is supported only by ansible<2.19
- ansible-version: "milestone"
enable-turbo-mode: true
- ansible-version: "stable-2.21"
enable-turbo-mode: true
# stable-2.18 supports 3.12
- ansible-version: "stable-2.18"
python-version: "3.13"
- ansible-version: "stable-2.21"
python-version: "3.12"
- ansible-version: "milestone"
python-version: "3.12"
ansible-version:
- milestone
python-version:
- "3.12"
enable-turbo-mode:
- true
- false
workflow-id: ${{ fromJson(needs.splitter.outputs.test_jobs) }}
name: Integration tests
name: "integration-py${{ matrix.python-version }}-${{ matrix.ansible-version }}-${{ matrix.workflow-id }}"
steps:
- name: Read target
id: read-targets
@@ -121,7 +105,6 @@ jobs:
source_path: ${{ env.source }}
- name: checkout ansible-collections/cloud.common
if: ${{ matrix.enable-turbo-mode == true }}
uses: ansible-network/github_actions/.github/actions/checkout_dependency@main
with:
repository: ansible-collections/cloud.common
@@ -135,15 +118,7 @@ jobs:
path: ${{ env.ansible_posix }}
ref: main
- name: checkout ansible-collections/community.general
uses: ansible-network/github_actions/.github/actions/checkout_dependency@main
with:
repository: ansible-collections/community.general
path: ${{ env.community_general }}
ref: main
- name: install cloud.common collection
if: ${{ matrix.enable-turbo-mode == true }}
uses: ansible-network/github_actions/.github/actions/build_install_collection@main
with:
install_python_dependencies: true
@@ -155,12 +130,6 @@ jobs:
install_python_dependencies: true
source_path: ${{ env.ansible_posix }}
- name: install community.general collection
uses: ansible-network/github_actions/.github/actions/build_install_collection@main
with:
install_python_dependencies: false
source_path: ${{ env.community_general }}
- name: create kubernetes cluster
uses: helm/kind-action@v1.8.0
with:
-28
View File
@@ -1,28 +0,0 @@
---
name: label new prs
on:
pull_request_target:
types:
- opened
- reopened
- converted_to_draft
- ready_for_review
jobs:
add_label:
if: github.actor != 'patchback[bot]'
runs-on: ubuntu-latest
permissions:
pull-requests: write
steps:
- name: Add 'needs_triage' label if the pr is not a draft
uses: actions-ecosystem/action-add-labels@v1
if: github.event.pull_request.draft == false
with:
labels: needs_triage
- name: Remove 'needs_triage' label if the pr is a draft
uses: actions-ecosystem/action-remove-labels@v1
if: github.event.pull_request.draft == true
with:
labels: needs_triage
+13 -5
View File
@@ -1,7 +1,16 @@
---
name: Linters
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
on: [workflow_call]
on:
pull_request:
branches:
- main
- stable-*
tags:
- '*'
jobs:
linters:
@@ -10,7 +19,6 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: run-ansible-lint
uses: ansible/ansible-lint@main
with:
gh_action_ref: "v25.5.0"
- name: Run ansible-lint
uses: ansible/ansible-lint@v24.2.3
+8 -1
View File
@@ -1,7 +1,14 @@
---
name: Sanity tests
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
on: [workflow_call]
on:
pull_request:
branches:
- main
- stable-*
jobs:
sanity:
-17
View File
@@ -1,17 +0,0 @@
---
name: Security Check
on: [workflow_call]
jobs:
security-check:
name: Block unsafe directories
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Check for blocked directories
uses: ansible/cloud-content-ci-automation/.github/actions/security_check_directories@74b5fe870e1d5346c5fcea332b97a6fb26f1ad8a
-89
View File
@@ -1,89 +0,0 @@
## SonarCloud Analysis Workflow for kubernetes.core
#
# This workflow runs SonarCloud analysis triggered by all_green workflow completion.
#
# FLOW: all_green completes (linters, ansible-test, coverage) → workflow_run triggers this workflow → finalize job runs
#
# - Triggered by: workflow_run (all_green on pull_request or push to main/stable-*)
# - Steps: Checkout → Download coverage from all_green run → Get PR info (if PR) → Run SonarCloud scan
# - Coverage: Unit test coverage is produced by the coverage job in all_green and passed to SonarCloud here.
---
name: SonarCloud
on:
workflow_run:
workflows:
- all_green
types:
- completed
permissions:
contents: read
pull-requests: read
actions: read
jobs:
finalize:
name: finalize
runs-on: ubuntu-latest
if: github.event.workflow_run.conclusion == 'success'
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
ref: ${{ github.event.workflow_run.head_sha }}
fetch-depth: 0
show-progress: false
- name: Download coverage artifacts
uses: dawidd6/action-download-artifact@2536c51d3d126276eb39f74d6bc9c72ac6ef30d3 # v16
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
workflow: all_green
run_id: ${{ github.event.workflow_run.id }}
pattern: coverage*
- name: Set coverage report paths
run: |
coverage_files=$(find . -name "coverage*.xml" -type f 2>/dev/null | tr '\n' ',' | sed 's/,$//')
echo "Found coverage files: ${coverage_files:-none}"
echo "COVERAGE_PATHS=${coverage_files}" >> "${GITHUB_ENV}"
- name: Get PR number and info
if: github.event.workflow_run.event == 'pull_request'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }}
REPO: ${{ github.repository }}
run: |
PR_NUMBER=$(gh pr list --head "$HEAD_BRANCH" --repo "$REPO" --json number -q '.[0].number')
echo "PR_NUMBER=${PR_NUMBER}" >> "${GITHUB_ENV}"
if [ -n "${PR_NUMBER}" ]; then
PR_DATA=$(gh api "repos/${REPO}/pulls/${PR_NUMBER}")
echo "PR_BASE=$(echo "${PR_DATA}" | jq -r '.base.ref')" >> "${GITHUB_ENV}"
echo "PR_HEAD=$(echo "${PR_DATA}" | jq -r '.head.ref')" >> "${GITHUB_ENV}"
fi
- name: Prepare SonarCloud args
env:
COMMIT_SHA: ${{ github.event.workflow_run.head_sha }}
EVENT_TYPE: ${{ github.event.workflow_run.event }}
run: |
SONAR_ARGS="-Dsonar.scm.revision=\"${COMMIT_SHA}\""
if [[ "${EVENT_TYPE}" == "pull_request" && -n "${PR_NUMBER:-}" ]]; then
SONAR_ARGS="${SONAR_ARGS} -Dsonar.pullrequest.key=${PR_NUMBER}"
SONAR_ARGS="${SONAR_ARGS} -Dsonar.pullrequest.branch=${PR_HEAD}"
SONAR_ARGS="${SONAR_ARGS} -Dsonar.pullrequest.base=${PR_BASE}"
fi
if [[ -n "${COVERAGE_PATHS:-}" ]]; then
SONAR_ARGS="${SONAR_ARGS} -Dsonar.python.coverage.reportPaths=${COVERAGE_PATHS}"
fi
echo "SONAR_ARGS=${SONAR_ARGS}" >> "${GITHUB_ENV}"
- name: SonarCloud Scan
uses: SonarSource/sonarqube-scan-action@a31c9398be7ace6bbfaf30c0bd5d415f843d45e9 # v7
env:
SONAR_TOKEN: ${{ secrets.ANSIBLE_COLLECTIONS_ORG_SONAR_TOKEN_CICD_BOT }}
with:
args: ${{ env.SONAR_ARGS }}
+8 -1
View File
@@ -1,6 +1,13 @@
name: Unit tests
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
on: [workflow_call]
on:
pull_request:
branches:
- main
- stable-*
jobs:
unit-source:
-9
View File
@@ -13,19 +13,10 @@ changelogs/.plugin-cache.yaml
tests/output
tests/integration/cloud-config-*
.cache
.ansible
# Helm charts
tests/integration/*-chart-*.tgz
tests/integration/targets/*/*.tgz
# ansible-test generated file
tests/integration/inventory
tests/integration/*-*.yml
# IDE and editor settings
.vscode/
.claude/
# Root coverage report for SonarCloud (generated locally or in CI)
/coverage.xml
-6
View File
@@ -1,6 +0,0 @@
repos:
- repo: https://github.com/ansible/cloud-content-ci-automation
rev: precommit_hook
hooks:
- id: block-ide-ai-files
always_run: true
-9
View File
@@ -5,25 +5,16 @@ rules:
braces:
max-spaces-inside: 1
level: error
brackets:
max-spaces-inside: 1
level: error
comments:
min-spaces-from-content: 1
comments-indentation: false
document-start: disable
line-length: disable
truthy: disable
indentation:
spaces: 2
indent-sequences: consistent
octal-values:
forbid-implicit-octal: true
forbid-explicit-octal: true
ignore: |
.cache
.tox
.ansible
tests/output
plugins/connection/kubectl.py
-347
View File
@@ -4,306 +4,6 @@ Kubernetes Collection Release Notes
.. contents:: Topics
v6.6.0
======
Minor Changes
-------------
- Remove the remaining ``ansible.module_utils.six`` import to avoid deprecation warnings, replacing it with the Python standard library equivalent (https://github.com/ansible-collections/kubernetes.core/pull/1197).
- helm - Add ``wait_for_jobs`` option to wait for all Jobs to complete before marking a Helm release as successful. Requires Helm >= 3.5.0 (https://github.com/ansible-collections/kubernetes.core/pull/1140).
- helm - add the ``cleanup_on_fail`` option, mapping to the ``--cleanup-on-fail`` flag, to allow deletion of new resources created during a failed upgrade. It complements ``atomic`` and can be combined with it, but cannot be used with ``replace``, since that deploys through ``helm install`` which does not accept the flag (https://github.com/ansible-collections/kubernetes.core/pull/1206).
- helm - warn when ``reuse_values`` or ``reset_then_reuse_values`` is requested in a combination helm ignores, which happens by default because ``reset_values`` defaults to ``true``, and whenever either is combined with ``replace``. The option descriptions and the examples now state that ``reset_values`` has to be set to ``false`` for either option to take effect (https://github.com/ansible-collections/kubernetes.core/pull/1230).
- k8s lookup - warn when ``ENABLE_TURBO_MODE`` is set but the ``cloud.common`` collection is not installed, instead of silently falling back to the standard lookup base (https://github.com/ansible-collections/kubernetes.core/pull/1242).
- k8s_cp - Add the ``copy_timeout`` option (default 300 seconds) bounding how long the module will spend streaming an archive to a pod and waiting for the remote ``tar`` to finish, so that a stalled copy fails instead of hanging indefinitely (https://github.com/ansible-collections/kubernetes.core/pull/1217).
- k8s_cp - Stream the tar archive to the pod chunk by chunk instead of building the whole archive in memory first, which cuts peak memory use when copying large files (https://github.com/ansible-collections/kubernetes.core/pull/1217).
- k8s_cp - When copying to a pod, the module now also uses ``/bin/sh`` and ``head`` in the container, when present, to confirm the copy completed. Containers without them keep the previous behaviour and get a warning that completion could not be verified (https://github.com/ansible-collections/kubernetes.core/pull/1217).
- k8s_info - Support for metadata-only fetches in k8s_info module (https://github.com/ansible-collections/kubernetes.core/pull/1030)
- meta - Add ``helm_plugin`` and ``helm_plugin_info`` to the ``helm`` action group, and ``k8s_taint`` to the ``k8s`` action group, so that ``module_defaults`` set on those groups applies to them (https://github.com/ansible-collections/kubernetes.core/pull/1216).
- use `collections.abc` instead of deprecated `ansible.module_utils.common._collections_compat` (https://github.com/ansible-collections/kubernetes.core/pull/1057).
- waiter - Add ``job_complete`` predicate to support waiting for Job resources to reach ``Complete`` or ``Failed`` condition (https://github.com/ansible-collections/kubernetes.core/issues/1201).
Deprecated Features
-------------------
- Ansible Turbo mode (``ENABLE_TURBO_MODE``) has been deprecated and will be removed in release 8.0.0, as it depends on the ``cloud.common`` collection, which is being retired (https://github.com/ansible-collections/kubernetes.core/pull/1242).
- helm - the ``status.values`` return value has been deprecated and will be removed in version 8.0.0. Use ``status.release_values`` instead (https://github.com/ansible-collections/kubernetes.core/issues/1239).
- helm - the ``wait_timeout`` parameter has been deprecated and will be removed in version 7.0.0. Use ``timeout`` instead (https://github.com/ansible-collections/kubernetes.core/issues/1239).
- helm_info - the ``status.values`` return value has been deprecated and will be removed in version 8.0.0. Use ``status.release_values`` instead (https://github.com/ansible-collections/kubernetes.core/issues/1239).
- k8s_exec - the ``return_code`` return value has been deprecated and will be removed in version 7.0.0. Use ``rc`` instead (https://github.com/ansible-collections/kubernetes.core/issues/1239).
- k8s_service - the ``merge_type=json`` option has been deprecated and will be removed in version 7.0.0. Use ``kubernetes.core.k8s_json_patch`` module instead (https://github.com/ansible-collections/kubernetes.core/issues/1239).
Bugfixes
--------
- Ansible Turbo mode - ignore ``ENABLE_TURBO_MODE`` on ansible-core 2.19.0 and later, where the ``cloud.common`` collection is not supported, and fall back to the standard ``AnsibleModule`` instead of failing with ``byte indices must be integers or slices, not str`` (https://github.com/ansible-collections/kubernetes.core/pull/1242).
- helm - do not pass the upgrade-only ``--reuse-values`` and ``--reset-then-reuse-values`` flags to ``helm install``, which rejected them with ``unknown flag`` whenever ``reuse_values`` or ``reset_then_reuse_values`` was combined with ``replace`` (https://github.com/ansible-collections/kubernetes.core/pull/1230).
- helm - fix the ``reuse_values`` example, which set only ``reuse_values=true``. ``reset_values`` defaults to ``true`` and helm ignores ``--reuse-values`` whenever ``--reset-values`` is passed, so following the example reset the release values instead of reusing them (https://github.com/ansible-collections/kubernetes.core/pull/1230).
- helm - skip Helm's OCI registry progress messages when parsing the output of ``helm show chart``. As of Helm 4.2.1 these are printed to stdout instead of stderr (https://github.com/helm/helm/pull/32056), which made installing a chart from an OCI registry fail with a YAML scanner error when the chart version contained a ``+`` (https://github.com/ansible-collections/kubernetes.core/pull/1223).
- helm_repository - normalize both sides of the repository URL comparison, so that a repository already registered with a trailing slash is recognized as matching instead of failing with ``Repository already have a repository named <name>`` (https://github.com/ansible-collections/kubernetes.core/pull/1236).
- helm_template - strip Helm's OCI registry progress messages from the returned ``stdout``, which is documented to contain only the rendered templates (https://github.com/ansible-collections/kubernetes.core/pull/1223).
- k8s lookup - ignore ``ENABLE_TURBO_MODE`` on ansible-core 2.19.0 and later, where the ``cloud.common`` collection is not supported. Fall back to the standard ``LookupBase`` instead of failing with a traceback (https://github.com/ansible-collections/kubernetes.core/pull/1253).
- k8s_cp - Fix silent truncation when copying to a pod. The module closed the exec connection immediately after writing the last chunk of the tar archive, which killed the remote ``tar`` before it had finished extracting, and never checked the process exit status, so a partial copy was reported as a success. The archive is now bounded with ``head -c`` so ``tar`` gets a clean EOF and exits on its own, and the module waits for that exit and fails on a non-zero status (https://github.com/ansible-collections/kubernetes.core/pull/1217).
- k8s_info - Handle empty template output gracefully by returning ``changed=false`` instead of failing when Jinja2 template renders to an empty string (https://github.com/ansible-collections/kubernetes.core/issues/1042).
v6.5.0
======
Release Summary
---------------
This release implements minor changes and bug fixes such as a new ``remove`` value to the ``behavior`` option of the ``kubeconfig`` module, allowing entries to be deleted from the kubeconfig file by name, as well as Helm v4 compatibility across the Helm modules.
Minor Changes
-------------
- helm - add the ``server_side`` and ``force_conflicts`` options to control Helm v4 server-side apply when installing or upgrading a release (https://github.com/ansible-collections/kubernetes.core/pull/1164).
- helm_plugin - add ``--keyring`` argument to allow changing the keyring default location. The option is only accepted with ``state=present`` (the ``helm plugin install`` subcommand), as that is the only implemented subcommand that supports ``--keyring`` (https://github.com/ansible-collections/kubernetes.core/pull/1150).
- helm_registry_auth - document that, as of Helm 4.2.1, registry success messages such as ``Login Succeeded`` are printed to stdout instead of stderr (https://github.com/ansible-collections/kubernetes.core/pull/1147).
- kubeconfig - add ``remove`` value to the ``behavior`` option, allowing entries to be deleted from the kubeconfig file by name (https://github.com/ansible-collections/kubernetes.core/pull/1123).
Bugfixes
--------
- ee - added ``meta/execution-environment.yml`` to decouple ansible-builder EE builds from the ``openshift-clients`` system dependency declared in ``bindep.txt``, which is not available in standard UBI repositories and caused builds to fail with ``No package matches 'openshift-clients'`` (https://github.com/ansible-collections/kubernetes.core/issues/1141).
- helm - use ``--server-side=false --force-replace`` instead of the deprecated/removed ``--force`` flag when ``force=true`` is used with Helm v4, preserving the Helm v3 client-side replacement behaviour and avoiding the server-side apply conflict (https://github.com/ansible-collections/kubernetes.core/pull/1164).
- helm - use the ``--rollback-on-failure`` flag instead of the deprecated/removed ``--atomic`` flag when ``atomic=true`` is used with Helm v4 (https://github.com/ansible-collections/kubernetes.core/pull/1144).
- helm_repository - correct handling of repository URLs with trailing slashes (https://github.com/ansible-collections/kubernetes.core/pull/1121).
- k8s_drain - Fix logic for handling pods with local storage to correctly check for empty_dir volumes in replicated pods and pods managed by DaemonSets (https://github.com/ansible-collections/kubernetes.core/pull/1095).
New Modules
-----------
- kubeconfig - Generate, update, and optionally write Kubernetes kubeconfig files
v6.4.0
======
Release Summary
---------------
This release adds Helm v4 compatibility across the Helm modules and improves ``k8s_drain`` with check mode. When you explicitly allow evicting unmanaged pods, pods with local storage, or pods managed by a ``DaemonSet``, those cases are reported as informational output instead of module warnings.
Minor Changes
-------------
- helm_info - Ensure compatibility with Helm v4 (https://github.com/ansible-collections/kubernetes.core/issues/1038).
- helm_plugin - Ensure compatibility with Helm v4 (https://github.com/ansible-collections/kubernetes.core/issues/1038).
- helm_plugin_info - Ensure compatibility with Helm v4 (https://github.com/ansible-collections/kubernetes.core/issues/1038).
- helm_pull - Ensure compatibility with Helm v4 (https://github.com/ansible-collections/kubernetes.core/issues/1038).
- helm_registry_auth - Ensure compatibility with Helm v4 (https://github.com/ansible-collections/kubernetes.core/issues/1038).
- helm_registry_auth - add new option plain_http to allow insecure http connection when running ``helm registry login`` (https://github.com/ansible-collections/kubernetes.core/pull/1090).
- helm_repository - Ensure compatibility with Helm v4 (https://github.com/ansible-collections/kubernetes.core/issues/1038).
- k8s_drain - Add support for ``check_mode`` (https://github.com/ansible-collections/kubernetes.core/pull/1086).
- k8s_drain - Convert module warnings into informational displays when users explicitly request the deletion of unmanaged pods, pods with local storage, or those managed by a ``DaemonSet`` (https://github.com/ansible-collections/kubernetes.core/issues/1037).
Bugfixes
--------
- Helm - Allow taking ownership of existing Kubernetes resources on the first installation of a Helm release. Previously, the ``take_ownership`` parameter was always disabled during the initial install, preventing resource adoption (https://github.com/ansible-collections/kubernetes.core/pull/1034).
v6.3.0
======
Release Summary
---------------
This release includes bugfixes such as implementing idempotency for the ``helm_pull`` module as well as a security update for selectively redacting sensitive information from kubeconfig.
Minor Changes
-------------
- Remove deprecated import from ``ansible.module_utils._text`` (https://github.com/ansible-collections/kubernetes.core/pull/1053).
- helm - add ``release_values`` key to ``status`` return value that can be accessed using Jinja2 dot notation (https://github.com/ansible-collections/kubernetes.core/pull/1056).
- helm_info - add ``release_values`` key to ``status`` return value that can be accessed using Jinja2 dot notation (https://github.com/ansible-collections/kubernetes.core/pull/1056).
Deprecated Features
-------------------
- helm - the ``status.values`` return value has been deprecated and will be removed in a release after 2027-01-08. Use ``status.release_values`` instead (https://github.com/ansible-collections/kubernetes.core/pull/1056).
- helm_info - the ``status.values`` return value has been deprecated and will be removed in a release after 2027-01-08. Use ``status.release_values`` instead (https://github.com/ansible-collections/kubernetes.core/pull/1056).
Security Fixes
--------------
- Selectively redact sensitive info from kubeconfig instead of applying blanket ``no_log=True`` (https://github.com/ansible-collections/kubernetes.core/pull/1014).
Bugfixes
--------
- Add idempotency for ``helm_pull`` module (https://github.com/ansible-collections/kubernetes.core/pull/1055).
- Fixed a bug where setting ``K8S_AUTH_VERIFY_SSL=true`` (or any string value) caused the value to be treated as a separate ``kubectl`` command argument. (https://github.com/ansible-collections/kubernetes.core/pull/1049).
- Limit supported versions of Helm to <4.0.0 (https://github.com/ansible-collections/kubernetes.core/pull/1039).
- Replace passing ``warnings`` to ``exit_json`` with ``AnsibleModule.warn`` in the ``k8s_drain``, ``k8s_rollback.py`` and ``k8s_scale.py`` modules as it deprecated in ``ansible-core>=2.19.0`` and will be removed in ``ansible-core>=2.23.0`` (https://github.com/ansible-collections/kubernetes.core/pull/1033).
- k8s - Fix return block from the module documentation (https://github.com/ansible-collections/kubernetes.core/pull/1056).
- meta - Add ``k8s_cluster_info``, ``k8s_json_patch`` and ``k8s_rollback`` to k8s action group (https://github.com/ansible-collections/kubernetes.core/pull/992).
v6.2.0
======
Release Summary
---------------
This release adds minor changes and bugfixes, including support of skip-schema-validation in ``helm`` module and removing deprecated ``ansible.module_utils.six`` imports.
Minor Changes
-------------
- Add support of skip-schema-validation in ``helm`` module (https://github.com/ansible-collections/kubernetes.core/pull/995)
- kustomize - Add support of local environ (https://github.com/ansible-collections/kubernetes.core/pull/786).
Bugfixes
--------
- Remove ``ansible.module_utils.six`` imports to avoid warnings (https://github.com/ansible-collections/kubernetes.core/pull/998).
- Update the ``k8s_cp`` module to also work for init containers (https://github.com/ansible-collections/kubernetes.core/pull/971).
v6.1.0
======
Release Summary
---------------
This release adds ``plain_http`` and ``take_ownership`` parameters for helm modules, support for ``hidden_fields`` in ``k8s_json_patch``, documented lack of idempotency support in ``helm_registry_auth`` with ``helm ≥ 3.18.0``, and improved ``k8s_rollback`` test coverage.
Minor Changes
-------------
- Module ``helm_registry_auth`` does not support idempotency with `helm >= 3.18.0` (https://github.com/ansible-collections/kubernetes.core/pull/946).
- Module k8s_json_patch - Add support for ``hidden_fields`` (https://github.com/ansible-collections/kubernetes.core/pull/964).
- helm - Parameter plain_http added for working with insecure OCI registries (https://github.com/ansible-collections/kubernetes.core/pull/934).
- helm - Parameter take_ownership added (https://github.com/ansible-collections/kubernetes.core/pull/957).
- helm_pull - Parameter plain_http added for working with insecure OCI registries (https://github.com/ansible-collections/kubernetes.core/pull/934).
- helm_template - Parameter plain_http added for working with insecure OCI registries (https://github.com/ansible-collections/kubernetes.core/pull/934).
Bugfixes
--------
- module_utils/k8s/service - hide fields first before creating diffs (https://github.com/ansible-collections/kubernetes.core/pull/915).
v6.0.0
======
Breaking Changes / Porting Guide
--------------------------------
- Remove deprecated ``k8s`` invetory plugin (https://github.com/ansible-collections/kubernetes.core/pull/867).
- Remove support for ``ansible-core<2.16`` (https://github.com/ansible-collections/kubernetes.core/pull/867).
v5.4.1
======
Release Summary
---------------
This release includes bugfixes for k8s service field handling, k8s_cp init containers support, and removes deprecated ansible.module_utils.six imports.
Bugfixes
--------
- Remove ``ansible.module_utils.six`` imports to avoid warnings (https://github.com/ansible-collections/kubernetes.core/pull/998).
- Update the ``k8s_cp`` module to also work for init containers (https://github.com/ansible-collections/kubernetes.core/pull/971).
- module_utils/k8s/service - hide fields first before creating diffs (https://github.com/ansible-collections/kubernetes.core/pull/915).
v5.4.0
======
Release Summary
---------------
This release updates the ``helm_registry_auth`` module to match the behavior of ``helm >= 3.18.0`` which reports a successful logout regardless of the current state (i.e., no idempotency).
Minor Changes
-------------
- Module ``helm_registry_auth`` does not support idempotency with ``helm >= 3.18.0`` (https://github.com/ansible-collections/kubernetes.core/pull/946).
v5.3.0
======
Release Summary
---------------
This release includes minor changes, bug fixes and also bumps ``ansible-lint`` version to ``25.1.2``.
Minor Changes
-------------
- Bump version of ``ansible-lint`` to 25.1.2 (https://github.com/ansible-collections/kubernetes.core/pull/919).
- action/k8s_info - update templating mechanism with changes from ``ansible-core 2.19`` (https://github.com/ansible-collections/kubernetes.core/pull/888).
- helm - add ``reset_then_reuse_values`` support to helm module (https://github.com/ansible-collections/kubernetes.core/issues/803).
- helm - add support for ``insecure_skip_tls_verify`` option to helm and helm_repository(https://github.com/ansible-collections/kubernetes.core/issues/694).
Bugfixes
--------
- module_utils/k8s/service - fix issue when trying to delete resource using ``delete_options`` and ``check_mode=true`` (https://github.com/ansible-collections/kubernetes.core/issues/892).
v5.2.0
======
Release Summary
---------------
This release adds more functionality to the hidden_fields option and support for waiting on ClusterOperators to reach a ready state.
Minor Changes
-------------
- k8s - Extend hidden_fields to allow the expression of more complex field types to be hidden (https://github.com/ansible-collections/kubernetes.core/pull/872)
- k8s_info - Extend hidden_fields to allow the expression of more complex field types to be hidden (https://github.com/ansible-collections/kubernetes.core/pull/872)
- waiter.py - add ClusterOperator support. The module can now check OpenShift cluster health by verifying ClusterOperator status requiring 'Available: True', 'Degraded: False', and 'Progressing: False' for success. (https://github.com/ansible-collections/kubernetes.core/issues/869)
v5.1.0
======
Release Summary
---------------
This release came with new module ``helm_registry_auth``, improvements to the error messages in the k8s_drain module, new parameter ``insecure_registry`` for ``helm_template`` module and several bug fixes.
Minor Changes
-------------
- Bump version of ``ansible-lint`` to minimum 24.7.0 (https://github.com/ansible-collections/kubernetes.core/pull/765).
- Parameter insecure_registry added to helm_template as equivalent of insecure-skip-tls-verify (https://github.com/ansible-collections/kubernetes.core/pull/805).
- k8s_drain - Improve error message for pod disruption budget when draining a node (https://github.com/ansible-collections/kubernetes.core/issues/797).
Bugfixes
--------
- helm - Helm version checks did not support RC versions. They now accept any version tags. (https://github.com/ansible-collections/kubernetes.core/pull/745).
- helm_pull - Apply no_log=True to pass_credentials to silence false positive warning. (https://github.com/ansible-collections/kubernetes.core/pull/796).
- k8s_drain - Fix k8s_drain does not wait for single pod (https://github.com/ansible-collections/kubernetes.core/issues/769).
- k8s_drain - Fix k8s_drain runs into a timeout when evicting a pod which is part of a stateful set (https://github.com/ansible-collections/kubernetes.core/issues/792).
- kubeconfig option should not appear in module invocation log (https://github.com/ansible-collections/kubernetes.core/issues/782).
- kustomize - kustomize plugin fails with deprecation warnings (https://github.com/ansible-collections/kubernetes.core/issues/639).
- waiter - Fix waiting for daemonset when desired number of pods is 0. (https://github.com/ansible-collections/kubernetes.core/pull/756).
New Modules
-----------
- helm_registry_auth - Helm registry authentication module
v5.0.0
======
Release Summary
---------------
This major release drops support for ``ansible-core<2.15``.
Minor Changes
-------------
- connection/kubectl.py - Added an example of using the kubectl connection plugin to the documentation (https://github.com/ansible-collections/kubernetes.core/pull/741).
- inventory/k8s.py - Defer removal of k8s inventory plugin to version 6.0.0 (https://github.com/ansible-collections/kubernetes.core/pull/734).
Breaking Changes / Porting Guide
--------------------------------
- Remove support for ``ansible-core<2.15`` (https://github.com/ansible-collections/kubernetes.core/pull/737).
v4.0.0
======
@@ -337,53 +37,6 @@ Bugfixes
- helm - use ``reuse-values`` when running ``helm diff`` command (https://github.com/ansible-collections/kubernetes.core/issues/680).
- integrations test helm_kubeconfig - set helm version to v3.10.3 to avoid incompatability with new bitnami charts (https://github.com/ansible-collections/kubernetes.core/pull/670).
v3.3.1
======
Release Summary
---------------
This release fixes the CI issues with the ``linters`` workflow.
v3.3.0
======
Release Summary
---------------
This release comes with improvements to the error messages in the k8s_drain module and several bug fixes.
Minor Changes
-------------
- k8s_drain - Improve error message for pod disruption budget when draining a node (https://github.com/ansible-collections/kubernetes.core/issues/797).
Bugfixes
--------
- helm - Helm version checks did not support RC versions. They now accept any version tags. (https://github.com/ansible-collections/kubernetes.core/pull/745).
- helm_pull - Apply no_log=True to pass_credentials to silence false positive warning. (https://github.com/ansible-collections/kubernetes.core/pull/796).
- k8s_drain - Fix k8s_drain does not wait for single pod (https://github.com/ansible-collections/kubernetes.core/issues/769).
- k8s_drain - Fix k8s_drain runs into a timeout when evicting a pod which is part of a stateful set (https://github.com/ansible-collections/kubernetes.core/issues/792).
- kubeconfig option should not appear in module invocation log (https://github.com/ansible-collections/kubernetes.core/issues/782).
- kustomize - kustomize plugin fails with deprecation warnings (https://github.com/ansible-collections/kubernetes.core/issues/639).
- waiter - Fix waiting for daemonset when desired number of pods is 0. (https://github.com/ansible-collections/kubernetes.core/pull/756).
v3.2.0
======
Release Summary
---------------
This release comes with documentation updates.
Minor Changes
-------------
- connection/kubectl.py - Added an example of using the kubectl connection plugin to the documentation (https://github.com/ansible-collections/kubernetes.core/pull/741).
- inventory/k8s.py - Defer removal of k8s inventory plugin to version 5.0 (https://github.com/ansible-collections/kubernetes.core/pull/723).
- inventory/k8s.py - Defer removal of k8s inventory plugin to version 6.0.0 (https://github.com/ansible-collections/kubernetes.core/pull/734).
v3.1.0
======
-37
View File
@@ -1,37 +0,0 @@
# Continuous Integration (CI)
## Kubernetes Upstream Testing
GitHub Actions are used to run the CI for the kubernetes.core collection. The workflows used for the CI can be found in the [.github/workflows](.github/workflows) directory.
### PR Testing Workflows
The following tests run on every pull request:
| Job | Description | Python Versions | ansible-core Versions |
| --- | ----------- | --------------- | --------------------- |
| [Changelog](.github/workflows/changelog.yaml) | Checks for the presence of changelog fragments | 3.12 | devel |
| [Linters](.github/workflows/linters.yaml) | Runs `black`, `flake8`, `isort`, `yamllint`, and `ansible-lint` on plugins and tests | 3.10 | devel |
| [Sanity](.github/workflows/sanity-tests.yaml) | Runs ansible sanity checks | See compatibility table below | devel, stable-2.18, stable-2.19, stable-2.20 |
| [Unit tests](.github/workflows/unit-tests.yaml) | Executes unit test cases | See compatibility table below | devel, stable-2.16, stable-2.17, stable-2.18, stable-2.19, stable-2.20 |
| [Integration](.github/workflows/integration-tests.yaml) | Executes integration test suites using KinD cluster (split across 8 jobs, tests with Turbo mode enabled/disabled) | 3.12 (stable-2.18), 3.13 (milestone) | stable-2.18, milestone |
| [all_green](.github/workflows/all_green_check.yaml) | Linters (PR only), sanity, units, coverage XML, aggregate gate, and SonarCloud scan (same-repo PR / push only) | (see jobs) | (see jobs) |
**Note:** Integration tests require a KinD (Kubernetes in Docker) cluster and test both with Turbo mode enabled and disabled.
### Python Version Compatibility by ansible-core Version
These are outlined in the collection's [tox.ini](tox.ini) file (`envlist`) and GitHub Actions workflow exclusions.
| ansible-core Version | Sanity Tests | Unit Tests | Integration Tests |
| -------------------- | ------------ | ---------- | ----------------- |
| devel | 3.12, 3.13, 3.14 | 3.13 | 3.13 (milestone) |
| stable-2.20 | 3.12, 3.13, 3.14 | 3.12, 3.13, 3.14 | — |
| stable-2.19 | 3.11, 3.12, 3.13 | 3.11, 3.12, 3.13 | — |
| stable-2.18 | 3.11, 3.12, 3.13 | 3.11, 3.12, 3.13 | 3.12 |
| stable-2.17 | 3.10, 3.11, 3.12 | 3.10, 3.11, 3.12 | — |
| stable-2.16 | 3.10, 3.11 | 3.10, 3.11 | — |
## SonarCloud
SonarCloud analysis runs from **[`all_green_check.yaml`](.github/workflows/all_green_check.yaml)** via the **`sonarcloud`** job, which calls **[`sonarcloud.yml`](.github/workflows/sonarcloud.yml)** (**`workflow_call`**) after the **`all_green`** gate and **coverage** succeed. The reusable workflow checks out the PR head or push SHA, downloads the **`coverage`** artifact, and runs the pinned **SonarSource** scan action. Same-repo **`pull_request`** and **`push`** only (fork PRs are excluded by the job **`if:`** gate). Details: [SONARCLOUD.md](SONARCLOUD.md).
+9 -15
View File
@@ -48,7 +48,7 @@ Where modules have multiple parameters we recommend running through the 4-step m
For general information on running the integration tests see the
[Integration Tests page of the Module Development Guide](https://docs.ansible.com/ansible/devel/dev_guide/testing_integration.html#testing-integration),
especially the section on configuration for cloud tests.
especially the section on configuration for cloud tests. For questions about writing tests the Ansible Kubernetes community can be found on Libera.Chat IRC as detailed below.
### Updating documentation
@@ -66,21 +66,15 @@ After installation, you can update documentation
Review the changes and create a pull request using updated files.
### Pre-Commit Hooks
To prevent accidental commits of local configuration and IDE files (specifically `.vscode/` and `.claude/`), this repository utilizes the `pre-commit` framework.
Please set up the hooks locally before making your first commit:
```bash
# Install the pre-commit tool
pip install pre-commit
# Register the hooks with Git
pre-commit install
```
### Code of Conduct
The `kubernetes.core` collection follows the Ansible project's
[Code of Conduct](https://docs.ansible.com/ansible/devel/community/code_of_conduct.html).
Please read and familiarize yourself with this document.
### IRC
Our IRC channels may require you to register your nickname. If you receive an error when you connect, see
[Libera.Chat's Nickname Registration guide](https://libera.chat/guides/registration) for instructions.
The `#ansible-kubernetes` channel on [libera.chat](https://libera.chat/) IRC is the main and official place to discuss use and development of the `kubernetes.core` collection.
For more information about Ansible's Kubernetes integration, browse the resources in the [Kubernetes Working Group](https://github.com/ansible/community/wiki/Kubernetes) Community wiki page.
+1 -1
View File
@@ -1,5 +1,5 @@
# Also needs to be updated in galaxy.yml
VERSION = 6.6.0
VERSION = 4.0.0
TEST_ARGS ?= ""
PYTHON_VERSION ?= `python -c 'import platform; print(".".join(platform.python_version_tuple()[0:2]))'`
+71 -124
View File
@@ -1,20 +1,34 @@
[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=ansible-collections_kubernetes.core&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=ansible-collections_kubernetes.core)
[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=ansible-collections_kubernetes.core&metric=coverage)](https://sonarcloud.io/summary/new_code?id=ansible-collections_kubernetes.core)
[![Vulnerabilities](https://sonarcloud.io/api/project_badges/measure?project=ansible-collections_kubernetes.core&metric=vulnerabilities)](https://sonarcloud.io/summary/new_code?id=ansible-collections_kubernetes.core)
[![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=ansible-collections_kubernetes.core&metric=security_rating)](https://sonarcloud.io/summary/new_code?id=ansible-collections_kubernetes.core)
[![Bugs](https://sonarcloud.io/api/project_badges/measure?project=ansible-collections_kubernetes.core&metric=bugs)](https://sonarcloud.io/summary/new_code?id=ansible-collections_kubernetes.core)
[![Code Smells](https://sonarcloud.io/api/project_badges/measure?project=ansible-collections_kubernetes.core&metric=code_smells)](https://sonarcloud.io/summary/new_code?id=ansible-collections_kubernetes.core)
[![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=ansible-collections_kubernetes.core&metric=sqale_rating)](https://sonarcloud.io/summary/new_code?id=ansible-collections_kubernetes.core)
# Kubernetes Collection for Ansible
[![CI](https://github.com/ansible-collections/kubernetes.core/workflows/CI/badge.svg?event=push)](https://github.com/ansible-collections/kubernetes.core/actions) [![Codecov](https://img.shields.io/codecov/c/github/ansible-collections/kubernetes.core)](https://codecov.io/gh/ansible-collections/kubernetes.core)
This repository hosts the `kubernetes.core` (formerly known as `community.kubernetes`) Ansible Collection.
## Description
The collection includes a variety of Ansible content to help automate the management of applications in Kubernetes and OpenShift clusters, as well as the provisioning and maintenance of clusters themselves.
### Included Content
<!--start requires_ansible-->
## Ansible version compatibility
This collection has been tested against following Ansible versions: **>=2.14.0**.
For collections that support Ansible 2.9, please ensure you update your `network_os` to use the
fully qualified collection name (for example, `cisco.ios.ios`).
Plugins and modules within a collection may be tested with only specific Ansible versions.
A collection may contain metadata that identifies these versions.
PEP440 is the schema used to describe the versions of Ansible.
<!--end requires_ansible-->
## Python Support
* Collection supports 3.9+
Note: Python2 is deprecated from [1st January 2020](https://www.python.org/doc/sunset-python-2/). Please switch to Python3.
## Kubernetes Version Support
This collection supports Kubernetes versions >= 1.24.
## Included content
Click on the name of a plugin or module to view that content's documentation:
@@ -22,73 +36,52 @@ Click on the name of a plugin or module to view that content's documentation:
### Connection plugins
Name | Description
--- | ---
[kubernetes.core.kubectl](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.kubectl_connection.rst)|Execute tasks in pods running on Kubernetes.
[kubernetes.core.kubectl](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.kubectl_connection.rst)|Execute tasks in pods running on Kubernetes.
### K8s filter plugins
Name | Description
--- | ---
kubernetes.core.k8s_config_resource_name|Generate resource name for the given resource of type ConfigMap, Secret
### Inventory plugins
Name | Description
--- | ---
[kubernetes.core.k8s](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_inventory.rst)|Kubernetes (K8s) inventory source
### Lookup plugins
Name | Description
--- | ---
[kubernetes.core.k8s](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_lookup.rst)|Query the K8s API
[kubernetes.core.kustomize](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.kustomize_lookup.rst)|Build a set of kubernetes resources using a 'kustomization.yaml' file.
[kubernetes.core.k8s](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_lookup.rst)|Query the K8s API
[kubernetes.core.kustomize](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.kustomize_lookup.rst)|Build a set of kubernetes resources using a 'kustomization.yaml' file.
### Modules
Name | Description
--- | ---
[kubernetes.core.helm](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.helm_module.rst)|Manages Kubernetes packages with the Helm package manager
[kubernetes.core.helm_info](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.helm_info_module.rst)|Get information from Helm package deployed inside the cluster
[kubernetes.core.helm_plugin](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.helm_plugin_module.rst)|Manage Helm plugins
[kubernetes.core.helm_plugin_info](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.helm_plugin_info_module.rst)|Gather information about Helm plugins
[kubernetes.core.helm_pull](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.helm_pull_module.rst)|download a chart from a repository and (optionally) unpack it in local directory.
[kubernetes.core.helm_registry_auth](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.helm_registry_auth_module.rst)|Helm registry authentication module
[kubernetes.core.helm_repository](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.helm_repository_module.rst)|Manage Helm repositories.
[kubernetes.core.helm_template](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.helm_template_module.rst)|Render chart templates
[kubernetes.core.k8s](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_module.rst)|Manage Kubernetes (K8s) objects
[kubernetes.core.k8s_cluster_info](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_cluster_info_module.rst)|Describe Kubernetes (K8s) cluster, APIs available and their respective versions
[kubernetes.core.k8s_cp](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_cp_module.rst)|Copy files and directories to and from pod.
[kubernetes.core.k8s_drain](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_drain_module.rst)|Drain, Cordon, or Uncordon node in k8s cluster
[kubernetes.core.k8s_exec](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_exec_module.rst)|Execute command in Pod
[kubernetes.core.k8s_info](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_info_module.rst)|Describe Kubernetes (K8s) objects
[kubernetes.core.k8s_json_patch](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_json_patch_module.rst)|Apply JSON patch operations to existing objects
[kubernetes.core.k8s_log](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_log_module.rst)|Fetch logs from Kubernetes resources
[kubernetes.core.k8s_rollback](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_rollback_module.rst)|Rollback Kubernetes (K8S) Deployments and DaemonSets
[kubernetes.core.k8s_scale](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_scale_module.rst)|Set a new size for a Deployment, ReplicaSet, Replication Controller, or Job.
[kubernetes.core.k8s_service](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_service_module.rst)|Manage Services on Kubernetes
[kubernetes.core.k8s_taint](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.k8s_taint_module.rst)|Taint a node in a Kubernetes/OpenShift cluster
[kubernetes.core.kubeconfig](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/kubernetes.core.kubeconfig_module.rst)|Generate, update, and optionally write Kubernetes kubeconfig files
[kubernetes.core.helm](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.helm_module.rst)|Manages Kubernetes packages with the Helm package manager
[kubernetes.core.helm_info](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.helm_info_module.rst)|Get information from Helm package deployed inside the cluster
[kubernetes.core.helm_plugin](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.helm_plugin_module.rst)|Manage Helm plugins
[kubernetes.core.helm_plugin_info](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.helm_plugin_info_module.rst)|Gather information about Helm plugins
[kubernetes.core.helm_pull](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.helm_pull_module.rst)|download a chart from a repository and (optionally) unpack it in local directory.
[kubernetes.core.helm_repository](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.helm_repository_module.rst)|Manage Helm repositories.
[kubernetes.core.helm_template](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.helm_template_module.rst)|Render chart templates
[kubernetes.core.k8s](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_module.rst)|Manage Kubernetes (K8s) objects
[kubernetes.core.k8s_cluster_info](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_cluster_info_module.rst)|Describe Kubernetes (K8s) cluster, APIs available and their respective versions
[kubernetes.core.k8s_cp](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_cp_module.rst)|Copy files and directories to and from pod.
[kubernetes.core.k8s_drain](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_drain_module.rst)|Drain, Cordon, or Uncordon node in k8s cluster
[kubernetes.core.k8s_exec](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_exec_module.rst)|Execute command in Pod
[kubernetes.core.k8s_info](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_info_module.rst)|Describe Kubernetes (K8s) objects
[kubernetes.core.k8s_json_patch](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_json_patch_module.rst)|Apply JSON patch operations to existing objects
[kubernetes.core.k8s_log](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_log_module.rst)|Fetch logs from Kubernetes resources
[kubernetes.core.k8s_rollback](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_rollback_module.rst)|Rollback Kubernetes (K8S) Deployments and DaemonSets
[kubernetes.core.k8s_scale](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_scale_module.rst)|Set a new size for a Deployment, ReplicaSet, Replication Controller, or Job.
[kubernetes.core.k8s_service](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_service_module.rst)|Manage Services on Kubernetes
[kubernetes.core.k8s_taint](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/kubernetes.core.k8s_taint_module.rst)|Taint a node in a Kubernetes/OpenShift cluster
<!--end collection content-->
## Requirements
## Installation and Usage
<!--start requires_ansible-->
## Ansible version compatibility
This collection has been tested against the following Ansible versions: **>=2.16.0**.
Plugins and modules within a collection may be tested with only specific Ansible versions.
A collection may contain metadata that identifies these versions.
PEP440 is the schema used to describe the versions of Ansible.
<!--end requires_ansible-->
### Helm Version Compatibility
This collection supports Helm v3.x and newer. Please note that specific modules or certain parameters may have additional version requirements.
### Python Support
* Collection supports 3.9+
Note: Python2 is deprecated from [1st January 2020](https://www.python.org/doc/sunset-python-2/). Please switch to Python3.
### Kubernetes Version Support
This collection supports Kubernetes versions >= 1.24.
## Installation
### Installing the Collection from Ansible Galaxy
Before using the Kubernetes collection, you need to install it with the Ansible Galaxy CLI:
@@ -100,18 +93,16 @@ You can also include it in a `requirements.yml` file and install it via `ansible
---
collections:
- name: kubernetes.core
version: 6.6.0
version: 4.0.0
```
### Installing the Kubernetes Python Library
Content in this collection requires the [Kubernetes Python client](https://pypi.org/project/kubernetes/) to interact with Kubernetes' APIs. You can install it with:
```bash
pip3 install kubernetes
```
pip3 install kubernetes
## Use Cases
### Using modules from the Kubernetes Collection in your playbooks
It's preferable to use content in this collection using their Fully Qualified Collection Namespace (FQCN), for example `kubernetes.core.k8s_info`:
@@ -179,13 +170,10 @@ If upgrading older playbooks which were built prior to Ansible 2.10 and this col
For documentation on how to use individual modules and other content included in this collection, please see the links in the 'Included content' section earlier in this README.
## Ansible Turbo Mode Tech Preview
## Ansible Turbo mode Tech Preview
> **Deprecated:** Ansible Turbo mode (`ENABLE_TURBO_MODE`) is deprecated and will be removed in a future major release (planned for 8.0.0), since it depends on the `cloud.common` collection, which is being retired. Setting `ENABLE_TURBO_MODE` will keep emitting a deprecation warning until support is removed, at which point the variable will have no effect.
> **Note:** Ansible Turbo mode is supported only with ``ansible-core`` versions **lower than 2.19**. Starting from ``ansible-core`` 2.19, the ``cloud.common`` collection is no longer supported, and therefore Ansible Turbo mode is also not supported in ``kubernetes.core``. If ``ENABLE_TURBO_MODE`` is set to ``1`` (or any truthy value) with ``ansible-core >= 2.19.0``, Turbo mode is ignored and a warning is emitted; modules run without it.
The ``kubernetes.core`` collection supports Ansible Turbo mode as a tech preview via the ``cloud.common`` collection (requires `ansible-core < 2.19`). By default, this feature is disabled. To enable Turbo mode for modules, set the environment variable `ENABLE_TURBO_MODE=1` on the managed node. For example:
The ``kubernetes.core`` collection supports Ansible Turbo mode as a tech preview via the ``cloud.common`` collection. By default, this feature is disabled. To enable Turbo mode for modules, set the environment variable `ENABLE_TURBO_MODE=1` on the managed node. For example:
```yaml
---
@@ -199,11 +187,13 @@ The ``kubernetes.core`` collection supports Ansible Turbo mode as a tech preview
To enable Turbo mode for k8s lookup plugin, set the environment variable `ENABLE_TURBO_MODE=1` on the managed node. This is not working when
defined in the playbook using `environment` keyword as above, you must set it using `export ENABLE_TURBO_MODE=1`.
Please read more about Ansible Turbo mode - [here](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/ansible_turbo_mode.rst).
Please read more about Ansible Turbo mode - [here](https://github.com/ansible-collections/kubernetes.core/blob/main/docs/ansible_turbo_mode.rst).
## Testing
## Testing and Development
[![Linters](https://img.shields.io/github/actions/workflow/status/ansible-collections/kubernetes.core/linters.yaml?label=linters)](https://github.com/ansible-collections/kubernetes.core/actions/workflows/linters.yaml) [![Integration tests](https://img.shields.io/github/actions/workflow/status/ansible-collections/kubernetes.core/integration-tests.yaml?label=integration%20tests)](https://github.com/ansible-collections/kubernetes.core/actions/workflows/integration-tests.yaml) [![Sanity tests](https://img.shields.io/github/actions/workflow/status/ansible-collections/kubernetes.core/sanity-tests.yaml?label=sanity%20tests)](https://github.com/ansible-collections/kubernetes.core/actions/workflows/sanity-tests.yaml) [![Unit tests](https://img.shields.io/github/actions/workflow/status/ansible-collections/kubernetes.core/unit-tests.yaml?label=unit%20tests)](https://github.com/ansible-collections/kubernetes.core/actions/workflows/unit-tests.yaml) [![Codecov](https://img.shields.io/codecov/c/github/ansible-collections/kubernetes.core)](https://app.codecov.io/gh/ansible-collections/kubernetes.core)
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 kubernetes.core](CONTRIBUTING.md).
### Testing with `ansible-test`
@@ -217,45 +207,12 @@ You can run the collection's test suites with the commands:
### Testing with `molecule`
There are also integration tests in the `molecule` directory which are meant to be run against a local Kubernetes cluster, e.g. using [KinD](https://kind.sigs.k8s.io) or [Minikube](https://minikube.sigs.k8s.io). To set up a local cluster using KinD and run Molecule:
There are also integration tests in the `molecule` directory which are meant to be run against a local Kubernetes cluster, e.g. using [KinD](https://kind.sigs.k8s.io) or [Minikube](https://minikube.sigs.k8s.io). To setup a local cluster using KinD and run Molecule:
kind create cluster
make test-molecule
## Contributing to this Collection
If you want to develop new content for this collection or improve what is already here, clone the Git repository 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 kubernetes.core](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/CONTRIBUTING.md).
Join the Ansible community:
* [Get Help](https://forum.ansible.com/c/help/6)
* [Posts tagged with 'kubernetes'](https://forum.ansible.com/tag/kubernetes)
* [Social Spaces](https://forum.ansible.com/c/chat/4)
* [News & Announcements](https://forum.ansible.com/c/news/5)
The Ansible [Bullhorn newsletter](https://docs.ansible.com/ansible/devel/community/communication.html#the-bullhorn) announces releases and important changes. For more information, see the [Ansible communication guide](https://docs.ansible.com/ansible/devel/community/communication.html).
### Code of Conduct
This project follows the [Ansible Code of Conduct](https://docs.ansible.com/ansible/devel/community/code_of_conduct.html). If you encounter abusive behavior, see the [policy violations](https://docs.ansible.com/ansible/devel/community/code_of_conduct.html#policy-violations) section for how to raise a complaint.
## Support
As Red Hat Ansible Certified Content, this collection is entitled to support through the Ansible Automation Platform (AAP) using the **Create issue** button on the top right corner. If a support case cannot be opened with Red Hat and the collection has been obtained either from Galaxy or GitHub, there may be community help available on the [Ansible Forum](https://forum.ansible.com/).
> **Note:** The `stable-4` branch (all `4.x.y` releases) is no longer supported. No backports or releases are performed on `stable-4`.
We announce releases and important changes through Ansible's [The Bullhorn newsletter](https://github.com/ansible/community/wiki/News#the-bullhorn). Subscribe via [this link](https://eepurl.com/gZmiEP).
We take part in the global quarterly [Ansible Contributor Summit](https://github.com/ansible/community/wiki/Contributor-Summit). Track The Bullhorn and join when announced.
For the latest supported versions, see [Release Notes and Roadmap](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/README.md#release-notes-and-roadmap).
Report bugs, request features, or ask questions by opening an issue in the [GitHub repository](https://github.com/ansible-collections/kubernetes.core/).
## Release Notes and Roadmap
## Publishing New Versions
Releases are automatically built and pushed to Ansible Galaxy for any new tag. Before tagging a release, make sure to do the following:
@@ -272,24 +229,14 @@ Releases are automatically built and pushed to Ansible Galaxy for any new tag. B
After the version is published, verify it exists on the [Kubernetes Collection Galaxy page](https://galaxy.ansible.com/kubernetes/core).
The process for [uploading a supported release to Automation Hub](https://docs.redhat.com/en/documentation/red_hat_ansible_automation_platform/2.1/html/uploading_content_to_red_hat_automation_hub/proc-upload-collection) is documented separately.
The process for uploading a supported release to Automation Hub is documented separately.
## Related Information
## More Information
* [Using Ansible collections](https://docs.ansible.com/ansible/devel/user_guide/collections_using.html)
* [Ansible communication guide](https://docs.ansible.com/ansible/devel/community/communication.html)
* [Continuous integration (CI) overview](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/CI.md)
* [SonarCloud integration](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/SONARCLOUD.md)
* [Ansible Turbo mode (tech preview)](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/docs/ansible_turbo_mode.rst)
For more information about Ansible's Kubernetes integration, join the `#ansible-kubernetes` channel on [libera.chat](https://libera.chat/) IRC, and browse the resources in the [Kubernetes Working Group](https://github.com/ansible/community/wiki/Kubernetes) Community wiki page.
### Code of conduct
We follow the [Ansible Code of Conduct](https://docs.ansible.com/ansible/devel/community/code_of_conduct.html) in all our interactions within this project.
If you encounter abusive behavior, please refer to the [policy violations](https://docs.ansible.com/ansible/devel/community/code_of_conduct.html#policy-violations) section of the Code for information on how to raise a complaint.
## License Information
## License
GNU General Public License v3.0 or later
See [LICENSE](https://github.com/ansible-collections/kubernetes.core/blob/stable-6/LICENSE) to see the full text.
See LICENCE to see the full text.
-32
View File
@@ -1,32 +0,0 @@
# SonarCloud
Dashboard:
[SonarCloud project overview](https://sonarcloud.io/project/overview?id=ansible-collections_kubernetes.core)
## CI integration
Sonar analysis is implemented in **[.github/workflows/sonarcloud.yml](.github/workflows/sonarcloud.yml)** as a **reusable workflow** (`on: workflow_call` only). It is **not** triggered by `workflow_run`.
**[.github/workflows/all_green_check.yaml](.github/workflows/all_green_check.yaml)** runs **linters** (on pull requests), **sanity**, **units**, and **coverage**, passes the aggregate **`all_green`** gate, then calls **`sonarcloud.yml`** via a **`sonarcloud`** job when the conditions below are met. The **coverage** job uploads a **`coverage`** artifact; the Sonar job downloads it in the **same** workflow run.
The caller runs on **`pull_request`** or **`push`**, so the reusable workflow inherits that **`github.event`**. **`actions/checkout`** uses **`github.event.pull_request.head.sha`** on pull requests and **`github.sha`** on push (Sonar-friendly checkout). PR parameters (**`sonar.pullrequest.*`**) are taken from **`github.event.pull_request`** (no `gh` API calls in **`sonarcloud.yml`**).
The scan step uses **`SonarSource/sonarqube-scan-action`** (pinned SHA in the workflow file) with **`sonar.python.coverage.reportPaths`** set from any **`coverage*.xml`** files found under the workspace after the artifact download. The overall flow (coverage in CI, then Sonar with XML) follows the same idea as [ansible-collections/amazon.aws#2871](https://github.com/ansible-collections/amazon.aws/pull/2871), using **`workflow_call`** from **`all_green`** instead of a separate **`workflow_run`** finalize workflow.
Workflow files:
- [.github/workflows/all_green_check.yaml](.github/workflows/all_green_check.yaml) -- **`all_green`** gate, **coverage** artifact upload, and **`sonarcloud`** job (**`uses: ./.github/workflows/sonarcloud.yml`**, passing only **`ANSIBLE_COLLECTIONS_ORG_SONAR_TOKEN_CICD_BOT`**) after **`all_green`** and **`coverage`** succeed, gated for **`push`** and same-repo **`pull_request`** only.
- [.github/workflows/sonarcloud.yml](.github/workflows/sonarcloud.yml) -- **`scan`** job: checkout, download **`coverage`**, **`SONAR_ARGS`**, SonarCloud scan.
Scanner configuration lives in [sonar-project.properties](sonar-project.properties).
The **coverage** job (in **`all_green`**) uses **`ansible-test`** (`units --coverage`, then **`coverage combine`** / **`coverage xml`**) with **ansible-core `stable-2.18`** on **`stable-6`**, then writes **`coverage.xml`** with workspace paths normalized for Sonar. **`pytest-cov`** is listed in **`tests/unit/requirements.txt`** for parity and any direct pytest runs; **`ansible-test`** still owns the coverage data used in CI.
**`sonarcloud.yml`** declares a required secret **`ANSIBLE_COLLECTIONS_ORG_SONAR_TOKEN_CICD_BOT`** and **`permissions: contents: read`**, **`pull-requests: read`**.
Org secrets and fork PR behavior follow GitHub's [secrets in Actions](https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions) documentation. The **`sonarcloud`** job is **`if:`**-gated so the org token is not used for fork-head checkouts; fork PRs still run **`all_green`** for CI without running Sonar.
## Branch protection (repository settings)
If **`SonarCloud scan`** or **`all_green`** should block merges, add them under **Settings** > **Branches** > **Required status checks** for the protected branch. That is not configured in YAML.
-464
View File
@@ -854,58 +854,6 @@ releases:
- 652-fix-json-patch-action.yml
- 654-helm-expand-user.yml
release_date: '2024-05-16'
3.2.0:
changes:
minor_changes:
- connection/kubectl.py - Added an example of using the kubectl connection plugin
to the documentation (https://github.com/ansible-collections/kubernetes.core/pull/741).
- inventory/k8s.py - Defer removal of k8s inventory plugin to version 5.0 (https://github.com/ansible-collections/kubernetes.core/pull/723).
- inventory/k8s.py - Defer removal of k8s inventory plugin to version 6.0.0
(https://github.com/ansible-collections/kubernetes.core/pull/734).
release_summary: This release comes with documentation updates.
fragments:
- 20240530-defer-removal-and-ansible-core-support-update.yaml
- 20240601-doc-example-of-using-kubectl.yaml
- 3.2.0.yml
- inventory-update_removal_date.yml
release_date: '2024-06-14'
3.3.0:
changes:
bugfixes:
- helm - Helm version checks did not support RC versions. They now accept any
version tags. (https://github.com/ansible-collections/kubernetes.core/pull/745).
- helm_pull - Apply no_log=True to pass_credentials to silence false positive
warning. (https://github.com/ansible-collections/kubernetes.core/pull/796).
- k8s_drain - Fix k8s_drain does not wait for single pod (https://github.com/ansible-collections/kubernetes.core/issues/769).
- k8s_drain - Fix k8s_drain runs into a timeout when evicting a pod which is
part of a stateful set (https://github.com/ansible-collections/kubernetes.core/issues/792).
- kubeconfig option should not appear in module invocation log (https://github.com/ansible-collections/kubernetes.core/issues/782).
- kustomize - kustomize plugin fails with deprecation warnings (https://github.com/ansible-collections/kubernetes.core/issues/639).
- waiter - Fix waiting for daemonset when desired number of pods is 0. (https://github.com/ansible-collections/kubernetes.core/pull/756).
minor_changes:
- k8s_drain - Improve error message for pod disruption budget when draining
a node (https://github.com/ansible-collections/kubernetes.core/issues/797).
release_summary: This release comes with improvements to the error messages
in the k8s_drain module and several bug fixes.
fragments:
- 20240530-ansible-core-support-update.yaml
- 20240611-helm-rc-version.yaml
- 20240620-fix-kustomize-plugin-fails-with-deprecation-warnings.yml
- 20241102-fix-ci-post-2.18-issue.yaml
- 20241213-kubeconfig-set-no_log-true.yaml
- 756-fix-daemonset-waiting.yaml
- 770-fix-k8s-drain-doesnt-wait-for-single-pod.yaml
- 793-fix-k8s-drain-runs-into-timeout.yaml
- 796-false-positive-helmull.yaml
- 798-drain-pdb-error-message.yaml
- readme_template_update.yml
release_date: '2025-01-20'
3.3.1:
changes:
release_summary: This release fixes the CI issues with the ``linters`` workflow.
fragments:
- release_summary.yml
release_date: '2025-03-26'
4.0.0:
changes:
bugfixes:
@@ -948,415 +896,3 @@ releases:
- k8s-merge_type-removed.yml
- module_utils-common-remove-deprecated-functions-and-class.yaml
release_date: '2024-05-24'
5.0.0:
changes:
breaking_changes:
- Remove support for ``ansible-core<2.15`` (https://github.com/ansible-collections/kubernetes.core/pull/737).
minor_changes:
- connection/kubectl.py - Added an example of using the kubectl connection plugin
to the documentation (https://github.com/ansible-collections/kubernetes.core/pull/741).
- inventory/k8s.py - Defer removal of k8s inventory plugin to version 6.0.0
(https://github.com/ansible-collections/kubernetes.core/pull/734).
release_summary: This major release drops support for ``ansible-core<2.15``.
fragments:
- 20240530-ansible-core-support-update.yaml
- 20240530-defer-removal-and-ansible-core-support-update.yaml
- 5.0.0.yml
release_date: '2024-05-31'
5.1.0:
changes:
bugfixes:
- helm - Helm version checks did not support RC versions. They now accept any
version tags. (https://github.com/ansible-collections/kubernetes.core/pull/745).
- helm_pull - Apply no_log=True to pass_credentials to silence false positive
warning. (https://github.com/ansible-collections/kubernetes.core/pull/796).
- k8s_drain - Fix k8s_drain does not wait for single pod (https://github.com/ansible-collections/kubernetes.core/issues/769).
- k8s_drain - Fix k8s_drain runs into a timeout when evicting a pod which is
part of a stateful set (https://github.com/ansible-collections/kubernetes.core/issues/792).
- kubeconfig option should not appear in module invocation log (https://github.com/ansible-collections/kubernetes.core/issues/782).
- kustomize - kustomize plugin fails with deprecation warnings (https://github.com/ansible-collections/kubernetes.core/issues/639).
- waiter - Fix waiting for daemonset when desired number of pods is 0. (https://github.com/ansible-collections/kubernetes.core/pull/756).
minor_changes:
- Bump version of ``ansible-lint`` to minimum 24.7.0 (https://github.com/ansible-collections/kubernetes.core/pull/765).
- Parameter insecure_registry added to helm_template as equivalent of insecure-skip-tls-verify
(https://github.com/ansible-collections/kubernetes.core/pull/805).
- k8s_drain - Improve error message for pod disruption budget when draining
a node (https://github.com/ansible-collections/kubernetes.core/issues/797).
release_summary: This release came with new module ``helm_registry_auth``, improvements
to the error messages in the k8s_drain module, new parameter ``insecure_registry``
for ``helm_template`` module and several bug fixes.
fragments:
- 0-readme.yml
- 20240601-doc-example-of-using-kubectl.yaml
- 20240611-helm-rc-version.yaml
- 20240620-fix-kustomize-plugin-fails-with-deprecation-warnings.yml
- 20241102-fix-ci-post-2.18-issue.yaml
- 20241103-completly-remove-obsolate-communication-channel.yaml
- 20241207-add-insecure-skip-tls-verify-to-helm-template.yaml
- 20241213-kubeconfig-set-no_log-true.yaml
- 756-fix-daemonset-waiting.yaml
- 765-bump-ansible-lint-version.yml
- 770-fix-k8s-drain-doesnt-wait-for-single-pod.yaml
- 793-fix-k8s-drain-runs-into-timeout.yaml
- 796-false-positive-helmull.yaml
- 798-drain-pdb-error-message.yaml
- readme_template_update.yml
modules:
- description: Helm registry authentication module
name: helm_registry_auth
namespace: ''
release_date: '2025-01-20'
5.2.0:
changes:
minor_changes:
- k8s - Extend hidden_fields to allow the expression of more complex field types
to be hidden (https://github.com/ansible-collections/kubernetes.core/pull/872)
- k8s_info - Extend hidden_fields to allow the expression of more complex field
types to be hidden (https://github.com/ansible-collections/kubernetes.core/pull/872)
- 'waiter.py - add ClusterOperator support. The module can now check OpenShift
cluster health by verifying ClusterOperator status requiring ''Available:
True'', ''Degraded: False'', and ''Progressing: False'' for success. (https://github.com/ansible-collections/kubernetes.core/issues/869)'
release_summary: This release adds more functionality to the hidden_fields option
and support for waiting on ClusterOperators to reach a ready state.
fragments:
- 5.2.0.yml
- 643-extend-hidden-fields.yaml
- 879-clusteroperator-waiter.py.yaml
release_date: '2025-03-27'
5.3.0:
changes:
bugfixes:
- module_utils/k8s/service - fix issue when trying to delete resource using
``delete_options`` and ``check_mode=true`` (https://github.com/ansible-collections/kubernetes.core/issues/892).
minor_changes:
- Bump version of ``ansible-lint`` to 25.1.2 (https://github.com/ansible-collections/kubernetes.core/pull/919).
- action/k8s_info - update templating mechanism with changes from ``ansible-core
2.19`` (https://github.com/ansible-collections/kubernetes.core/pull/888).
- helm - add ``reset_then_reuse_values`` support to helm module (https://github.com/ansible-collections/kubernetes.core/issues/803).
- helm - add support for ``insecure_skip_tls_verify`` option to helm and helm_repository(https://github.com/ansible-collections/kubernetes.core/issues/694).
release_summary: This release includes minor changes, bug fixes and also bumps
``ansible-lint`` version to ``25.1.2``.
fragments:
- 20250324-k8s_info-templating.yaml
- 5.3.0.yml
- 694-add-insecure-skip-tls-verify.yml
- 800-helm-add-reset_then_reuse_values-support.yml
- 898-k8s-dont-delete-in-check-mode.yaml
- 919-update-ansible-lint-version.yaml
release_date: '2025-05-16'
5.4.0:
changes:
minor_changes:
- Module ``helm_registry_auth`` does not support idempotency with ``helm >=
3.18.0`` (https://github.com/ansible-collections/kubernetes.core/pull/946).
release_summary: This release updates the ``helm_registry_auth`` module to match
the behavior of ``helm >= 3.18.0`` which reports a successful logout regardless
of the current state (i.e., no idempotency).
fragments:
- 20250411-kubeconfig-no_log-revert.yaml
- 20250503-fix-unit-tests.yml
- 20250605-fix-helm_registry_auth-integration_test.yaml
- 5.4.0.yml
release_date: '2025-08-12'
5.4.1:
changes:
bugfixes:
- Remove ``ansible.module_utils.six`` imports to avoid warnings (https://github.com/ansible-collections/kubernetes.core/pull/998).
- Update the ``k8s_cp`` module to also work for init containers (https://github.com/ansible-collections/kubernetes.core/pull/971).
- module_utils/k8s/service - hide fields first before creating diffs (https://github.com/ansible-collections/kubernetes.core/pull/915).
release_summary: This release includes bugfixes for k8s service field handling,
k8s_cp init containers support, and removes deprecated ansible.module_utils.six
imports.
fragments:
- 20250428-k8s-service-hide-fields-first.yaml
- 20250731-fix-k8s_cp-initcontainers.yaml
- 20250922-remove-ansible-six-imports.yaml
- 5.4.1.yml
release_date: '2025-10-07'
6.0.0:
changes:
breaking_changes:
- Remove deprecated ``k8s`` invetory plugin (https://github.com/ansible-collections/kubernetes.core/pull/867).
- Remove support for ``ansible-core<2.16`` (https://github.com/ansible-collections/kubernetes.core/pull/867).
fragments:
- 20250121-breaking-changes-6.0.0.yml
release_date: '2025-05-19'
6.1.0:
changes:
bugfixes:
- module_utils/k8s/service - hide fields first before creating diffs (https://github.com/ansible-collections/kubernetes.core/pull/915).
minor_changes:
- Module ``helm_registry_auth`` does not support idempotency with `helm >= 3.18.0`
(https://github.com/ansible-collections/kubernetes.core/pull/946).
- Module k8s_json_patch - Add support for ``hidden_fields`` (https://github.com/ansible-collections/kubernetes.core/pull/964).
- helm - Parameter plain_http added for working with insecure OCI registries
(https://github.com/ansible-collections/kubernetes.core/pull/934).
- helm - Parameter take_ownership added (https://github.com/ansible-collections/kubernetes.core/pull/957).
- helm_pull - Parameter plain_http added for working with insecure OCI registries
(https://github.com/ansible-collections/kubernetes.core/pull/934).
- helm_template - Parameter plain_http added for working with insecure OCI registries
(https://github.com/ansible-collections/kubernetes.core/pull/934).
release_summary: "This release adds ``plain_http`` and ``take_ownership`` parameters
for helm modules, support for ``hidden_fields`` in ``k8s_json_patch``, documented
lack of idempotency support in ``helm_registry_auth`` with ``helm \u2265 3.18.0``,
and improved ``k8s_rollback`` test coverage."
fragments:
- 20250411-kubeconfig-no_log-revert.yaml
- 20250428-k8s-service-hide-fields-first.yaml
- 20250522-add-plain-http-for-oci-registries.yaml
- 20250605-fix-helm_registry_auth-integration_test.yaml
- 20250704-k8s-rollback-integration-test-coverage.yaml
- 20250720-k8s-patch-add-hidden-fields.yaml
- 20250911-add-support-helm-take-ownership.yaml
- release_summary.yml
release_date: '2025-08-12'
6.2.0:
changes:
bugfixes:
- Remove ``ansible.module_utils.six`` imports to avoid warnings (https://github.com/ansible-collections/kubernetes.core/pull/998).
- Update the ``k8s_cp`` module to also work for init containers (https://github.com/ansible-collections/kubernetes.core/pull/971).
minor_changes:
- Add support of skip-schema-validation in ``helm`` module (https://github.com/ansible-collections/kubernetes.core/pull/995)
- kustomize - Add support of local environ (https://github.com/ansible-collections/kubernetes.core/pull/786).
release_summary: This release adds minor changes and bugfixes, including support
of skip-schema-validation in ``helm`` module and removing deprecated ``ansible.module_utils.six``
imports.
fragments:
- 20241030-support-of-evrion-for-kustomize-lookup-plugin.yaml
- 20250731-fix-k8s_cp-initcontainers.yaml
- 20250916-skip-schema-validation.yaml
- 20250922-remove-ansible-six-imports.yaml
- 6_2_0.yml
release_date: '2025-10-07'
6.3.0:
changes:
bugfixes:
- Add idempotency for ``helm_pull`` module (https://github.com/ansible-collections/kubernetes.core/pull/1055).
- Fixed a bug where setting ``K8S_AUTH_VERIFY_SSL=true`` (or any string value)
caused the value to be treated as a separate ``kubectl`` command argument.
(https://github.com/ansible-collections/kubernetes.core/pull/1049).
- Limit supported versions of Helm to <4.0.0 (https://github.com/ansible-collections/kubernetes.core/pull/1039).
- Replace passing ``warnings`` to ``exit_json`` with ``AnsibleModule.warn``
in the ``k8s_drain``, ``k8s_rollback.py`` and ``k8s_scale.py`` modules as
it deprecated in ``ansible-core>=2.19.0`` and will be removed in ``ansible-core>=2.23.0``
(https://github.com/ansible-collections/kubernetes.core/pull/1033).
- k8s - Fix return block from the module documentation (https://github.com/ansible-collections/kubernetes.core/pull/1056).
- meta - Add ``k8s_cluster_info``, ``k8s_json_patch`` and ``k8s_rollback`` to
k8s action group (https://github.com/ansible-collections/kubernetes.core/pull/992).
deprecated_features:
- helm - the ``status.values`` return value has been deprecated and will be
removed in a release after 2027-01-08. Use ``status.release_values`` instead
(https://github.com/ansible-collections/kubernetes.core/pull/1056).
- helm_info - the ``status.values`` return value has been deprecated and will
be removed in a release after 2027-01-08. Use ``status.release_values`` instead
(https://github.com/ansible-collections/kubernetes.core/pull/1056).
minor_changes:
- Remove deprecated import from ``ansible.module_utils._text`` (https://github.com/ansible-collections/kubernetes.core/pull/1053).
- helm - add ``release_values`` key to ``status`` return value that can be accessed
using Jinja2 dot notation (https://github.com/ansible-collections/kubernetes.core/pull/1056).
- helm_info - add ``release_values`` key to ``status`` return value that can
be accessed using Jinja2 dot notation (https://github.com/ansible-collections/kubernetes.core/pull/1056).
release_summary: This release includes bugfixes such as implementing idempotency
for the ``helm_pull`` module as well as a security update for selectively
redacting sensitive information from kubeconfig.
security_fixes:
- Selectively redact sensitive info from kubeconfig instead of applying blanket
``no_log=True`` (https://github.com/ansible-collections/kubernetes.core/pull/1014).
fragments:
- 1033-warnings-deprecations.yaml
- 20251002-fix-k8s-actiongroup.yaml
- 20251007-selective-kubeconfig-redaction.yaml
- 20251115-limit-versions-of-helm.yaml
- 20251220-fix-K8S_AUTH_VERIFY_SSL-in-kubectl-connecton-plugion.yaml
- 20251228-1053-remove-deprecated-import.yaml
- 20260107-add-idempodency-for-helm-pull.yaml
- 20260108-fix-sanity-failures.yml
- 6-3-0.yaml
release_date: '2026-02-03'
6.4.0:
changes:
bugfixes:
- Helm - Allow taking ownership of existing Kubernetes resources on the first
installation of a Helm release. Previously, the ``take_ownership`` parameter
was always disabled during the initial install, preventing resource adoption
(https://github.com/ansible-collections/kubernetes.core/pull/1034).
minor_changes:
- helm_info - Ensure compatibility with Helm v4 (https://github.com/ansible-collections/kubernetes.core/issues/1038).
- helm_plugin - Ensure compatibility with Helm v4 (https://github.com/ansible-collections/kubernetes.core/issues/1038).
- helm_plugin_info - Ensure compatibility with Helm v4 (https://github.com/ansible-collections/kubernetes.core/issues/1038).
- helm_pull - Ensure compatibility with Helm v4 (https://github.com/ansible-collections/kubernetes.core/issues/1038).
- helm_registry_auth - Ensure compatibility with Helm v4 (https://github.com/ansible-collections/kubernetes.core/issues/1038).
- helm_registry_auth - add new option plain_http to allow insecure http connection
when running ``helm registry login`` (https://github.com/ansible-collections/kubernetes.core/pull/1090).
- helm_repository - Ensure compatibility with Helm v4 (https://github.com/ansible-collections/kubernetes.core/issues/1038).
- k8s_drain - Add support for ``check_mode`` (https://github.com/ansible-collections/kubernetes.core/pull/1086).
- k8s_drain - Convert module warnings into informational displays when users
explicitly request the deletion of unmanaged pods, pods with local storage,
or those managed by a ``DaemonSet`` (https://github.com/ansible-collections/kubernetes.core/issues/1037).
release_summary: This release adds Helm v4 compatibility across the Helm modules
and improves ``k8s_drain`` with check mode. When you explicitly allow evicting
unmanaged pods, pods with local storage, or pods managed by a ``DaemonSet``,
those cases are reported as informational output instead of module warnings.
fragments:
- 20251224-take-ownership-helm-initialization.yaml
- 20260203-k8s_drain-warning-fixes.yaml
- 20260213-support-helm-v4-for-helm-plugin-modules.yaml
- release-6-4-0.yml
release_date: '2026-04-22'
6.5.0:
changes:
bugfixes:
- ee - added ``meta/execution-environment.yml`` to decouple ansible-builder
EE builds from the ``openshift-clients`` system dependency declared in ``bindep.txt``,
which is not available in standard UBI repositories and caused builds to fail
with ``No package matches 'openshift-clients'`` (https://github.com/ansible-collections/kubernetes.core/issues/1141).
- helm - use ``--server-side=false --force-replace`` instead of the deprecated/removed
``--force`` flag when ``force=true`` is used with Helm v4, preserving the
Helm v3 client-side replacement behaviour and avoiding the server-side apply
conflict (https://github.com/ansible-collections/kubernetes.core/pull/1164).
- helm - use the ``--rollback-on-failure`` flag instead of the deprecated/removed
``--atomic`` flag when ``atomic=true`` is used with Helm v4 (https://github.com/ansible-collections/kubernetes.core/pull/1144).
- helm_repository - correct handling of repository URLs with trailing slashes
(https://github.com/ansible-collections/kubernetes.core/pull/1121).
- k8s_drain - Fix logic for handling pods with local storage to correctly check
for empty_dir volumes in replicated pods and pods managed by DaemonSets (https://github.com/ansible-collections/kubernetes.core/pull/1095).
minor_changes:
- helm - add the ``server_side`` and ``force_conflicts`` options to control
Helm v4 server-side apply when installing or upgrading a release (https://github.com/ansible-collections/kubernetes.core/pull/1164).
- helm_plugin - add ``--keyring`` argument to allow changing the keyring default
location. The option is only accepted with ``state=present`` (the ``helm plugin
install`` subcommand), as that is the only implemented subcommand that supports
``--keyring`` (https://github.com/ansible-collections/kubernetes.core/pull/1150).
- helm_registry_auth - document that, as of Helm 4.2.1, registry success messages
such as ``Login Succeeded`` are printed to stdout instead of stderr (https://github.com/ansible-collections/kubernetes.core/pull/1147).
- kubeconfig - add ``remove`` value to the ``behavior`` option, allowing entries
to be deleted from the kubeconfig file by name (https://github.com/ansible-collections/kubernetes.core/pull/1123).
release_summary: This release implements minor changes and bug fixes such as
a new ``remove`` value to the ``behavior`` option of the ``kubeconfig`` module,
allowing entries to be deleted from the kubeconfig file by name, as well as
Helm v4 compatibility across the Helm modules.
fragments:
- 1123-kubeconfig-remove-behavior.yml
- 1173-security-check-workflow.yml
- 20260306-k8s_drain-delete-logic-fixes-for-daemonsets.yaml
- 20260506-improve_idempotency_for_helm_repository.yaml
- 20260611-helm-atomic-helm-v4.yml
- 20260612-helm-registry-output-stream.yml
- 20260620-add-plugin-keyring-option.yaml
- 20260629-helm-force-helm-v4.yml
- 6-5-0.yml
- fix-openshift-clients-ee-dependency.yaml
modules:
- description: Generate, update, and optionally write Kubernetes kubeconfig files
name: kubeconfig
namespace: ''
release_date: '2026-07-08'
6.6.0:
changes:
bugfixes:
- Ansible Turbo mode - ignore ``ENABLE_TURBO_MODE`` on ansible-core 2.19.0 and
later, where the ``cloud.common`` collection is not supported, and fall back
to the standard ``AnsibleModule`` instead of failing with ``byte indices must
be integers or slices, not str`` (https://github.com/ansible-collections/kubernetes.core/pull/1242).
- helm - do not pass the upgrade-only ``--reuse-values`` and ``--reset-then-reuse-values``
flags to ``helm install``, which rejected them with ``unknown flag`` whenever
``reuse_values`` or ``reset_then_reuse_values`` was combined with ``replace``
(https://github.com/ansible-collections/kubernetes.core/pull/1230).
- helm - fix the ``reuse_values`` example, which set only ``reuse_values=true``.
``reset_values`` defaults to ``true`` and helm ignores ``--reuse-values``
whenever ``--reset-values`` is passed, so following the example reset the
release values instead of reusing them (https://github.com/ansible-collections/kubernetes.core/pull/1230).
- helm - skip Helm's OCI registry progress messages when parsing the output
of ``helm show chart``. As of Helm 4.2.1 these are printed to stdout instead
of stderr (https://github.com/helm/helm/pull/32056), which made installing
a chart from an OCI registry fail with a YAML scanner error when the chart
version contained a ``+`` (https://github.com/ansible-collections/kubernetes.core/pull/1223).
- helm_repository - normalize both sides of the repository URL comparison, so
that a repository already registered with a trailing slash is recognized as
matching instead of failing with ``Repository already have a repository named
<name>`` (https://github.com/ansible-collections/kubernetes.core/pull/1236).
- helm_template - strip Helm's OCI registry progress messages from the returned
``stdout``, which is documented to contain only the rendered templates (https://github.com/ansible-collections/kubernetes.core/pull/1223).
- k8s lookup - ignore ``ENABLE_TURBO_MODE`` on ansible-core 2.19.0 and later,
where the ``cloud.common`` collection is not supported. Fall back to the standard
``LookupBase`` instead of failing with a traceback (https://github.com/ansible-collections/kubernetes.core/pull/1253).
- k8s_cp - Fix silent truncation when copying to a pod. The module closed the
exec connection immediately after writing the last chunk of the tar archive,
which killed the remote ``tar`` before it had finished extracting, and never
checked the process exit status, so a partial copy was reported as a success.
The archive is now bounded with ``head -c`` so ``tar`` gets a clean EOF and
exits on its own, and the module waits for that exit and fails on a non-zero
status (https://github.com/ansible-collections/kubernetes.core/pull/1217).
- k8s_info - Handle empty template output gracefully by returning ``changed=false``
instead of failing when Jinja2 template renders to an empty string (https://github.com/ansible-collections/kubernetes.core/issues/1042).
deprecated_features:
- Ansible Turbo mode (``ENABLE_TURBO_MODE``) has been deprecated and will be
removed in release 8.0.0, as it depends on the ``cloud.common`` collection,
which is being retired (https://github.com/ansible-collections/kubernetes.core/pull/1242).
- helm - the ``status.values`` return value has been deprecated and will be
removed in version 8.0.0. Use ``status.release_values`` instead (https://github.com/ansible-collections/kubernetes.core/issues/1239).
- helm - the ``wait_timeout`` parameter has been deprecated and will be removed
in version 7.0.0. Use ``timeout`` instead (https://github.com/ansible-collections/kubernetes.core/issues/1239).
- helm_info - the ``status.values`` return value has been deprecated and will
be removed in version 8.0.0. Use ``status.release_values`` instead (https://github.com/ansible-collections/kubernetes.core/issues/1239).
- k8s_exec - the ``return_code`` return value has been deprecated and will be
removed in version 7.0.0. Use ``rc`` instead (https://github.com/ansible-collections/kubernetes.core/issues/1239).
- k8s_service - the ``merge_type=json`` option has been deprecated and will
be removed in version 7.0.0. Use ``kubernetes.core.k8s_json_patch`` module
instead (https://github.com/ansible-collections/kubernetes.core/issues/1239).
minor_changes:
- Remove the remaining ``ansible.module_utils.six`` import to avoid deprecation
warnings, replacing it with the Python standard library equivalent (https://github.com/ansible-collections/kubernetes.core/pull/1197).
- helm - Add ``wait_for_jobs`` option to wait for all Jobs to complete before
marking a Helm release as successful. Requires Helm >= 3.5.0 (https://github.com/ansible-collections/kubernetes.core/pull/1140).
- helm - add the ``cleanup_on_fail`` option, mapping to the ``--cleanup-on-fail``
flag, to allow deletion of new resources created during a failed upgrade.
It complements ``atomic`` and can be combined with it, but cannot be used
with ``replace``, since that deploys through ``helm install`` which does not
accept the flag (https://github.com/ansible-collections/kubernetes.core/pull/1206).
- helm - warn when ``reuse_values`` or ``reset_then_reuse_values`` is requested
in a combination helm ignores, which happens by default because ``reset_values``
defaults to ``true``, and whenever either is combined with ``replace``. The
option descriptions and the examples now state that ``reset_values`` has to
be set to ``false`` for either option to take effect (https://github.com/ansible-collections/kubernetes.core/pull/1230).
- k8s lookup - warn when ``ENABLE_TURBO_MODE`` is set but the ``cloud.common``
collection is not installed, instead of silently falling back to the standard
lookup base (https://github.com/ansible-collections/kubernetes.core/pull/1242).
- k8s_cp - Add the ``copy_timeout`` option (default 300 seconds) bounding how
long the module will spend streaming an archive to a pod and waiting for the
remote ``tar`` to finish, so that a stalled copy fails instead of hanging
indefinitely (https://github.com/ansible-collections/kubernetes.core/pull/1217).
- k8s_cp - Stream the tar archive to the pod chunk by chunk instead of building
the whole archive in memory first, which cuts peak memory use when copying
large files (https://github.com/ansible-collections/kubernetes.core/pull/1217).
- k8s_cp - When copying to a pod, the module now also uses ``/bin/sh`` and ``head``
in the container, when present, to confirm the copy completed. Containers
without them keep the previous behaviour and get a warning that completion
could not be verified (https://github.com/ansible-collections/kubernetes.core/pull/1217).
- k8s_info - Support for metadata-only fetches in k8s_info module (https://github.com/ansible-collections/kubernetes.core/pull/1030)
- meta - Add ``helm_plugin`` and ``helm_plugin_info`` to the ``helm`` action
group, and ``k8s_taint`` to the ``k8s`` action group, so that ``module_defaults``
set on those groups applies to them (https://github.com/ansible-collections/kubernetes.core/pull/1216).
- use `collections.abc` instead of deprecated `ansible.module_utils.common._collections_compat`
(https://github.com/ansible-collections/kubernetes.core/pull/1057).
- waiter - Add ``job_complete`` predicate to support waiting for Job resources
to reach ``Complete`` or ``Failed`` condition (https://github.com/ansible-collections/kubernetes.core/issues/1201).
fragments:
- 1253-k8s-lookup-turbo-version-check.yml
- 20250108-fix-empty-template-output.yaml
- 20251027-metadata-only-fetches.yaml
- 20260109-fix-deprecated-calls.yaml
- 20260723-remove-module-utils-six.yaml
- 20260805-add-job-wait-condition.yaml
- 20260807-helm-cleanup-on-fail.yaml
- 20260807-helm-wait-for-jobs.yaml
- 20260812-action-groups.yaml
- 20260813-k8s-cp-truncation.yaml
- 20260817-helm-oci-registry-progress-on-stdout.yml
- 20260826-helm-value-reuse-options.yaml
- 20260908-helm-repository-trailing-slash.yaml
- 20260911-deprecate-status-values.yaml
- 20260911-update-deprecation-notices.yaml
- deprecate-enable-turbo-mode.yml
- fix-ansible-lint-warnings.yaml
release_date: '2026-09-16'
+2 -17
View File
@@ -12,20 +12,6 @@ Following document provides overview of Ansible Turbo mode in ``kubernetes.core`
:depth: 1
.. warning::
Ansible Turbo mode is **deprecated** and will be removed in a future major release
(planned for 8.0.0), as it depends on the ``cloud.common`` collection, which is being
retired. Setting ``ENABLE_TURBO_MODE`` now emits a deprecation warning; once support is
removed, the variable will have no effect. Start planning your migration away from
Turbo mode.
.. warning::
Ansible Turbo mode is supported only with ``ansible-core`` versions **lower than 2.19**.
Starting from ``ansible-core`` 2.19, the ``cloud.common`` collection is no longer supported,
and therefore Ansible Turbo mode is also not supported in ``kubernetes.core``.
If ``ENABLE_TURBO_MODE`` is set to ``1`` (or any truthy value) with ``ansible-core >= 2.19.0``,
Turbo mode is ignored and a warning is emitted; modules run without it.
Synopsis
--------
- A brief introduction about Ansible Turbo mode in ``kuberentes.core`` collection.
@@ -34,9 +20,8 @@ Synopsis
Requirements
------------
The following requirements are needed on the host that executes this module.
The following requirement is needed on the host that executes this module.
- ``ansible-core`` version lower than 2.19.
- The ``cloud.common`` collection (https://github.com/ansible-collections/cloud.common)
You will also need to set the environment variable ``ENABLE_TURBO_MODE=1`` on the managed host. This can be done in the same ways you would usually do so, for example::
@@ -159,4 +144,4 @@ You may want to manually start the server. This can be done with the following c
PYTHONPATH=$HOME/.ansible/collections python -m ansible_collections.cloud.common.plugins.module_utils.turbo.server --socket-path $HOME/.ansible/tmp/turbo_mode.kubernetes.core.socket
You can use the ``--help`` argument to get a list of the optional parameters.
You can use the ``--help`` argument to get a list of the optional parameters.
@@ -17,7 +17,7 @@ Requirements
To use the modules, you'll need the following:
- Ansible 2.16.0 or latest installed
- Ansible 2.9.17 or latest installed
- `Kubernetes Python client <https://pypi.org/project/kubernetes/>`_ installed on the host that will execute the modules.
@@ -42,92 +42,6 @@ Basic authentication is also supported using the ``username`` and ``password`` o
To disable SSL certificate verification, set ``verify_ssl`` to false.
Sharing options across tasks with action groups
===============================================
Repeating the same authentication options on every task gets verbose quickly. The collection
defines two `action groups <https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_module_defaults.html#module-defaults-groups>`_
so you can set them once with ``module_defaults``:
``kubernetes.core.k8s``
Modules that talk to the Kubernetes API and accept the standard authentication options
(``kubeconfig``, ``context``, ``host``, ``api_key``, ``validate_certs``, and so on):
``k8s``, ``k8s_cluster_info``, ``k8s_cp``, ``k8s_drain``, ``k8s_exec``, ``k8s_info``,
``k8s_json_patch``, ``k8s_log``, ``k8s_rollback``, ``k8s_scale``, ``k8s_service``, and
``k8s_taint``.
``kubernetes.core.helm``
Modules that shell out to the ``helm`` binary and accept its shared authentication
options (``binary_path``, ``kubeconfig``, ``context``, ``host``, ``api_key``,
``ca_cert``, ``validate_certs``): ``helm``, ``helm_info``, ``helm_plugin``,
``helm_plugin_info``, and ``helm_repository``.
Prefix the group name with ``group/`` to use it:
.. code-block:: yaml
- hosts: localhost
module_defaults:
group/kubernetes.core.k8s:
kubeconfig: /path/to/kubeconfig
context: staging
group/kubernetes.core.helm:
binary_path: /path/to/helm
kubeconfig: /path/to/kubeconfig
context: staging
tasks:
- name: Create a namespace
kubernetes.core.k8s:
definition:
apiVersion: v1
kind: Namespace
metadata:
name: monitoring
- name: Read it back
kubernetes.core.k8s_info:
kind: Namespace
name: monitoring
- name: Add the prometheus chart repository
kubernetes.core.helm_repository:
name: prometheus-community
repo_url: https://prometheus-community.github.io/helm-charts
- name: Deploy the kube-prometheus-stack chart
kubernetes.core.helm:
name: kube-prometheus-stack
chart_ref: prometheus-community/kube-prometheus-stack
release_namespace: monitoring
- name: Collect the releases in that namespace
kubernetes.core.helm_info:
name: kube-prometheus-stack
release_namespace: monitoring
Every task picks up ``kubeconfig`` and ``context`` from its group without repeating them, the
``helm`` modules additionally pick up ``binary_path``, and an option set on an individual task
still wins over the group default.
.. note::
Always write the group name fully qualified as ``group/kubernetes.core.k8s``. A bare
``group/k8s`` refers to the legacy ``k8s`` group that ansible-core defined back when the
Kubernetes modules shipped in core itself. The two are not the same group, and the legacy
one does not cover the modules in this collection.
Some modules are deliberately **not** in these groups because they do not accept the shared
authentication options, and including them would make ``module_defaults`` fail for everyone
using the group:
- ``helm_pull`` and ``helm_template`` accept only ``binary_path``.
- ``helm_registry_auth`` accepts ``binary_path`` and its own ``host``, which is an OCI
registry URL rather than a Kubernetes API server.
- ``kubeconfig`` writes a kubeconfig file locally and takes no cluster connection options.
Pass options to those modules directly, or give them their own per-module ``module_defaults``
entry.
Reporting an issue
==================
@@ -0,0 +1,88 @@
.. _ansible_collections.kubernetes.core.docsite.k8s_ansible_inventory:
*****************************************
Using Kubernetes dynamic inventory plugin
*****************************************
.. contents::
:local:
Kubernetes dynamic inventory plugin
===================================
The best way to interact with your Pods is to use the Kubernetes dynamic inventory plugin, which queries Kubernetes APIs using ``kubectl`` command line available on controller node and tells Ansible what Pods can be managed.
Requirements
------------
To use the Kubernetes dynamic inventory plugins, you must install `Kubernetes Python client <https://github.com/kubernetes-client/python>`_, `kubectl <https://github.com/kubernetes/kubectl>`_ on your control node (the host running Ansible).
.. code-block:: bash
$ pip install kubernetes
Please refer to Kubernetes official documentation for `installing kubectl <https://kubernetes.io/docs/tasks/tools/install-kubectl/>`_ on the given operating systems.
To use this Kubernetes dynamic inventory plugin, you need to enable it first by specifying the following in the ``ansible.cfg`` file:
.. code-block:: ini
[inventory]
enable_plugins = kubernetes.core.k8s
Then, create a file that ends in ``.k8s.yml`` or ``.k8s.yaml`` in your working directory.
The ``kubernetes.core.k8s`` inventory plugin takes in the same authentication information as any other Kubernetes modules.
Here's an example of a valid inventory file:
.. code-block:: yaml
plugin: kubernetes.core.k8s
Executing ``ansible-inventory --list -i <filename>.k8s.yml`` will create a list of Pods that are ready to be configured using Ansible.
You can also provide the namespace to gather information about specific pods from the given namespace. For example, to gather information about Pods under the ``test`` namespace you will specify the ``namespaces`` parameter:
.. code-block:: yaml
plugin: kubernetes.core.k8s
connections:
- namespaces:
- test
Using vaulted configuration files
=================================
Since the inventory configuration file contains Kubernetes related sensitive information in plain text, a security risk, you may want to
encrypt your entire inventory configuration file.
You can encrypt a valid inventory configuration file as follows:
.. code-block:: bash
$ ansible-vault encrypt <filename>.k8s.yml
New Vault password:
Confirm New Vault password:
Encryption successful
$ echo "MySuperSecretPassw0rd!" > /path/to/vault_password_file
And you can use this vaulted inventory configuration file using:
.. code-block:: bash
$ ansible-inventory -i <filename>.k8s.yml --list --vault-password-file=/path/to/vault_password_file
.. seealso::
`Kubernetes Python client - Issue Tracker <https://github.com/kubernetes-client/python/issues>`_
The issue tracker for Kubernetes Python client
`Kubectl installation <https://kubernetes.io/docs/tasks/tools/install-kubectl/>`_
Installation guide for installing Kubectl
:ref:`working_with_playbooks`
An introduction to playbooks
:ref:`playbooks_vault`
Using Vault in playbooks
+1
View File
@@ -13,5 +13,6 @@ To get started, please select one of the following topics.
:maxdepth: 1
kubernetes_scenarios/k8s_intro
kubernetes_scenarios/k8s_inventory
kubernetes_scenarios/k8s_scenarios
+3 -21
View File
@@ -25,7 +25,7 @@ Requirements
------------
The below requirements are needed on the host that executes this module.
- helm >= 3.0.0 (https://github.com/helm/helm/releases)
- helm (https://github.com/helm/helm/releases)
- yaml (https://pypi.org/project/PyYAML/)
@@ -268,7 +268,7 @@ Examples
Return Values
-------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html
@@ -410,23 +410,6 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>release_values</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.3.0</div>
</td>
<td>always</td>
<td>
<div>Dict of Values used to deploy.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
@@ -482,13 +465,12 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
<b>values</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
<span style="color: purple">string</span>
</div>
</td>
<td>always</td>
<td>
<div>Dict of Values used to deploy</div>
<div>This return value has been deprecated and will be removed in version 8.0.0. Use RV(status.release_values) instead.</div>
<br/>
</td>
</tr>
+9 -255
View File
@@ -25,7 +25,7 @@ Requirements
------------
The below requirements are needed on the host that executes this module.
- helm >= 3.0.0 (https://github.com/helm/helm/releases)
- helm (https://github.com/helm/helm/releases)
- yaml (https://pypi.org/project/PyYAML/)
@@ -73,7 +73,6 @@ Parameters
</td>
<td>
<div>If set, the installation process deletes the installation on failure.</div>
<div>With Helm v4 this is translated to the <code>--rollback-on-failure</code> flag, since <code>--atomic</code> was renamed; with Helm v3 the <code>--atomic</code> flag is used. The O(atomic) option works the same way regardless of the installed Helm version.</div>
</td>
</tr>
<tr>
@@ -157,29 +156,6 @@ Parameters
<div>Chart version to install. If this is not specified, the latest version is installed.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>cleanup_on_fail</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.6.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&nbsp;&larr;</div></li>
<li>yes</li>
</ul>
</td>
<td>
<div>Allow deletion of new resources created during a failed upgrade.</div>
<div>Maps to the <code>--cleanup-on-fail</code> flag, which is available since helm 3.0.0 and was not renamed in Helm v4.</div>
<div>Complements O(atomic) rather than replacing it, and the two can be combined so that a rollback also drops resources orphaned by the failed upgrade.</div>
<div>Helm only accepts this flag on <code>helm upgrade</code>, so it cannot be used together with O(replace), which deploys through <code>helm install</code>.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -278,30 +254,6 @@ Parameters
</td>
<td>
<div>Helm option to force reinstall, ignore on new install.</div>
<div>With Helm v4 this performs a client-side replacement. Helm v4 deprecated <code>--force</code> (split into <code>--force-replace</code> and <code>--force-conflicts</code>) and enables server-side apply by default, so for Helm v4 the module emits <code>--server-side=false --force-replace</code> to preserve the Helm v3 behaviour. With Helm v3 the <code>--force</code> flag is used. The O(force) option works the same way regardless of the installed Helm version.</div>
<div>Mutually exclusive with O(server_side) and O(force_conflicts).</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>force_conflicts</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.5.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&nbsp;&larr;</div></li>
<li>yes</li>
</ul>
</td>
<td>
<div>When server-side apply is enabled (the Helm v4 default), force changes against conflicts instead of failing.</div>
<div>Maps to the <code>--force-conflicts</code> flag.</div>
<div>This option requires Helm v4, cannot be combined with O(server_side=false), and is mutually exclusive with O(force).</div>
</td>
</tr>
<tr>
@@ -337,29 +289,6 @@ Parameters
<div>Provide a URL for accessing the API. Can also be specified via <code>K8S_AUTH_HOST</code> environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>insecure_skip_tls_verify</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 5.3.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&nbsp;&larr;</div></li>
<li>yes</li>
</ul>
</td>
<td>
<div>Skip tls certificate checks for the chart download.</div>
<div>Do not confuse with the <code>validate_certs</code> option.</div>
<div>This option is only available for helm &gt;= 3.16.0.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: skip_tls_certs_check</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -378,27 +307,6 @@ Parameters
<div style="font-size: small; color: darkgreen"><br/>aliases: kubeconfig_path</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>plain_http</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.1.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&nbsp;&larr;</div></li>
<li>yes</li>
</ul>
</td>
<td>
<div>Use HTTP instead of HTTPS when working with OCI registries</div>
<div>Requires Helm &gt;= 3.13.0</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -527,30 +435,6 @@ Parameters
<div>mutually exclusive with with <code>history_max</code>.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>reset_then_reuse_values</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.0.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&nbsp;&larr;</div></li>
<li>yes</li>
</ul>
</td>
<td>
<div>When upgrading package, reset the values to the ones built into the chart, apply the last release&#x27;s values and merge in any overrides from parameters O(release_values), O(values_files) or O(set_values).</div>
<div>Helm ignores this when <code>--reset-values</code> or <code>--reuse-values</code> is passed. Since O(reset_values) defaults to V(true), it has to be set to V(false), and O(reuse_values) left unset or V(false), for this option to take any effect.</div>
<div><code>helm install</code> does not accept <code>--reset-then-reuse-values</code>, so this option is ignored when O(replace) is set.</div>
<div>The module warns whenever one of those combinations makes this option a no-op.</div>
<div>This feature requires helm diff &gt;= 3.9.12.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -559,7 +443,7 @@ Parameters
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 3.0.0</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.5.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
@@ -569,7 +453,6 @@ Parameters
</td>
<td>
<div>When upgrading package, reset the values to the ones built into the chart.</div>
<div>Defaults to V(true), which makes helm ignore O(reuse_values) and O(reset_then_reuse_values). Set it to V(false) to use either of them.</div>
</td>
</tr>
<tr>
@@ -580,7 +463,7 @@ Parameters
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 3.0.0</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.5.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
@@ -589,33 +472,8 @@ Parameters
</ul>
</td>
<td>
<div>When upgrading package, specifies whether to reuse the last release&#x27;s values and merge in any overrides from parameters O(release_values), O(values_files) or O(set_values).</div>
<div>Helm ignores this when <code>--reset-values</code> is passed. Since O(reset_values) defaults to V(true), it has to be set to V(false) for this option to take any effect.</div>
<div><code>helm install</code> does not accept <code>--reuse-values</code>, so this option is ignored when O(replace) is set.</div>
<div>The module warns whenever one of those combinations makes this option a no-op.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>server_side</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.5.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>auto</li>
<li>true</li>
<li>false</li>
</ul>
</td>
<td>
<div>Control Helm v4 server-side apply when installing or upgrading a release.</div>
<div>Maps to the <code>--server-side</code> flag, which accepts <code>true</code>, <code>false</code> or <code>auto</code>.</div>
<div>This option requires Helm v4 and is mutually exclusive with O(force).</div>
<div>When upgrading package, specifies wether to reuse the last release&#x27;s values and merge in any overrides from parameters <em>release_values</em>, <em>values_files</em> or <em>set_values</em>.</div>
<div>If <em>reset_values</em> is set to <code>True</code>, this is ignored.</div>
</td>
</tr>
<tr>
@@ -698,48 +556,6 @@ Parameters
<div>Skip custom resource definitions when installing or upgrading.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>skip_schema_validation</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.2.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&nbsp;&larr;</div></li>
<li>yes</li>
</ul>
</td>
<td>
<div>Disables JSON schema validation for Chart and values.</div>
<div>This feature requires helm &gt;= 3.16.0</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>take_ownership</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.1.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&nbsp;&larr;</div></li>
<li>yes</li>
</ul>
</td>
<td>
<div>Helm will ignore the check for helm annotations and take ownership of the existing resources</div>
<div>This feature requires helm &gt;= 3.17.0</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -839,28 +655,6 @@ Parameters
<div>When <em>release_state</em> is set to <code>absent</code>, will wait until all the resources are deleted before returning. It will wait for as long as <em>wait_timeout</em>. This feature requires helm&gt;=3.7.0. Added in version 2.3.0.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>wait_for_jobs</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.6.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&nbsp;&larr;</div></li>
<li>yes</li>
</ul>
</td>
<td>
<div>When <em>release_state</em> is set to <code>present</code>, and <em>wait</em> is set to <code>True</code>, wait until all jobs are in a completed state before marking the release as successful.</div>
<div>Ignored when used without O(wait).</div>
<div>Requires Helm &gt;= 3.5.0</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -874,7 +668,7 @@ Parameters
</td>
<td>
<div>Timeout when wait option is enabled (helm2 is a number of seconds, helm3 is a duration).</div>
<div>The use of <em>wait_timeout</em> to wait for kubernetes commands to complete has been deprecated and will be removed in version 7.0.0. Use O(timeout) instead.</div>
<div>The use of <em>wait_timeout</em> to wait for kubernetes commands to complete has been deprecated and will be removed after 2022-12-01.</div>
</td>
</tr>
</table>
@@ -971,12 +765,6 @@ Examples
chart_ref: "https://github.com/grafana/helm-charts/releases/download/grafana-5.6.0/grafana-5.6.0.tgz"
release_namespace: monitoring
- name: Deploy Bitnami's MongoDB latest chart from OCI registry
kubernetes.core.helm:
name: test
chart_ref: "oci://registry-1.docker.io/bitnamicharts/mongodb"
release_namespace: database
# Using complex Values
- name: Deploy new-relic client chart
kubernetes.core.helm:
@@ -985,7 +773,6 @@ Examples
release_namespace: default
force: True
wait: True
wait_for_jobs: True
replace: True
update_repo_cache: True
disable_hook: True
@@ -1005,36 +792,21 @@ Examples
enabled: True
# Deploy latest version
# 'reset_values' defaults to true and helm ignores '--reuse-values' when it is set,
# so it has to be turned off explicitly.
- name: Deploy latest version of Grafana chart using reuse_values
kubernetes.core.helm:
name: test
chart_ref: stable/grafana
release_namespace: monitoring
reuse_values: true
reset_values: false
values:
replicas: 2
version: 3e8ec0b2dffa40fb97d5342e4af887de95faa8c61a62480dd7f8aa03dffcf533
# Same for 'reset_then_reuse_values', which helm ignores when either
# '--reset-values' or '--reuse-values' is set.
- name: Deploy latest version of Grafana chart using reset_then_reuse_values
kubernetes.core.helm:
name: test
chart_ref: stable/grafana
release_namespace: monitoring
reset_then_reuse_values: true
reset_values: false
values:
replicas: 2
Return Values
-------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html
@@ -1140,23 +912,6 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>release_values</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.3.0</div>
</td>
<td>always</td>
<td>
<div>Dict of Values used to deploy.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
@@ -1212,13 +967,12 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
<b>values</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
<span style="color: purple">string</span>
</div>
</td>
<td>always</td>
<td>
<div>Dict of Values used to deploy.</div>
<div>This return value has been deprecated and will be removed in version 8.0.0. Use RV(status.release_values) instead.</div>
<div>Dict of Values used to deploy</div>
<br/>
</td>
</tr>
@@ -25,7 +25,7 @@ Requirements
------------
The below requirements are needed on the host that executes this module.
- helm >= 3.0.0 (https://github.com/helm/helm/releases)
- helm (https://github.com/helm/helm/releases)
Parameters
@@ -196,7 +196,7 @@ Examples
Return Values
-------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html
+2 -42
View File
@@ -25,7 +25,7 @@ Requirements
------------
The below requirements are needed on the host that executes this module.
- helm >= 3.0.0 (https://github.com/helm/helm/releases)
- helm (https://github.com/helm/helm/releases)
Parameters
@@ -120,24 +120,6 @@ Parameters
<div>Provide a URL for accessing the API. Can also be specified via <code>K8S_AUTH_HOST</code> environment variable.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>keyring</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.5.0</div>
</td>
<td>
</td>
<td>
<div>Location of public keys used for verification.</div>
<div>Only valid with <code>state=present</code>, which maps to the <code>helm plugin install</code> subcommand.</div>
<div>This option requires helm version &gt;= 4.0.0.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -249,28 +231,6 @@ Parameters
<div style="font-size: small; color: darkgreen"><br/>aliases: verify_ssl</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>verify</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.4.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>no</li>
<li><div style="color: blue"><b>yes</b>&nbsp;&larr;</div></li>
</ul>
</td>
<td>
<div>Verify the plugin signature before installing.</div>
<div>This option requires helm version &gt;= 4.0.0</div>
<div>Used with <em>state=present</em>.</div>
</td>
</tr>
</table>
<br/>
@@ -312,7 +272,7 @@ Examples
Return Values
-------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html
+3 -81
View File
@@ -27,7 +27,7 @@ Requirements
------------
The below requirements are needed on the host that executes this module.
- helm >= 3.0.0 (https://github.com/helm/helm/releases)
- helm >= 3.0 (https://github.com/helm/helm/releases)
Parameters
@@ -174,28 +174,6 @@ Parameters
<div>location to write the chart.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>force</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.3.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&nbsp;&larr;</div></li>
<li>yes</li>
</ul>
</td>
<td>
<div>Force download of the chart even if it already exists in the destination directory.</div>
<div>By default, the module will skip downloading if the chart with the same version already exists for idempotency.</div>
<div>When used with O(untar_chart=true), will remove any existing chart directory before extracting.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -215,27 +193,6 @@ Parameters
<div>Pass credentials to all domains.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>plain_http</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.1.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&nbsp;&larr;</div></li>
<li>yes</li>
</ul>
</td>
<td>
<div>Use HTTP instead of HTTPS when working with OCI registries</div>
<div>Requires Helm &gt;= 3.13.0</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -322,8 +279,7 @@ Parameters
</td>
<td>
<div>Whether or not to check tls certificate for the chart download.</div>
<div>Requires helm &gt;= 3.3.0. Alias <code>insecure_skip_tls_verify</code> added in 5.3.0.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: insecure_skip_tls_verify</div>
<div>Requires helm &gt;= 3.3.0.</div>
</td>
</tr>
<tr>
@@ -419,28 +375,11 @@ Examples
username: myuser
password: mypassword123
- name: Download Chart (force re-download even if exists)
kubernetes.core.helm_pull:
chart_ref: redis
repo_url: https://charts.bitnami.com/bitnami
chart_version: '17.0.0'
destination: /path/to/chart
force: yes
- name: Download and untar chart (force re-extraction even if directory exists)
kubernetes.core.helm_pull:
chart_ref: redis
repo_url: https://charts.bitnami.com/bitnami
chart_version: '17.0.0'
destination: /path/to/chart
untar_chart: yes
force: yes
Return Values
-------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html
@@ -467,23 +406,6 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
<div style="font-size: smaller; color: blue; word-wrap: break-word; word-break: break-all;">helm pull --repo test ...</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>msg</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>when chart already exists</td>
<td>
<div>A message indicating the result of the operation.</div>
<br/>
<div style="font-size: smaller"><b>Sample:</b></div>
<div style="font-size: smaller; color: blue; word-wrap: break-word; word-break: break-all;">Chart redis version 17.0.0 already exists in destination directory</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
@@ -1,359 +0,0 @@
.. _kubernetes.core.helm_registry_auth_module:
**********************************
kubernetes.core.helm_registry_auth
**********************************
**Helm registry authentication module**
Version added: 5.1.0
.. contents::
:local:
:depth: 1
Synopsis
--------
- Helm registry authentication module allows you to login ``helm registry login`` and logout ``helm registry logout`` from a Helm registry.
Requirements
------------
The below requirements are needed on the host that executes this module.
- helm (https://github.com/helm/helm/releases) >= 3.8.0
Parameters
----------
.. raw:: html
<table border=0 cellpadding=0 class="documentation-table">
<tr>
<th colspan="1">Parameter</th>
<th>Choices/<font color="blue">Defaults</font></th>
<th width="100%">Comments</th>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>binary_path</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>The path of a helm binary to use.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>ca_file</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to the CA certificate SSL file for verify registry server certificate.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>cert_file</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to the client certificate SSL file for identify registry client using this certificate file.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>host</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
/ <span style="color: red">required</span>
</div>
</td>
<td>
</td>
<td>
<div>Provide a URL for accessing the registry.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: registry_url</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>insecure</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&nbsp;&larr;</div></li>
<li>yes</li>
</ul>
</td>
<td>
<div>Allow connections to SSL sites without certs.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>key_file</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">path</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to the client key SSL file for identify registry client using this key file.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>password</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Password for the registry.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: repo_password</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>plain_http</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.4.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&nbsp;&larr;</div></li>
<li>yes</li>
</ul>
</td>
<td>
<div>Use insecure HTTP connections for <code>helm registry login</code>.</div>
<div>Requires Helm &gt;= 3.18.0</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>state</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>present</b>&nbsp;&larr;</div></li>
<li>absent</li>
</ul>
</td>
<td>
<div>Desired state of the registry.</div>
<div>If set to V(present) attempt to log in to the remote registry server using the URL specified in O(host).</div>
<div>If set to V(absent) attempt to log out from the remote registry server using the URL specified in O(host).</div>
<div>As helm &gt;= 3.18.0 reports successful logout even if the user is not logged in, this module will report a change regardless of the current state.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>username</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Username for the registry.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: repo_username</div>
</td>
</tr>
</table>
<br/>
Examples
--------
.. code-block:: yaml
- name: Login to remote registry
kubernetes.core.helm_registry_auth:
username: admin
password: "sample_password"
host: localhost:5000
- name: Logout from remote registry
kubernetes.core.helm_registry_auth:
state: absent
host: localhost:5000
Return Values
-------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html
<table border=0 cellpadding=0 class="documentation-table">
<tr>
<th colspan="1">Key</th>
<th>Returned</th>
<th width="100%">Description</th>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>command</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>always</td>
<td>
<div>Full <code>helm</code> command executed</div>
<br/>
<div style="font-size: smaller"><b>Sample:</b></div>
<div style="font-size: smaller; color: blue; word-wrap: break-word; word-break: break-all;">/usr/local/bin/helm registry login oci-registry.domain.example --username=admin --password-stdin --insecure</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>failed</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
</td>
<td>always</td>
<td>
<div>Indicate if the <code>helm</code> command failed</div>
<br/>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>stderr</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>always</td>
<td>
<div>Full <code>helm</code> command stderr, in case you want to display it or examine the event log.</div>
<div>Please note that the helm binary may print messages to stderr even if the command is successful.</div>
<div>On Helm versions earlier than 4.2.1, success messages such as <code>Login Succeeded</code> are printed here; as of Helm 4.2.1 they are printed to stdout (see <a href='https://github.com/helm/helm/pull/32056'>https://github.com/helm/helm/pull/32056</a>).</div>
<br/>
<div style="font-size: smaller"><b>Sample:</b></div>
<div style="font-size: smaller; color: blue; word-wrap: break-word; word-break: break-all;">Login Succeeded\n</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>stderr_lines</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
</div>
</td>
<td>always</td>
<td>
<div>Full <code>helm</code> command stderr, in case you want to display it or examine the event log</div>
<br/>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>stdout</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>always</td>
<td>
<div>Full <code>helm</code> command stdout, in case you want to display it or examine the event log.</div>
<div>As of Helm 4.2.1 success messages such as <code>Login Succeeded</code> are printed to stdout (see <a href='https://github.com/helm/helm/pull/32056'>https://github.com/helm/helm/pull/32056</a>). On earlier versions they are printed to stderr.</div>
<br/>
<div style="font-size: smaller"><b>Sample:</b></div>
<div style="font-size: smaller; color: blue; word-wrap: break-word; word-break: break-all;">Login Succeeded\n</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>stdout_lines</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
</div>
</td>
<td>always</td>
<td>
<div>Full <code>helm</code> command stdout, in case you want to display it or examine the event log</div>
<br/>
</td>
</tr>
</table>
<br/><br/>
Status
------
Authors
~~~~~~~
- Yuriy Novostavskiy (@yurnov)
@@ -25,7 +25,7 @@ Requirements
------------
The below requirements are needed on the host that executes this module.
- helm >= 3.0.0 (https://github.com/helm/helm/releases)
- helm (https://github.com/helm/helm/releases)
- yaml (https://pypi.org/project/PyYAML/)
@@ -143,27 +143,6 @@ Parameters
<div>Provide a URL for accessing the API. Can also be specified via <code>K8S_AUTH_HOST</code> environment variable.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>insecure_skip_tls_verify</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 5.3.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&nbsp;&larr;</div></li>
<li>yes</li>
</ul>
</td>
<td>
<div>Skip tls certificate checks for the repository url.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: skip_tls_certs_check</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -336,7 +315,7 @@ Examples
Return Values
-------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html
+1 -49
View File
@@ -20,13 +20,6 @@ Synopsis
Requirements
------------
The below requirements are needed on the host that executes this module.
- helm >= 3.0.0 (https://github.com/helm/helm/releases)
- yaml (https://pypi.org/project/PyYAML/)
Parameters
----------
@@ -165,26 +158,6 @@ Parameters
<div>Include custom resource descriptions in rendered templates.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>insecure_registry</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 5.1.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&nbsp;&larr;</div></li>
<li>yes</li>
</ul>
</td>
<td>
<div>Skip TLS certificate checks for the chart download</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -201,27 +174,6 @@ Parameters
<div>If the directory already exists, it will be overwritten.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>plain_http</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.1.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&nbsp;&larr;</div></li>
<li>yes</li>
</ul>
</td>
<td>
<div>Use HTTP instead of HTTPS when working with OCI registries</div>
<div>Requires Helm &gt;= 3.13.0</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -437,7 +389,7 @@ Examples
Return Values
-------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html
@@ -416,7 +416,7 @@ Examples
Return Values
-------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html
+1 -22
View File
@@ -152,25 +152,6 @@ Parameters
<div>The name of a context found in the config file. Can also be specified via K8S_AUTH_CONTEXT environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>copy_timeout</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">integer</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.6.0</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">300</div>
</td>
<td>
<div>Maximum time in seconds to spend streaming the archive to the pod and waiting for the remote <code>tar</code> process to finish extracting it.</div>
<div>Raise this when copying large files over a slow connection.</div>
<div>This option is ignored when <em>state</em> is set to <code>from_pod</code>.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -531,8 +512,6 @@ Notes
.. note::
- the tar binary is required on the container when copying from local filesystem to pod.
- a POSIX shell at ``/bin/sh`` and ``head`` are also used, when present, to bound the archive sent to the container so that the module can confirm the copy finished. Without them the copy still runs but completion cannot be verified, and a warning is emitted.
- the (init) container has to be started before you copy files or directories to it.
- To avoid SSL certificate validation errors when ``validate_certs`` is *True*, the full certificate chain for the API server must be provided via ``ca_cert`` or in the kubeconfig file.
@@ -591,7 +570,7 @@ Examples
Return Values
-------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html
+3 -4
View File
@@ -423,7 +423,7 @@ Parameters
<span style="color: purple">list</span>
/ <span style="color: purple">elements=string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 3.0.0</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.5.0</div>
</td>
<td>
</td>
@@ -595,8 +595,7 @@ Examples
kubernetes.core.k8s_drain:
state: drain
name: foo
delete_options:
force: yes
force: yes
- name: Drain node "foo", but abort if there are pods not managed by a ReplicationController, Job, or DaemonSet, and use a grace period of 15 minutes.
kubernetes.core.k8s_drain:
@@ -627,7 +626,7 @@ Examples
Return Values
-------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html
+2 -2
View File
@@ -481,7 +481,7 @@ Examples
Return Values
-------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html
@@ -535,7 +535,7 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
</td>
<td></td>
<td>
<div>The command status code. This attribute is deprecated and will be removed in version 7.0.0. Use RV(result.rc) instead.</div>
<div>The command status code. This attribute is deprecated and will be removed in a future release. Please use rc instead.</div>
<br/>
</td>
</tr>
+4 -47
View File
@@ -168,13 +168,14 @@ Parameters
<span style="color: purple">list</span>
/ <span style="color: purple">elements=string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 3.0.0</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.5.0</div>
</td>
<td>
</td>
<td>
<div>Hide fields matching any of the field definitions in the result</div>
<div>An example might be <code>hidden_fields=[metadata.managedFields]</code> or V(hidden_fields=[spec.containers[0].env[3].value]) or V(hidden_fields=[metadata.annotations[kubectl.kubernetes.io/last-applied-configuration]])</div>
<div>An example might be <code>hidden_fields=[metadata.managedFields]</code></div>
<div>Only field definitions that don&#x27;t reference list items are supported (so V(spec.containers[0]) would not work)</div>
</td>
</tr>
<tr>
@@ -280,29 +281,6 @@ Parameters
<div>List of label selectors to use to filter results</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>metadata_only</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.6.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>no</b>&nbsp;&larr;</div></li>
<li>yes</li>
</ul>
</td>
<td>
<div>Request metadata only response from the Kubernetes API server.</div>
<div>This feature is useful for clients that only need to check for the existence of an object,</div>
<div>or that only need to read its metadata.</div>
<div>It can significantly reduce the size of the response from the API server.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -724,32 +702,11 @@ Examples
wait_sleep: 10
wait_timeout: 360
- name: Wait for OpenShift bootstrap to complete
kubernetes.core.k8s_info:
api_version: v1
kind: ConfigMap
name: bootstrap
namespace: kube-system
register: ocp_bootstrap_status
until: >
ocp_bootstrap_status.resources is defined and
(ocp_bootstrap_status.resources | length > 0) and
(ocp_bootstrap_status.resources[0].data.status is defined) and
(ocp_bootstrap_status.resources[0].data.status == 'complete')
retries: 60
delay: 15
- name: Get a list of all pods metadata only
kubernetes.core.k8s_info:
kind: Pod
metadata_only: true
register: pod_metadata_list
Return Values
-------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html
+372
View File
@@ -0,0 +1,372 @@
.. _kubernetes.core.k8s_inventory:
*******************
kubernetes.core.k8s
*******************
**Kubernetes (K8s) inventory source**
.. contents::
:local:
:depth: 1
DEPRECATED
----------
:Removed in collection release after
:Why: As discussed in https://github.com/ansible-collections/kubernetes.core/issues/31, we decided to
remove the k8s inventory plugin in release 5.0.0.
:Alternative: Use :ref:`kubernetes.core.k8s_info <kubernetes.core.k8s_info_module>` and :ref:`ansible.builtin.add_host <ansible.builtin.add_host_module>` instead.
Synopsis
--------
- Fetch containers and services for one or more clusters.
- Groups by cluster name, namespace, namespace_services, namespace_pods, and labels.
- Uses the kubectl connection plugin to access the Kubernetes cluster.
- Uses k8s.(yml|yaml) YAML configuration file to set parameter values.
Requirements
------------
The below requirements are needed on the local Ansible controller node that executes this inventory.
- python >= 3.9
- kubernetes >= 24.2.0
- PyYAML >= 3.11
Parameters
----------
.. raw:: html
<table border=0 cellpadding=0 class="documentation-table">
<tr>
<th colspan="2">Parameter</th>
<th>Choices/<font color="blue">Defaults</font></th>
<th>Configuration</th>
<th width="100%">Comments</th>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>connections</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Optional list of cluster connection settings. If no connections are provided, the default <em>~/.kube/config</em> and active context will be used, and objects will be returned for all namespaces the active user is authorized to access.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>api_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Token used to authenticate with the API. Can also be specified via K8S_AUTH_API_KEY environment variable.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>ca_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Path to a CA certificate used to authenticate with the API. Can also be specified via K8S_AUTH_SSL_CA_CERT environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: ssl_ca_cert</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Path to a certificate used to authenticate with the API. Can also be specified via K8S_AUTH_CERT_FILE environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: cert_file</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Path to a key file used to authenticate with the API. Can also be specified via K8S_AUTH_KEY_FILE environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: key_file</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>context</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>The name of a context found in the config file. Can also be specified via K8S_AUTH_CONTEXT environment variable.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>host</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Provide a URL for accessing the API. Can also be specified via K8S_AUTH_HOST environment variable.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>kubeconfig</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Path to an existing Kubernetes config file. If not provided, and no other connection options are provided, the Kubernetes client will attempt to load the default configuration file from <em>~/.kube/config</em>. Can also be specified via K8S_AUTH_KUBECONFIG environment variable.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>name</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Optional name to assign to the cluster. If not provided, a name is constructed from the server and port.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>namespaces</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>List of namespaces. If not specified, will fetch all containers for all namespaces user is authorized to access.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>password</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Provide a password for authenticating with the API. Can also be specified via K8S_AUTH_PASSWORD environment variable.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>username</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Provide a username for authenticating with the API. Can also be specified via K8S_AUTH_USERNAME environment variable.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>validate_certs</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>no</li>
<li>yes</li>
</ul>
</td>
<td>
</td>
<td>
<div>Whether or not to verify the API server&#x27;s SSL certificates. Can also be specified via K8S_AUTH_VERIFY_SSL environment variable.</div>
<div style="font-size: small; color: darkgreen"><br/>aliases: verify_ssl</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>plugin</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">-</span>
/ <span style="color: red">required</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>kubernetes.core.k8s</li>
<li>k8s</li>
<li>community.kubernetes.k8s</li>
</ul>
</td>
<td>
</td>
<td>
<div>token that ensures this is a source file for the &#x27;k8s&#x27; plugin.</div>
</td>
</tr>
</table>
<br/>
Examples
--------
.. code-block:: yaml
# File must be named k8s.yaml or k8s.yml
- name: Authenticate with token, and return all pods and services for all namespaces
plugin: kubernetes.core.k8s
connections:
- host: https://192.168.64.4:8443
api_key: xxxxxxxxxxxxxxxx
validate_certs: false
- name: Use default config (~/.kube/config) file and active context, and return objects for a specific namespace
plugin: kubernetes.core.k8s
connections:
- namespaces:
- testing
- name: Use a custom config file, and a specific context.
plugin: kubernetes.core.k8s
connections:
- kubeconfig: /path/to/config
context: 'awx/192-168-64-4:8443/developer'
Status
------
- This inventory will be removed in version 5.0.0. *[deprecated]*
- For more information see `DEPRECATED`_.
Authors
~~~~~~~
- Chris Houseknecht (@chouseknecht)
- Fabian von Feilitzsch (@fabianvf)
.. hint::
Configuration entries for each entry type have a low to high priority order. For example, a variable that is lower in the list will override a variable that is higher up.
+1 -20
View File
@@ -140,25 +140,6 @@ Parameters
<div>The name of a context found in the config file. Can also be specified via K8S_AUTH_CONTEXT environment variable.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>hidden_fields</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
/ <span style="color: purple">elements=string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.1.0</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">[]</div>
</td>
<td>
<div>List of fields to hide from the diff output.</div>
<div>This is useful for fields that are not relevant to the patch operation, such as `metadata.managedFields`.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -640,7 +621,7 @@ Examples
Return Values
-------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html
+1 -1
View File
@@ -612,7 +612,7 @@ Examples
Return Values
-------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html
+20 -133
View File
@@ -38,13 +38,13 @@ Parameters
<table border=0 cellpadding=0 class="documentation-table">
<tr>
<th colspan="2">Parameter</th>
<th colspan="1">Parameter</th>
<th>Choices/<font color="blue">Defaults</font></th>
<th>Configuration</th>
<th width="100%">Comments</th>
</tr>
<tr>
<td colspan="2">
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>api_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -61,7 +61,7 @@ Parameters
</td>
</tr>
<tr>
<td colspan="2">
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>api_version</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -79,7 +79,7 @@ Parameters
</td>
</tr>
<tr>
<td colspan="2">
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>ca_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -97,7 +97,7 @@ Parameters
</td>
</tr>
<tr>
<td colspan="2">
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_cert</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -115,7 +115,7 @@ Parameters
</td>
</tr>
<tr>
<td colspan="2">
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client_key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -133,7 +133,7 @@ Parameters
</td>
</tr>
<tr>
<td colspan="2">
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>cluster_info</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -150,7 +150,7 @@ Parameters
</td>
</tr>
<tr>
<td colspan="2">
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>context</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -167,7 +167,7 @@ Parameters
</td>
</tr>
<tr>
<td colspan="2">
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>field_selector</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -184,7 +184,7 @@ Parameters
</td>
</tr>
<tr>
<td colspan="2">
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>host</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -201,7 +201,7 @@ Parameters
</td>
</tr>
<tr>
<td colspan="2">
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>kind</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -219,7 +219,7 @@ Parameters
</td>
</tr>
<tr>
<td colspan="2">
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>kubeconfig</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -236,7 +236,7 @@ Parameters
</td>
</tr>
<tr>
<td colspan="2">
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>label_selector</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -253,7 +253,7 @@ Parameters
</td>
</tr>
<tr>
<td colspan="2">
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>namespace</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -270,26 +270,7 @@ Parameters
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>no_proxy</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>The comma separated list of hosts/domains/IP/CIDR that shouldn&#x27;t go through proxy. Can also be specified via K8S_AUTH_NO_PROXY environment variable.</div>
<div>Please note that this module does not pick up typical proxy settings from the environment (e.g. NO_PROXY).</div>
<div>This feature requires kubernetes&gt;=19.15.0. When kubernetes library is less than 19.15.0, it fails even if no_proxy is set correctly.</div>
</td>
</tr>
<tr>
<td colspan="2">
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>password</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -306,101 +287,7 @@ Parameters
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>The URL of an HTTP proxy to use for the connection. Can also be specified via K8S_AUTH_PROXY environment variable.</div>
<div>Please note that this module does not pick up typical proxy settings from the environment (e.g. HTTP_PROXY).</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy_headers</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>The Header used for the HTTP proxy.</div>
<div>Documentation can be found here <a href='https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html?highlight=proxy_headers#urllib3.util.make_headers'>https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html?highlight=proxy_headers#urllib3.util.make_headers</a>.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>basic_auth</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Colon-separated username:password for basic authentication header.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_BASIC_AUTH environment.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy_basic_auth</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>Colon-separated username:password for proxy basic authentication header.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_PROXY_BASIC_AUTH environment.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>user_agent</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
</td>
<td>
<div>String representing the user-agent you want, such as foo/1.0.</div>
<div>Can also be specified via K8S_AUTH_PROXY_HEADERS_USER_AGENT environment.</div>
</td>
</tr>
<tr>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>resource_definition</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -417,7 +304,7 @@ Parameters
</td>
</tr>
<tr>
<td colspan="2">
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>resource_name</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -434,7 +321,7 @@ Parameters
</td>
</tr>
<tr>
<td colspan="2">
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>src</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -452,7 +339,7 @@ Parameters
</td>
</tr>
<tr>
<td colspan="2">
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>username</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -469,7 +356,7 @@ Parameters
</td>
</tr>
<tr>
<td colspan="2">
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>validate_certs</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
@@ -545,7 +432,7 @@ Examples
Return Values
-------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this lookup:
Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this lookup:
.. raw:: html
+27 -165
View File
@@ -216,7 +216,7 @@ Parameters
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 3.0.0</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.5.0</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
@@ -389,13 +389,14 @@ Parameters
<span style="color: purple">list</span>
/ <span style="color: purple">elements=string</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 3.0.0</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 2.5.0</div>
</td>
<td>
</td>
<td>
<div>Hide fields matching this option in the result</div>
<div>An example might be <code>hidden_fields=[metadata.managedFields]</code> or V(hidden_fields=[spec.containers[0].env[3].value]) or V(hidden_fields=[metadata.annotations[kubectl.kubernetes.io/last-applied-configuration]])</div>
<div>An example might be <code>hidden_fields=[metadata.managedFields]</code></div>
<div>Only field definitions that don&#x27;t reference list items are supported (so V(spec.containers[0]) would not work)</div>
</td>
</tr>
<tr>
@@ -1279,35 +1280,18 @@ Examples
Return Values
-------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html
<table border=0 cellpadding=0 class="documentation-table">
<tr>
<th colspan="3">Key</th>
<th colspan="2">Key</th>
<th>Returned</th>
<th width="100%">Description</th>
</tr>
<tr>
<td colspan="3">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>method</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>success</td>
<td>
<div>The method used to deploy the resource.</div>
<br/>
<div style="font-size: smaller"><b>Sample:</b></div>
<div style="font-size: smaller; color: blue; word-wrap: break-word; word-break: break-all;">create</div>
</td>
</tr>
<tr>
<td colspan="3">
<td colspan="2">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>result</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
@@ -1323,105 +1307,6 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>api_version</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>when O(resource_definition) or O(src) contains a single object.</td>
<td>
<div>The versioned schema of this representation of an object.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>duration</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">integer</span>
</div>
</td>
<td>when <code>wait</code> is true</td>
<td>
<div>elapsed time of task in seconds</div>
<br/>
<div style="font-size: smaller"><b>Sample:</b></div>
<div style="font-size: smaller; color: blue; word-wrap: break-word; word-break: break-all;">48</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>error</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">complex</span>
</div>
</td>
<td>error</td>
<td>
<div>error while trying to create/delete the object.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>kind</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>when O(resource_definition) or O(src) contains a single object.</td>
<td>
<div>Represents the REST resource this object represents.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>metadata</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">complex</span>
</div>
</td>
<td>when O(resource_definition) or O(src) contains a single object.</td>
<td>
<div>Standard object metadata. Includes name, namespace, annotations, labels, etc.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>results</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">complex</span>
</div>
</td>
<td>when O(resource_definition) or O(src) contains a list of objects.</td>
<td>
<div>An array of created, patched, or otherwise present objects.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>api_version</b>
@@ -1430,7 +1315,7 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
<span style="color: purple">string</span>
</div>
</td>
<td>when O(resource_definition) or O(src) contains a single object.</td>
<td>success</td>
<td>
<div>The versioned schema of this representation of an object.</div>
<br/>
@@ -1438,7 +1323,6 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>duration</b>
@@ -1457,7 +1341,6 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>error</b>
@@ -1474,6 +1357,21 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>items</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
</div>
</td>
<td>when resource_definition or src contains list of objects</td>
<td>
<div>Returned only when multiple yaml documents are passed to src or resource_definition</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
@@ -1483,7 +1381,7 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
<span style="color: purple">string</span>
</div>
</td>
<td>when O(resource_definition) or O(src) contains a single object.</td>
<td>success</td>
<td>
<div>Represents the REST resource this object represents.</div>
<br/>
@@ -1491,7 +1389,6 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>metadata</b>
@@ -1500,7 +1397,7 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
<span style="color: purple">complex</span>
</div>
</td>
<td>when O(resource_definition) or O(src) contains a single object.</td>
<td>success</td>
<td>
<div>Standard object metadata. Includes name, namespace, annotations, labels, etc.</div>
<br/>
@@ -1508,7 +1405,6 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>spec</b>
@@ -1517,7 +1413,7 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
<span style="color: purple">complex</span>
</div>
</td>
<td>when O(resource_definition) or O(src) contains a single object.</td>
<td>success</td>
<td>
<div>Specific attributes of the object. Will vary based on the <em>api_version</em> and <em>kind</em>.</div>
<br/>
@@ -1525,7 +1421,6 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>status</b>
@@ -1534,40 +1429,7 @@ Common return values are documented `here <https://docs.ansible.com/projects/ans
<span style="color: purple">complex</span>
</div>
</td>
<td>when O(resource_definition) or O(src) contains a single object.</td>
<td>
<div>Current status details for the object.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>spec</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">complex</span>
</div>
</td>
<td>when O(resource_definition) or O(src) contains a single object.</td>
<td>
<div>Specific attributes of the object. Will vary based on the <em>api_version</em> and <em>kind</em>.</div>
<br/>
</td>
</tr>
<tr>
<td class="elbow-placeholder">&nbsp;</td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>status</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">complex</span>
</div>
</td>
<td>when O(resource_definition) or O(src) contains a single object.</td>
<td>success</td>
<td>
<div>Current status details for the object.</div>
<br/>
+1 -1
View File
@@ -503,7 +503,7 @@ Examples
Return Values
-------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html
+1 -1
View File
@@ -686,7 +686,7 @@ Examples
Return Values
-------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html
+1 -2
View File
@@ -247,7 +247,6 @@ Parameters
<div>See <a href='https://kubernetes.io/docs/tasks/run-application/update-api-object-kubectl-patch/#use-a-json-merge-patch-to-update-a-deployment'>https://kubernetes.io/docs/tasks/run-application/update-api-object-kubectl-patch/#use-a-json-merge-patch-to-update-a-deployment</a></div>
<div>If more than one <code>merge_type</code> is given, the merge_types will be tried in order</div>
<div>This defaults to <code>[&#x27;strategic-merge&#x27;, &#x27;merge&#x27;]</code>, which is ideal for using the same parameters on resource kinds that combine Custom Resources and built-in resources.</div>
<div><em>merge_type=json</em> has been deprecated and will be removed in version 7.0.0. Use <span class='module'>kubernetes.core.k8s_json_patch</span> instead.</div>
</td>
</tr>
<tr>
@@ -615,7 +614,7 @@ Examples
Return Values
-------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html
+1 -1
View File
@@ -541,7 +541,7 @@ Examples
Return Values
-------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html
-863
View File
@@ -1,863 +0,0 @@
.. _kubernetes.core.kubeconfig_module:
**************************
kubernetes.core.kubeconfig
**************************
**Generate, update, and optionally write Kubernetes kubeconfig files**
Version added: 6.5.0
.. contents::
:local:
:depth: 1
Synopsis
--------
- Build, update, and manage Kubernetes kubeconfig files using structured input.
- Supports loading an existing kubeconfig file and merging clusters, users, and contexts.
- Can optionally write the resulting kubeconfig to a destination path.
- Ensures idempotent behavior by only updating files when changes occur.
Requirements
------------
The below requirements are needed on the host that executes this module.
- PyYAML >= 5.1
Parameters
----------
.. raw:: html
<table border=0 cellpadding=0 class="documentation-table">
<tr>
<th colspan="3">Parameter</th>
<th>Choices/<font color="blue">Defaults</font></th>
<th width="100%">Comments</th>
</tr>
<tr>
<td colspan="3">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>clusters</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
/ <span style="color: purple">elements=dictionary</span>
</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">[]</div>
</td>
<td>
<div>List of cluster definitions to merge into the kubeconfig.</div>
<div>Each cluster is identified by its <code>name</code>.</div>
<div>When <code>name</code> matches an existing cluster, the default <code>behavior</code> is V(merge).</div>
<div>See the <code>behavior</code> suboption for V(replace), V(keep), and V(remove).</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>behavior</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>merge</b>&nbsp;&larr;</div></li>
<li>replace</li>
<li>keep</li>
<li>remove</li>
</ul>
</td>
<td>
<div>How to handle merging if a cluster with this name already exists.</div>
<div><code>merge</code> - Update only the specified fields, preserve others (default).</div>
<div><code>replace</code> - Replace the entire cluster definition.</div>
<div><code>keep</code> - Keep existing cluster, skip this entry.</div>
<div><code>remove</code> - Remove the cluster entry entirely. Silently skipped if the entry does not exist.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>cluster</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
</td>
<td>
</td>
<td>
<div>Cluster configuration details.</div>
<div>Not required when <code>behavior</code> is V(remove).</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>certificate-authority</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to a CA certificate file for validating the API server certificate.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>certificate-authority-data</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Base64 encoded CA certificate data.</div>
<div>Use this instead of <code>certificate-authority</code> for embedded certificates.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>insecure-skip-tls-verify</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">boolean</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li>no</li>
<li>yes</li>
</ul>
</td>
<td>
<div>If true, the server&#x27;s certificate will not be validated.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>proxy-url</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Optional proxy URL for cluster connections.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>server</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
/ <span style="color: red">required</span>
</div>
</td>
<td>
</td>
<td>
<div>Kubernetes API server URL (e.g., <code>https://k8s.example.com:6443</code>).</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>tls-server-name</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Server name to use for server certificate validation.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>name</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
/ <span style="color: red">required</span>
</div>
</td>
<td>
</td>
<td>
<div>Unique name identifier for the cluster.</div>
</td>
</tr>
<tr>
<td colspan="3">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>contexts</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
/ <span style="color: purple">elements=dictionary</span>
</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">[]</div>
</td>
<td>
<div>List of context definitions linking users and clusters.</div>
<div>Each context is identified by its <code>name</code>.</div>
<div>When <code>name</code> matches an existing context, the default <code>behavior</code> is V(merge).</div>
<div>See the <code>behavior</code> suboption for V(replace), V(keep), and V(remove).</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>behavior</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>merge</b>&nbsp;&larr;</div></li>
<li>replace</li>
<li>keep</li>
<li>remove</li>
</ul>
</td>
<td>
<div>How to handle merging if a context with this name already exists.</div>
<div><code>merge</code> - Update only the specified fields, preserve others (default).</div>
<div><code>replace</code> - Replace the entire context definition.</div>
<div><code>keep</code> - Keep existing context, skip this entry.</div>
<div><code>remove</code> - Remove the context entry entirely. Silently skipped if the entry does not exist.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>context</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
</td>
<td>
</td>
<td>
<div>Context configuration linking cluster and user.</div>
<div>Not required when <code>behavior</code> is V(remove).</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>cluster</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
/ <span style="color: red">required</span>
</div>
</td>
<td>
</td>
<td>
<div>Name of the cluster to use (must match a cluster name in O(clusters)).</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>namespace</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Default namespace to use for this context.</div>
<div>If not specified, defaults to <code>default</code>.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>user</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
/ <span style="color: red">required</span>
</div>
</td>
<td>
</td>
<td>
<div>Name of the user to authenticate as (must match a user name in O(users)).</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>name</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
/ <span style="color: red">required</span>
</div>
</td>
<td>
</td>
<td>
<div>Unique name identifier for the context.</div>
</td>
</tr>
<tr>
<td colspan="3">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>current_context</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Name of the context to set as current/active.</div>
<div>This context will be used by default when using kubectl.</div>
<div>Must match one of the context names defined in O(contexts).</div>
</td>
</tr>
<tr>
<td colspan="3">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>dest</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Destination path where the final kubeconfig should be written.</div>
<div>If not specified, the kubeconfig will be saved to O(path).</div>
<div>Allows copying and modifying a kubeconfig to a new location.</div>
</td>
</tr>
<tr>
<td colspan="3">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>path</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
/ <span style="color: red">required</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to an existing kubeconfig file to load and merge from.</div>
<div>If the file does not exist, a new kubeconfig will be created.</div>
<div>This becomes the default destination if O(dest) is not specified.</div>
</td>
</tr>
<tr>
<td colspan="3">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>preferences</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">{}</div>
</td>
<td>
<div>Kubeconfig preferences.</div>
<div>Used for client-side settings like color output, default editor, etc.</div>
</td>
</tr>
<tr>
<td colspan="3">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>users</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">list</span>
/ <span style="color: purple">elements=dictionary</span>
</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">[]</div>
</td>
<td>
<div>List of user authentication configurations.</div>
<div>Each user is identified by its <code>name</code>.</div>
<div>When <code>name</code> matches an existing user, the default <code>behavior</code> is V(merge).</div>
<div>See the <code>behavior</code> suboption for V(replace), V(keep), and V(remove).</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>behavior</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
<ul style="margin: 0; padding: 0"><b>Choices:</b>
<li><div style="color: blue"><b>merge</b>&nbsp;&larr;</div></li>
<li>replace</li>
<li>keep</li>
<li>remove</li>
</ul>
</td>
<td>
<div>How to handle merging if a user with this name already exists.</div>
<div><code>merge</code> - Update only the specified fields, preserve others (default).</div>
<div><code>replace</code> - Replace the entire user definition.</div>
<div><code>keep</code> - Keep existing user, skip this entry.</div>
<div><code>remove</code> - Remove the user entry entirely. Silently skipped if the entry does not exist.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>name</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
/ <span style="color: red">required</span>
</div>
</td>
<td>
</td>
<td>
<div>Unique name identifier for the user.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td colspan="2">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>user</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
</td>
<td>
</td>
<td>
<div>User authentication configuration.</div>
<div>Not required when <code>behavior</code> is V(remove).</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>auth-provider</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
</td>
<td>
</td>
<td>
<div>Authentication provider configuration (e.g., for GCP, Azure).</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client-certificate</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to client certificate file.</div>
<div>Used for certificate-based authentication.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client-certificate-data</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Base64 encoded client certificate.</div>
<div>Use instead of <code>client-certificate</code> for embedded certificates.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client-key</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Path to client private key file.</div>
<div>Must be provided with <code>client-certificate</code>.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>client-key-data</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Base64 encoded client private key.</div>
<div>Use instead of <code>client-key</code> for embedded keys.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>exec</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
</td>
<td>
</td>
<td>
<div>Exec-based credential plugin configuration.</div>
<div>Used for external authentication providers.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>password</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Password for basic authentication.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>token</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Bearer token for authentication.</div>
</td>
</tr>
<tr>
<td class="elbow-placeholder"></td>
<td class="elbow-placeholder"></td>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>username</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>
</td>
<td>
<div>Username for basic authentication.</div>
</td>
</tr>
</table>
<br/>
Notes
-----
.. note::
- Input data is merged by resource name (cluster, user, context).
- Updates under O(clusters), O(users), and O(contexts) are matched by ``name`` against the kubeconfig loaded from O(path).
- For an existing ``name``, each entry's ``behavior`` suboption controls the update.
- The default is V(merge), which merges nested ``cluster``, ``user``, and ``context`` data so unspecified keys are preserved.
- With V(replace), the previous entry for that name is dropped and only the new definition is used.
- With V(keep), the existing entry is left unchanged.
- With V(remove), the existing entry is deleted from the kubeconfig entirely. If no entry with that name exists, the operation is silently skipped.
- This can be used to move kubeconfig files to a different location with different content.
- This module does not validate cluster connectivity or authentication.
- The module supports ``check_mode`` and will not write files when enabled.
- The structure follows standard Kubernetes kubeconfig format as defined in the Kubernetes documentation.
- Tokens and sensitive data should be protected using ansible-vault or environment variables.
See Also
--------
.. seealso::
`Kubernetes kubeconfig documentation <https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/>`_
Official Kubernetes documentation for kubeconfig files
`kubectl config documentation <https://kubernetes.io/docs/reference/kubectl/generated/kubectl_config/>`_
kubectl commands for working with kubeconfig files
Examples
--------
.. code-block:: yaml
# Create a new kubeconfig file with a single cluster
- name: Create basic kubeconfig
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
clusters:
- name: production-cluster
cluster:
server: https://prod.k8s.example.com:6443
certificate-authority-data: LS0tLS1CRUdJTi...
users:
- name: admin-user
user:
token: eyJhbGciOiJSUzI1NiIsImtpZCI6IiJ9...
contexts:
- name: prod-admin
context:
cluster: production-cluster
user: admin-user
namespace: production
current_context: prod-admin
- name: Add a second cluster to an existing kubeconfig without touching other entries
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
clusters:
- name: staging-cluster
cluster:
server: https://staging.k8s.example.com:6443
insecure-skip-tls-verify: true
users:
- name: staging-user
user:
client-certificate: /path/to/staging.crt
client-key: /path/to/staging.key
contexts:
- name: staging-admin
context:
cluster: staging-cluster
user: staging-user
namespace: staging
- name: Update only the token for an existing user, preserving all other user fields
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
users:
- name: admin-user
behavior: merge
user:
token: "{{ new_admin_token }}"
- name: Replace a cluster definition entirely.
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
clusters:
- name: production-cluster
behavior: replace
cluster:
server: https://new-prod.k8s.example.com:6443
certificate-authority-data: LS0tLS1CRUdJTi...
- name: Remove a decommissioned cluster, user, and context
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
clusters:
- name: old-cluster
behavior: remove
users:
- name: old-user
behavior: remove
contexts:
- name: old-context
behavior: remove
- name: Switch the active context
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
current_context: staging-admin
- name: Copy a kubeconfig to a new location with an additional cluster merged in
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
dest: /home/user/.kube/config-ci
clusters:
- name: ci-cluster
cluster:
server: https://ci.k8s.example.com:6443
insecure-skip-tls-verify: true
Return Values
-------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this module:
.. raw:: html
<table border=0 cellpadding=0 class="documentation-table">
<tr>
<th colspan="1">Key</th>
<th>Returned</th>
<th width="100%">Description</th>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>dest</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">string</span>
</div>
</td>
<td>always</td>
<td>
<div>The path where the kubeconfig was written.</div>
<br/>
<div style="font-size: smaller"><b>Sample:</b></div>
<div style="font-size: smaller; color: blue; word-wrap: break-word; word-break: break-all;">/home/user/.kube/config</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
<b>kubeconfig</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
<span style="color: purple">dictionary</span>
</div>
</td>
<td>always</td>
<td>
<div>The complete kubeconfig data structure.</div>
<br/>
</td>
</tr>
</table>
<br/><br/>
Status
------
Authors
~~~~~~~
- Youssef Khalid Ali (@YoussefKhalidAli)
@@ -365,85 +365,6 @@ Parameters
Examples
--------
.. code-block:: yaml
- name: Run a command in a pod using local kubectl with kubeconfig file ~/.kube/config
hosts: localhost
gather_facts: no
vars:
ansible_connection: kubernetes.core.kubectl
ansible_kubectl_namespace: my-namespace
ansible_kubectl_pod: my-pod
ansible_kubectl_container: my-container
tasks:
# be aware that the command is executed as the user that started the container
# and requires python to be installed in the image
- name: Run a command in a pod
ansible.builtin.command: echo "Hello, World!"
changed_when: false
- name: Run a command in a pod using local kubectl with inventory variables
# Example inventory:
# k8s:
# hosts:
# foo.example.com:
# ansible_connection: kubernetes.core.kubectl
# ansible_kubectl_kubeconfig: /root/.kube/foo.example.com.config
# ansible_kubectl_pod: my-foo-pod
# ansible_kubectl_container: my-foo-container
# ansible_kubectl_namespace: my-foo-namespace
# bar.example.com:
# ansible_connection: kubernetes.core.kubectl
# ansible_kubectl_kubeconfig: /root/.kube/bar.example.com.config
# ansible_kubectl_pod: my-bar-pod
# ansible_kubectl_container: my-bar-container
# ansible_kubectl_namespace: my-bar-namespace
hosts: k8s
gather_facts: no
tasks:
# be aware that the command is executed as the user that started the container
# and requires python to be installed in the image
- name: Run a command in a pod
ansible.builtin.command: echo "Hello, World!"
changed_when: false
- name: Run a command in a pod using dynamic inventory
hosts: localhost
gather_facts: no
vars:
kubeconfig: /root/.kube/config
namespace: my-namespace
my_app: my-app
tasks:
- name: Get My App pod info based on label
kubernetes.core.k8s_info:
kubeconfig: "{{ kubeconfig }}"
namespace: "{{ namespace }}"
kind: Pod
label_selectors: app.kubernetes.io/name = "{{ my_app }}"
register: my_app_pod
- name: Get My App pod name
ansible.builtin.set_fact:
my_app_pod_name: "{{ my_app_pod.resources[0].metadata.name }}"
- name: Add My App pod to inventory
ansible.builtin.add_host:
name: "{{ my_app_pod_name }}"
ansible_connection: kubernetes.core.kubectl
ansible_kubectl_kubeconfig: "{{ kubeconfig }}"
ansible_kubectl_pod: "{{ my_app_pod_name }}"
ansible_kubectl_namespace: "{{ namespace }}"
- name: Run a command in My App pod
# be aware that the command is executed as the user that started the container
# and requires python to be installed in the image
ansible.builtin.command: echo "Hello, World!"
changed_when: false
delegate_to: "{{ my_app_pod_name }}"
+1 -29
View File
@@ -95,26 +95,6 @@ Parameters
<div>Enable the helm chart inflation generator</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
<b>environment</b>
<a class="ansibleOptionLink" href="#parameter-" title="Permalink to this option"></a>
<div style="font-size: small">
<span style="color: purple">raw</span>
</div>
<div style="font-style: italic; font-size: small; color: darkgreen">added in 6.2.0</div>
</td>
<td>
<b>Default:</b><br/><div style="color: blue">{}</div>
</td>
<td>
</td>
<td>
<div>The environment variables to pass to the kustomize or kubectl command.</div>
<div>This can be a dictionary or a string in the format key=value, multiple pairs separated by space.</div>
</td>
</tr>
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="parameter-"></div>
@@ -165,19 +145,11 @@ Examples
kubernetes.core.k8s:
definition: "{{ lookup('kubernetes.core.kustomize', dir='/path/to/kustomization', enable_helm=True) }}"
- name: Create kubernetes resources for lookup output with environment variables in string format
kubernetes.core.k8s:
definition: "{{ lookup('kubernetes.core.kustomize', binary_path='/path/to/kubectl', environment='HTTP_PROXY=http://proxy.example.com:3128') }}"
- name: Create kubernetes resources for lookup output with environment variables in dict format
kubernetes.core.k8s:
definition: "{{ lookup('kubernetes.core.kustomize', binary_path='/path/to/kubectl', environment={'HTTP_PROXY': 'http://proxy.example.com:3128'}) }}"
Return Values
-------------
Common return values are documented `here <https://docs.ansible.com/projects/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this lookup:
Common return values are documented `here <https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html#common-return-values>`_, the following are the fields unique to this lookup:
.. raw:: html
+1 -1
View File
@@ -25,7 +25,7 @@ tags:
- openshift
- okd
- cluster
version: 6.6.0
version: 4.0.0
build_ignore:
- .DS_Store
- "*.tar.gz"
-1
View File
@@ -1 +0,0 @@
kubernetes-client [platform:fedora]
-5
View File
@@ -1,5 +0,0 @@
---
version: 3
dependencies:
python: requirements.txt
system: meta/ee-bindep.txt
+7 -17
View File
@@ -1,41 +1,31 @@
---
requires_ansible: '>=2.16.0'
requires_ansible: '>=2.14.0'
# Only modules that accept the shared authentication options belong in these
# groups: HELM_AUTH_ARG_SPEC for helm, AUTH_ARG_SPEC for k8s. Adding a module
# that does not accept them makes module_defaults fail for every user of the
# group. This excludes helm_pull, helm_registry_auth, helm_template and
# kubeconfig, which only take a subset (or none) of those options.
action_groups:
helm:
- helm
- helm_info
- helm_plugin
- helm_plugin_info
- helm_repository
k8s:
- k8s
- k8s_cluster_info
- k8s_cp
- k8s_drain
- k8s_exec
- k8s_info
- k8s_json_patch
- k8s_log
- k8s_rollback
- k8s_scale
- k8s_service
- k8s_taint
- k8s_cp
- k8s_drain
plugin_routing:
inventory:
openshift:
redirect: community.okd.openshift
k8s:
tombstone:
removal_version: 6.0.0
deprecation:
removal_version: 5.0.0
warning_text: >-
The k8s inventory plugin was slated for deprecation in 3.3.0 and has been removed in release 6.0.0. Use kubernetes.core.k8s_info and ansible.builtin.add_host instead.
The k8s inventory plugin has been deprecated and
will be removed in release 5.0.0.
modules:
k8s_auth:
redirect: community.okd.k8s_auth
+51 -56
View File
@@ -20,26 +20,35 @@ from ansible.errors import (
AnsibleError,
AnsibleFileNotFound,
)
from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
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.six import iteritems, string_types
from ansible.plugins.action import ActionBase
try:
from ansible.template import trust_as_template
except ImportError:
trust_as_template = None
class RemoveOmit(object):
def __init__(self, buffer, omit_value):
try:
import yaml
except ImportError:
raise AnsibleError("Failed to import the required Python library (PyYAML).")
self.data = yaml.safe_load_all(buffer)
self.omit = omit_value
def _from_yaml_to_definition(buffer):
try:
import yaml
except ImportError:
raise AnsibleError("Failed to import the required Python library (PyYAML).")
def remove_omit(self, data):
if isinstance(data, dict):
result = dict()
for key, value in iteritems(data):
if value == self.omit:
continue
result[key] = self.remove_omit(value)
return result
if isinstance(data, list):
return [self.remove_omit(v) for v in data if v != self.omit]
return data
# Handle empty template output
if buffer is None:
return []
return [doc for doc in yaml.safe_load_all(buffer) if doc is not None]
def output(self):
return [self.remove_omit(d) for d in self.data]
ENV_KUBECONFIG_PATH_SEPARATOR = ";" if platform.system() == "Windows" else ":"
@@ -103,7 +112,7 @@ class ActionModule(ActionBase):
"trim_blocks": True,
"lstrip_blocks": False,
}
if isinstance(template, str):
if isinstance(template, string_types):
# treat this as raw_params
template_param["path"] = template
elif isinstance(template, dict):
@@ -123,7 +132,7 @@ class ActionModule(ActionBase):
):
if s_type in template_args:
value = ensure_type(template_args[s_type], "string")
if value is not None and not isinstance(value, str):
if value is not None and not isinstance(value, string_types):
raise AnsibleActionFail(
"%s is expected to be a string, but got %s instead"
% (s_type, type(value))
@@ -198,8 +207,9 @@ class ActionModule(ActionBase):
"'template' is only a supported parameter for the 'k8s' module."
)
omit_value = task_vars.get("omit")
template_params = []
if isinstance(template, str) or isinstance(template, dict):
if isinstance(template, string_types) or isinstance(template, dict):
template_params.append(self.get_template_args(template))
elif isinstance(template, list):
for element in template:
@@ -220,18 +230,17 @@ class ActionModule(ActionBase):
old_vars = self._templar.available_variables
default_environment = {}
if trust_as_template is None:
for key in (
"newline_sequence",
"variable_start_string",
"variable_end_string",
"block_start_string",
"block_end_string",
"trim_blocks",
"lstrip_blocks",
):
if hasattr(self._templar.environment, key):
default_environment[key] = getattr(self._templar.environment, key)
for key in (
"newline_sequence",
"variable_start_string",
"variable_end_string",
"block_start_string",
"block_end_string",
"trim_blocks",
"lstrip_blocks",
):
if hasattr(self._templar.environment, key):
default_environment[key] = getattr(self._templar.environment, key)
for template_item in template_params:
# We need to convert unescaped sequences to proper escaped sequences for Jinja2
newline_sequence = template_item["newline_sequence"]
@@ -248,35 +257,26 @@ class ActionModule(ActionBase):
with self.get_template_data(template_item["path"]) as template_data:
# add ansible 'template' vars
temp_vars = copy.deepcopy(task_vars)
overrides = {}
for key, value in template_item.items():
for key, value in iteritems(template_item):
if hasattr(self._templar.environment, key):
if value is not None:
overrides[key] = value
if trust_as_template is None:
setattr(self._templar.environment, key, value)
elif trust_as_template is None:
setattr(self._templar.environment, key, value)
else:
setattr(
self._templar.environment,
key,
default_environment.get(key),
)
self._templar.available_variables = temp_vars
if trust_as_template:
template_data = trust_as_template(template_data)
result = self._templar.template(
template_data,
preserve_trailing_newlines=True,
escape_backslashes=False,
overrides=overrides,
)
result = self._templar.do_template(
template_data,
preserve_trailing_newlines=True,
escape_backslashes=False,
)
if omit_value is not None:
result_template.extend(RemoveOmit(result, omit_value).output())
else:
result = self._templar.do_template(
template_data,
preserve_trailing_newlines=True,
escape_backslashes=False,
)
result_template.extend(_from_yaml_to_definition(result))
result_template.append(result)
self._templar.available_variables = old_vars
resource_definition = self._task.args.get("definition", None)
if not resource_definition:
@@ -306,7 +306,7 @@ class ActionModule(ActionBase):
)
def get_kubeconfig(self, kubeconfig, remote_transport, new_module_args):
if isinstance(kubeconfig, str):
if isinstance(kubeconfig, string_types):
# find the kubeconfig in the expected search path
if not remote_transport:
# kubeconfig is local
@@ -384,15 +384,10 @@ class ActionModule(ActionBase):
template = self._task.args.get("template", None)
if template:
self.load_template(template, new_module_args, task_vars)
# If template rendered to empty definition, return early with no changes
if not new_module_args.get("definition"):
result["changed"] = False
return self._ensure_invocation(result)
local_path = self._task.args.get("local_path")
state = self._task.args.get("state", None)
is_local_pod_upload = local_path and state == "to_pod" and not remote_transport
if is_local_pod_upload:
if local_path and state == "to_pod" and not remote_transport:
new_module_args["local_path"] = self.get_file_realpath(local_path)
# Execute the k8s_* module.
+5 -87
View File
@@ -181,95 +181,16 @@ DOCUMENTATION = r"""
aliases: [ kubectl_verify_ssl ]
"""
EXAMPLES = r"""
- name: Run a command in a pod using local kubectl with kubeconfig file ~/.kube/config
hosts: localhost
gather_facts: no
vars:
ansible_connection: kubernetes.core.kubectl
ansible_kubectl_namespace: my-namespace
ansible_kubectl_pod: my-pod
ansible_kubectl_container: my-container
tasks:
# be aware that the command is executed as the user that started the container
# and requires python to be installed in the image
- name: Run a command in a pod
ansible.builtin.command: echo "Hello, World!"
changed_when: false
- name: Run a command in a pod using local kubectl with inventory variables
# Example inventory:
# k8s:
# hosts:
# foo.example.com:
# ansible_connection: kubernetes.core.kubectl
# ansible_kubectl_kubeconfig: /root/.kube/foo.example.com.config
# ansible_kubectl_pod: my-foo-pod
# ansible_kubectl_container: my-foo-container
# ansible_kubectl_namespace: my-foo-namespace
# bar.example.com:
# ansible_connection: kubernetes.core.kubectl
# ansible_kubectl_kubeconfig: /root/.kube/bar.example.com.config
# ansible_kubectl_pod: my-bar-pod
# ansible_kubectl_container: my-bar-container
# ansible_kubectl_namespace: my-bar-namespace
hosts: k8s
gather_facts: no
tasks:
# be aware that the command is executed as the user that started the container
# and requires python to be installed in the image
- name: Run a command in a pod
ansible.builtin.command: echo "Hello, World!"
changed_when: false
- name: Run a command in a pod using dynamic inventory
hosts: localhost
gather_facts: no
vars:
kubeconfig: /root/.kube/config
namespace: my-namespace
my_app: my-app
tasks:
- name: Get My App pod info based on label
kubernetes.core.k8s_info:
kubeconfig: "{{ kubeconfig }}"
namespace: "{{ namespace }}"
kind: Pod
label_selectors: app.kubernetes.io/name = "{{ my_app }}"
register: my_app_pod
- name: Get My App pod name
ansible.builtin.set_fact:
my_app_pod_name: "{{ my_app_pod.resources[0].metadata.name }}"
- name: Add My App pod to inventory
ansible.builtin.add_host:
name: "{{ my_app_pod_name }}"
ansible_connection: kubernetes.core.kubectl
ansible_kubectl_kubeconfig: "{{ kubeconfig }}"
ansible_kubectl_pod: "{{ my_app_pod_name }}"
ansible_kubectl_namespace: "{{ namespace }}"
- name: Run a command in My App pod
# be aware that the command is executed as the user that started the container
# and requires python to be installed in the image
ansible.builtin.command: echo "Hello, World!"
changed_when: false
delegate_to: "{{ my_app_pod_name }}"
"""
import json
import os
import os.path
import shutil
import subprocess
import tempfile
from shlex import quote as shlex_quote
from ansible.errors import AnsibleError, AnsibleFileNotFound
from ansible.module_utils.common.text.converters import to_bytes
from ansible.module_utils.parsing.convert_bool import boolean
from ansible.module_utils._text import to_bytes
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
@@ -328,12 +249,9 @@ class Connection(ConnectionBase):
# Build command options based on doc string
doc_yaml = AnsibleLoader(self.documentation).get_single_data()
for key in doc_yaml.get("options"):
if key == "validate_certs" and self.get_option(key) != "":
# Translate validate_certs to --insecure-skip-tls-verify flag
# validate_certs=True means verify certs (don't skip verification)
# validate_certs=False means don't verify certs (skip verification)
validate_certs_value = boolean(self.get_option(key), strict=False)
skip_verify_ssl = not validate_certs_value
if key.endswith("verify_ssl") and self.get_option(key) != "":
# Translate verify_ssl to skip_verify_ssl, and output as string
skip_verify_ssl = not self.get_option(key)
local_cmd.append(
"{0}={1}".format(
self.connection_options[key], str(skip_verify_ssl).lower()
+476
View File
@@ -0,0 +1,476 @@
# Copyright (c) 2018 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = """
name: k8s
author:
- Chris Houseknecht (@chouseknecht)
- Fabian von Feilitzsch (@fabianvf)
short_description: Kubernetes (K8s) inventory source
description:
- Fetch containers and services for one or more clusters.
- Groups by cluster name, namespace, namespace_services, namespace_pods, and labels.
- Uses the kubectl connection plugin to access the Kubernetes cluster.
- Uses k8s.(yml|yaml) YAML configuration file to set parameter values.
deprecated:
removed_in: 5.0.0
why: |
As discussed in U(https://github.com/ansible-collections/kubernetes.core/issues/31), we decided to
remove the k8s inventory plugin in release 5.0.0.
alternative: "Use M(kubernetes.core.k8s_info) and M(ansible.builtin.add_host) instead."
options:
plugin:
description: token that ensures this is a source file for the 'k8s' plugin.
required: True
choices: ['kubernetes.core.k8s', 'k8s', 'community.kubernetes.k8s']
connections:
description:
- Optional list of cluster connection settings. If no connections are provided, the default
I(~/.kube/config) and active context will be used, and objects will be returned for all namespaces
the active user is authorized to access.
suboptions:
name:
description:
- Optional name to assign to the cluster. If not provided, a name is constructed from the server
and port.
kubeconfig:
description:
- Path to an existing Kubernetes config file. If not provided, and no other connection
options are provided, the Kubernetes client will attempt to load the default
configuration file from I(~/.kube/config). Can also be specified via K8S_AUTH_KUBECONFIG
environment variable.
context:
description:
- The name of a context found in the config file. Can also be specified via K8S_AUTH_CONTEXT environment
variable.
host:
description:
- Provide a URL for accessing the API. Can also be specified via K8S_AUTH_HOST environment variable.
api_key:
description:
- Token used to authenticate with the API. Can also be specified via K8S_AUTH_API_KEY environment
variable.
username:
description:
- Provide a username for authenticating with the API. Can also be specified via K8S_AUTH_USERNAME
environment variable.
password:
description:
- Provide a password for authenticating with the API. Can also be specified via K8S_AUTH_PASSWORD
environment variable.
client_cert:
description:
- Path to a certificate used to authenticate with the API. Can also be specified via K8S_AUTH_CERT_FILE
environment variable.
aliases: [ cert_file ]
client_key:
description:
- Path to a key file used to authenticate with the API. Can also be specified via K8S_AUTH_KEY_FILE
environment variable.
aliases: [ key_file ]
ca_cert:
description:
- Path to a CA certificate used to authenticate with the API. Can also be specified via
K8S_AUTH_SSL_CA_CERT environment variable.
aliases: [ ssl_ca_cert ]
validate_certs:
description:
- "Whether or not to verify the API server's SSL certificates. Can also be specified via
K8S_AUTH_VERIFY_SSL environment variable."
type: bool
aliases: [ verify_ssl ]
namespaces:
description:
- List of namespaces. If not specified, will fetch all containers for all namespaces user is authorized
to access.
requirements:
- "python >= 3.9"
- "kubernetes >= 24.2.0"
- "PyYAML >= 3.11"
"""
EXAMPLES = r"""
# File must be named k8s.yaml or k8s.yml
- name: Authenticate with token, and return all pods and services for all namespaces
plugin: kubernetes.core.k8s
connections:
- host: https://192.168.64.4:8443
api_key: xxxxxxxxxxxxxxxx
validate_certs: false
- name: Use default config (~/.kube/config) file and active context, and return objects for a specific namespace
plugin: kubernetes.core.k8s
connections:
- namespaces:
- testing
- name: Use a custom config file, and a specific context.
plugin: kubernetes.core.k8s
connections:
- kubeconfig: /path/to/config
context: 'awx/192-168-64-4:8443/developer'
"""
import json
from ansible.errors import AnsibleError
from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable, Constructable
try:
from kubernetes.dynamic.exceptions import DynamicApiError
HAS_K8S_MODULE_HELPER = True
k8s_import_exception = None
except ImportError as e:
HAS_K8S_MODULE_HELPER = False
k8s_import_exception = e
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
get_api_client,
)
def format_dynamic_api_exc(exc):
if exc.body:
if exc.headers and exc.headers.get("Content-Type") == "application/json":
message = json.loads(exc.body).get("message")
if message:
return message
return exc.body
else:
return "%s Reason: %s" % (exc.status, exc.reason)
class K8sInventoryException(Exception):
pass
class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
NAME = "kubernetes.core.k8s"
connection_plugin = "kubernetes.core.kubectl"
transport = "kubectl"
def parse(self, inventory, loader, path, cache=True):
super(InventoryModule, self).parse(inventory, loader, path)
self.display.deprecated(
"The 'k8s' inventory plugin has been deprecated and will be removed in release 5.0.0",
version="5.0.0",
collection_name="kubernetes.core",
)
cache_key = self._get_cache_prefix(path)
config_data = self._read_config_data(path)
self.setup(config_data, cache, cache_key)
def setup(self, config_data, cache, cache_key):
connections = config_data.get("connections")
if not HAS_K8S_MODULE_HELPER:
raise K8sInventoryException(
"This module requires the Kubernetes Python client. Try `pip install kubernetes`. Detail: {0}".format(
k8s_import_exception
)
)
source_data = None
if cache and cache_key in self._cache:
try:
source_data = self._cache[cache_key]
except KeyError:
pass
if not source_data:
self.fetch_objects(connections)
def fetch_objects(self, connections):
if connections:
if not isinstance(connections, list):
raise K8sInventoryException("Expecting connections to be a list.")
for connection in connections:
if not isinstance(connection, dict):
raise K8sInventoryException(
"Expecting connection to be a dictionary."
)
client = get_api_client(**connection)
name = connection.get(
"name", self.get_default_host_name(client.configuration.host)
)
if connection.get("namespaces"):
namespaces = connection["namespaces"]
else:
namespaces = self.get_available_namespaces(client)
for namespace in namespaces:
self.get_pods_for_namespace(client, name, namespace)
self.get_services_for_namespace(client, name, namespace)
else:
client = get_api_client()
name = self.get_default_host_name(client.configuration.host)
namespaces = self.get_available_namespaces(client)
for namespace in namespaces:
self.get_pods_for_namespace(client, name, namespace)
self.get_services_for_namespace(client, name, namespace)
@staticmethod
def get_default_host_name(host):
return (
host.replace("https://", "")
.replace("http://", "")
.replace(".", "-")
.replace(":", "_")
)
def get_available_namespaces(self, client):
v1_namespace = client.resources.get(api_version="v1", kind="Namespace")
try:
obj = v1_namespace.get()
except DynamicApiError as exc:
self.display.debug(exc)
raise K8sInventoryException(
"Error fetching Namespace list: %s" % format_dynamic_api_exc(exc)
)
return [namespace.metadata.name for namespace in obj.items]
def get_pods_for_namespace(self, client, name, namespace):
v1_pod = client.resources.get(api_version="v1", kind="Pod")
try:
obj = v1_pod.get(namespace=namespace)
except DynamicApiError as exc:
self.display.debug(exc)
raise K8sInventoryException(
"Error fetching Pod list: %s" % format_dynamic_api_exc(exc)
)
namespace_group = "namespace_{0}".format(namespace)
namespace_pods_group = "{0}_pods".format(namespace_group)
self.inventory.add_group(name)
self.inventory.add_group(namespace_group)
self.inventory.add_child(name, namespace_group)
self.inventory.add_group(namespace_pods_group)
self.inventory.add_child(namespace_group, namespace_pods_group)
for pod in obj.items:
pod_name = pod.metadata.name
pod_groups = []
pod_annotations = (
{} if not pod.metadata.annotations else dict(pod.metadata.annotations)
)
if pod.metadata.labels:
# create a group for each label_value
for key, value in pod.metadata.labels:
group_name = "label_{0}_{1}".format(key, value)
if group_name not in pod_groups:
pod_groups.append(group_name)
self.inventory.add_group(group_name)
pod_labels = dict(pod.metadata.labels)
else:
pod_labels = {}
if not pod.status.containerStatuses:
continue
for container in pod.status.containerStatuses:
# add each pod_container to the namespace group, and to each label_value group
container_name = "{0}_{1}".format(pod.metadata.name, container.name)
self.inventory.add_host(container_name)
self.inventory.add_child(namespace_pods_group, container_name)
if pod_groups:
for group in pod_groups:
self.inventory.add_child(group, container_name)
# Add hostvars
self.inventory.set_variable(container_name, "object_type", "pod")
self.inventory.set_variable(container_name, "labels", pod_labels)
self.inventory.set_variable(
container_name, "annotations", pod_annotations
)
self.inventory.set_variable(
container_name, "cluster_name", pod.metadata.clusterName
)
self.inventory.set_variable(
container_name, "pod_node_name", pod.spec.nodeName
)
self.inventory.set_variable(container_name, "pod_name", pod.spec.name)
self.inventory.set_variable(
container_name, "pod_host_ip", pod.status.hostIP
)
self.inventory.set_variable(
container_name, "pod_phase", pod.status.phase
)
self.inventory.set_variable(container_name, "pod_ip", pod.status.podIP)
self.inventory.set_variable(
container_name, "pod_self_link", pod.metadata.selfLink
)
self.inventory.set_variable(
container_name, "pod_resource_version", pod.metadata.resourceVersion
)
self.inventory.set_variable(container_name, "pod_uid", pod.metadata.uid)
self.inventory.set_variable(
container_name, "container_name", container.image
)
self.inventory.set_variable(
container_name, "container_image", container.image
)
if container.state.running:
self.inventory.set_variable(
container_name, "container_state", "Running"
)
if container.state.terminated:
self.inventory.set_variable(
container_name, "container_state", "Terminated"
)
if container.state.waiting:
self.inventory.set_variable(
container_name, "container_state", "Waiting"
)
self.inventory.set_variable(
container_name, "container_ready", container.ready
)
self.inventory.set_variable(
container_name, "ansible_remote_tmp", "/tmp/"
)
self.inventory.set_variable(
container_name, "ansible_connection", self.connection_plugin
)
self.inventory.set_variable(
container_name, "ansible_{0}_pod".format(self.transport), pod_name
)
self.inventory.set_variable(
container_name,
"ansible_{0}_container".format(self.transport),
container.name,
)
self.inventory.set_variable(
container_name,
"ansible_{0}_namespace".format(self.transport),
namespace,
)
def get_services_for_namespace(self, client, name, namespace):
v1_service = client.resources.get(api_version="v1", kind="Service")
try:
obj = v1_service.get(namespace=namespace)
except DynamicApiError as exc:
self.display.debug(exc)
raise K8sInventoryException(
"Error fetching Service list: %s" % format_dynamic_api_exc(exc)
)
namespace_group = "namespace_{0}".format(namespace)
namespace_services_group = "{0}_services".format(namespace_group)
self.inventory.add_group(name)
self.inventory.add_group(namespace_group)
self.inventory.add_child(name, namespace_group)
self.inventory.add_group(namespace_services_group)
self.inventory.add_child(namespace_group, namespace_services_group)
for service in obj.items:
service_name = service.metadata.name
service_labels = (
{} if not service.metadata.labels else dict(service.metadata.labels)
)
service_annotations = (
{}
if not service.metadata.annotations
else dict(service.metadata.annotations)
)
self.inventory.add_host(service_name)
if service.metadata.labels:
# create a group for each label_value
for key, value in service.metadata.labels:
group_name = "label_{0}_{1}".format(key, value)
self.inventory.add_group(group_name)
self.inventory.add_child(group_name, service_name)
try:
self.inventory.add_child(namespace_services_group, service_name)
except AnsibleError:
raise
ports = [
{
"name": port.name,
"port": port.port,
"protocol": port.protocol,
"targetPort": port.targetPort,
"nodePort": port.nodePort,
}
for port in service.spec.ports or []
]
# add hostvars
self.inventory.set_variable(service_name, "object_type", "service")
self.inventory.set_variable(service_name, "labels", service_labels)
self.inventory.set_variable(
service_name, "annotations", service_annotations
)
self.inventory.set_variable(
service_name, "cluster_name", service.metadata.clusterName
)
self.inventory.set_variable(service_name, "ports", ports)
self.inventory.set_variable(service_name, "type", service.spec.type)
self.inventory.set_variable(
service_name, "self_link", service.metadata.selfLink
)
self.inventory.set_variable(
service_name, "resource_version", service.metadata.resourceVersion
)
self.inventory.set_variable(service_name, "uid", service.metadata.uid)
if service.spec.externalTrafficPolicy:
self.inventory.set_variable(
service_name,
"external_traffic_policy",
service.spec.externalTrafficPolicy,
)
if service.spec.externalIPs:
self.inventory.set_variable(
service_name, "external_ips", service.spec.externalIPs
)
if service.spec.externalName:
self.inventory.set_variable(
service_name, "external_name", service.spec.externalName
)
if service.spec.healthCheckNodePort:
self.inventory.set_variable(
service_name,
"health_check_node_port",
service.spec.healthCheckNodePort,
)
if service.spec.loadBalancerIP:
self.inventory.set_variable(
service_name, "load_balancer_ip", service.spec.loadBalancerIP
)
if service.spec.selector:
self.inventory.set_variable(
service_name, "selector", dict(service.spec.selector)
)
if (
hasattr(service.status.loadBalancer, "ingress")
and service.status.loadBalancer.ingress
):
load_balancer = [
{"hostname": ingress.hostname, "ip": ingress.ip}
for ingress in service.status.loadBalancer.ingress
]
self.inventory.set_variable(
service_name, "load_balancer", load_balancer
)
+3 -69
View File
@@ -86,48 +86,14 @@ DOCUMENTATION = """
description:
- Provide a username for authenticating with the API. Can also be specified via K8S_AUTH_USERNAME environment
variable.
no_proxy:
description:
- The comma separated list of hosts/domains/IP/CIDR that shouldn't go through proxy.
Can also be specified via K8S_AUTH_NO_PROXY environment variable.
- Please note that this module does not pick up typical proxy settings from the environment (e.g. NO_PROXY).
- This feature requires kubernetes>=19.15.0.
When kubernetes library is less than 19.15.0, it fails even if no_proxy is set correctly.
type: str
password:
description:
- Provide a password for authenticating with the API. Can also be specified via K8S_AUTH_PASSWORD environment
variable.
proxy:
description:
- The URL of an HTTP proxy to use for the connection. Can also be specified via K8S_AUTH_PROXY environment variable.
- Please note that this module does not pick up typical proxy settings from the environment (e.g. HTTP_PROXY).
type: str
proxy_headers:
description:
- The Header used for the HTTP proxy.
- Documentation can be found here
U(https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html?highlight=proxy_headers#urllib3.util.make_headers).
type: dict
suboptions:
proxy_basic_auth:
type: str
description:
- Colon-separated username:password for proxy basic authentication header.
- Can also be specified via K8S_AUTH_PROXY_HEADERS_PROXY_BASIC_AUTH environment.
basic_auth:
type: str
description:
- Colon-separated username:password for basic authentication header.
- Can also be specified via K8S_AUTH_PROXY_HEADERS_BASIC_AUTH environment.
user_agent:
type: str
description:
- String representing the user-agent you want, such as foo/1.0.
- Can also be specified via K8S_AUTH_PROXY_HEADERS_USER_AGENT environment.
client_cert:
description:
- Path to a certificate used to authenticate with the API. Can also be specified via K8S_AUTH_CERT_FILE environment
- Path to a certificate used to authenticate with the API. Can also be specified via K8S_AUTH_CERT_FILE
environment
variable.
aliases: [ cert_file ]
client_key:
@@ -209,60 +175,28 @@ RETURN = """
"""
import os
from collections.abc import KeysView
from ansible.errors import AnsibleError
from ansible.module_utils.ansible_release import __version__ as ansible_version
from ansible.module_utils.common._collections_compat import KeysView
from ansible.module_utils.common.validation import check_type_bool
from ansible.utils.display import Display
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
get_api_client,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.resource import (
create_definitions,
)
from ansible_collections.kubernetes.core.plugins.module_utils.version import (
LooseVersion,
)
display = Display()
# cloud.common declares requires_ansible '>=2.15.0,<2.19'. On newer ansible-core the
# import still succeeds, so the version has to be checked explicitly: relying on
# ImportError alone lets turbo mode fail later with an unrelated traceback.
TURBO_UNSUPPORTED_CORE = "2.19.0"
try:
enable_turbo_mode = check_type_bool(os.environ.get("ENABLE_TURBO_MODE"))
except TypeError:
enable_turbo_mode = False
if enable_turbo_mode:
display.deprecated(
"ENABLE_TURBO_MODE is deprecated, as it relies on the cloud.common "
"collection which is being retired. Setting this environment "
"variable will have no effect once support is removed.",
version="8.0.0",
collection_name="kubernetes.core",
)
if LooseVersion(ansible_version) >= LooseVersion(TURBO_UNSUPPORTED_CORE):
display.warning(
"ENABLE_TURBO_MODE is ignored on ansible-core %s: Ansible Turbo mode requires "
"the cloud.common collection, which supports ansible-core < %s only. "
"Continuing without Turbo mode." % (ansible_version, TURBO_UNSUPPORTED_CORE)
)
enable_turbo_mode = False
if enable_turbo_mode:
try:
from ansible_collections.cloud.common.plugins.plugin_utils.turbo.lookup import (
TurboLookupBase as LookupBase,
)
except ImportError:
display.warning(
"ENABLE_TURBO_MODE is set but the cloud.common collection is not installed. "
"Continuing without Turbo mode."
)
from ansible.plugins.lookup import LookupBase # noqa: F401
else:
from ansible.plugins.lookup import LookupBase # noqa: F401
+8 -51
View File
@@ -34,13 +34,6 @@ DOCUMENTATION = """
description:
- Enable the helm chart inflation generator
default: "False"
environment:
description:
- The environment variables to pass to the kustomize or kubectl command.
- This can be a dictionary or a string in the format key=value, multiple pairs separated by space.
type: raw
default: {}
version_added: 6.2.0
requirements:
- "python >= 3.6"
@@ -62,14 +55,6 @@ EXAMPLES = """
- name: Create kubernetes resources for lookup output with `--enable-helm` set
kubernetes.core.k8s:
definition: "{{ lookup('kubernetes.core.kustomize', dir='/path/to/kustomization', enable_helm=True) }}"
- name: Create kubernetes resources for lookup output with environment variables in string format
kubernetes.core.k8s:
definition: "{{ lookup('kubernetes.core.kustomize', binary_path='/path/to/kubectl', environment='HTTP_PROXY=http://proxy.example.com:3128') }}"
- name: Create kubernetes resources for lookup output with environment variables in dict format
kubernetes.core.k8s:
definition: "{{ lookup('kubernetes.core.kustomize', binary_path='/path/to/kubectl', environment={'HTTP_PROXY': 'http://proxy.example.com:3128'}) }}"
"""
RETURN = """
@@ -87,7 +72,6 @@ RETURN = """
key1: val1
"""
import os
import subprocess
from ansible.errors import AnsibleLookupError
@@ -108,12 +92,9 @@ def get_binary_from_path(name, opt_dirs=None):
return None
def run_command(command, environ=None):
cmd = subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environ
)
stdout, stderr = cmd.communicate()
return cmd.returncode, stdout, stderr
def run_command(command):
cmd = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return cmd.communicate()
class LookupModule(LookupBase):
@@ -125,7 +106,6 @@ class LookupModule(LookupBase):
binary_path=None,
opt_dirs=None,
enable_helm=False,
environment=None,
**kwargs
):
executable_path = binary_path
@@ -160,32 +140,9 @@ class LookupModule(LookupBase):
if enable_helm:
command += ["--enable-helm"]
environ = None
if environment:
environ = os.environ.copy()
if isinstance(environment, str):
if not all(env.count("=") == 1 for env in environment.split(" ")):
raise AnsibleLookupError(
"environment should be dict or string in the format key=value, multiple pairs separated by space"
)
for env in environment.split(" "):
key, value = env.split("=")
environ[key] = value
if isinstance(environment, dict):
environ.update(environment)
(ret, out, err) = run_command(command, environ=environ)
if ret != 0:
if err:
raise AnsibleLookupError(
"kustomize command failed. exit code: {0}, error: {1}".format(
ret, err.decode("utf-8")
)
)
else:
raise AnsibleLookupError(
"kustomize command failed with unknown error. exit code: {0}".format(
ret
)
)
(out, err) = run_command(command)
if err:
raise AnsibleLookupError(
"kustomize command failed with: {0}".format(err.decode("utf-8"))
)
return [out.decode("utf-8")]
-30
View File
@@ -5,39 +5,13 @@ __metaclass__ = type
import os
from ansible.module_utils.ansible_release import __version__ as ansible_version
from ansible.module_utils.common.validation import check_type_bool
from ansible.module_utils.common.warnings import deprecate, warn
from ansible_collections.kubernetes.core.plugins.module_utils.version import (
LooseVersion,
)
# cloud.common declares requires_ansible '>=2.15.0,<2.19'. On newer ansible-core the
# import still succeeds, so the version has to be checked explicitly: relying on
# ImportError alone lets turbo mode fail later with an unrelated traceback.
TURBO_UNSUPPORTED_CORE = "2.19.0"
try:
enable_turbo_mode = check_type_bool(os.environ.get("ENABLE_TURBO_MODE"))
except TypeError:
enable_turbo_mode = False
if enable_turbo_mode:
deprecate(
"ENABLE_TURBO_MODE is deprecated, as it relies on the cloud.common collection "
"which is being retired. Setting this environment variable will have no effect "
"once support is removed.",
version="8.0.0",
collection_name="kubernetes.core",
)
if LooseVersion(ansible_version) >= LooseVersion(TURBO_UNSUPPORTED_CORE):
warn(
"ENABLE_TURBO_MODE is ignored on ansible-core %s: Ansible Turbo mode requires "
"the cloud.common collection, which supports ansible-core < %s only. "
"Continuing without Turbo mode." % (ansible_version, TURBO_UNSUPPORTED_CORE)
)
enable_turbo_mode = False
if enable_turbo_mode:
try:
from ansible_collections.cloud.common.plugins.module_utils.turbo.module import ( # noqa: F401
@@ -46,10 +20,6 @@ if enable_turbo_mode:
AnsibleModule.collection_name = "kubernetes.core"
except ImportError:
warn(
"ENABLE_TURBO_MODE is set but the cloud.common collection is not installed. "
"Continuing without Turbo mode."
)
from ansible.module_utils.basic import AnsibleModule # noqa: F401
else:
from ansible.module_utils.basic import AnsibleModule # noqa: F401
+3 -66
View File
@@ -1,64 +1,16 @@
from __future__ import absolute_import, division, print_function
from ansible.module_utils.six import string_types
__metaclass__ = type
import warnings
def list_dict_str(value):
if isinstance(value, (list, dict, str)):
if isinstance(value, (list, dict, string_types)):
return value
raise TypeError
def extract_sensitive_values_from_kubeconfig(kubeconfig_data):
"""
Extract only sensitive string values from kubeconfig data for no_log_values.
:arg kubeconfig_data: Dictionary containing kubeconfig data
:returns: Set of sensitive string values to be added to no_log_values
"""
values = set()
sensitive_fields = {
"token",
"password",
"secret",
"client-key-data",
"client-certificate-data",
"certificate-authority-data",
"api_key",
"access-token",
"refresh-token",
}
# Check API version and warn if not v1
if isinstance(kubeconfig_data, dict):
api_version = kubeconfig_data.get("apiVersion", "v1")
if api_version != "v1":
warnings.warn(
f"Kubeconfig API version '{api_version}' is not 'v1'. "
f"Sensitive field redaction is only guaranteed for API version 'v1'. "
f"Some sensitive data may not be properly redacted from the logs.",
UserWarning,
)
def _extract_recursive(data, current_path=""):
if isinstance(data, dict):
for key, value in data.items():
path = f"{current_path}.{key}" if current_path else key
if key in sensitive_fields:
if isinstance(value, str):
values.add(value)
else:
_extract_recursive(value, path)
elif isinstance(data, list):
for i, item in enumerate(data):
_extract_recursive(item, f"{current_path}[{i}]")
_extract_recursive(kubeconfig_data)
return values
AUTH_PROXY_HEADERS_SPEC = dict(
proxy_basic_auth=dict(type="str", no_log=True),
basic_auth=dict(type="str", no_log=True),
@@ -144,18 +96,3 @@ DELETE_OPTS_ARG_SPEC = {
"options": {"resourceVersion": {"type": "str"}, "uid": {"type": "str"}},
},
}
METADATA_ONLY_HEADERS_SPEC = {
"accept": {"type": "str"},
}
METADATA_ONLY_HEADER_VALUES = {
"partial_object": (
"application/json;as=PartialObjectMetadata;g=meta.k8s.io;v=v1,"
"application/json;q=0.9"
),
"partial_object_list": (
"application/json;as=PartialObjectMetadataList;g=meta.k8s.io;v=v1,"
"application/json;q=0.9"
),
}
+1 -1
View File
@@ -23,7 +23,7 @@ import base64
import os
from tempfile import NamedTemporaryFile
from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.module_utils.urls import Request
try:
+63 -202
View File
@@ -18,14 +18,12 @@ from __future__ import absolute_import, division, print_function
__metaclass__ = type
import os
import shlex
import tarfile
import time
from abc import ABCMeta, abstractmethod
from select import select
from tempfile import NamedTemporaryFile, TemporaryFile
from ansible.module_utils.common.text.converters import to_native
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.k8s.exceptions import (
@@ -98,7 +96,7 @@ class K8SCopy(metaclass=ABCMeta):
return error, stdout, stderr
except Exception as e:
self.module.fail_json(
msg="Error while running/parsing from pod {0}/{1} command='{2}' : {3}".format(
msg="Error while running/parsing from pod {1}/{2} command='{0}' : {3}".format(
self.namespace, self.name, cmd, to_native(e)
)
)
@@ -280,15 +278,11 @@ class K8SCopyFromPod(K8SCopy):
def run(self):
self.files_to_copy = self.list_remote_files()
if self.files_to_copy == []:
# Using warn method instead of passing warnings to exit_json as it is
# deprecated in ansible-core>=2.19.0
self._module.warn(
"No file found from directory '{0}' into remote Pod.".format(
self.remote_path
)
)
self.module.exit_json(
changed=False,
warning="No file found from directory '{0}' into remote Pod.".format(
self.remote_path
),
)
self.copy()
@@ -298,156 +292,14 @@ class K8SCopyToPod(K8SCopy):
Copy files/directory from local filesystem into remote Pod
"""
# Size of the chunks the tar archive is written to stdin with.
CHUNK_SIZE = 1024 * 1024
SHELL = "/bin/sh"
def __init__(self, module, client):
super(K8SCopyToPod, self).__init__(module, client)
self.files_to_copy = list()
self.named_temp_file = None
self.copy_timeout = module.params.get("copy_timeout")
def close_temp_file(self):
if self.named_temp_file:
self.named_temp_file.close()
def _fail(self, response, msg, stderr=(), **kwargs):
"""Fail, keeping whatever the remote already wrote to stderr.
An early close or a stall is usually the symptom, not the cause: tar
has typically said why on stderr first.
"""
if stderr:
msg = "{0}: {1}".format(msg, "".join(stderr))
response.close()
self.close_temp_file()
self.module.fail_json(
msg="Failed to copy local file/directory into Pod: {0}".format(msg),
**kwargs,
)
def tar_command(self, dest_file):
if self.no_preserve:
command = [
"tar",
"--no-same-permissions",
"--no-same-owner",
"-xmf",
"-",
]
else:
command = ["tar", "-xmf", "-"]
if dest_file.startswith("/"):
command.extend(["-C", "/"])
return command
def can_bound_stream(self):
"""Whether the container can run ``sh -c 'head -c ...'``."""
error, _out, _err = self._run_from_pod(
cmd=[self.SHELL, "-c", "command -v head"]
)
return (error or {}).get("status") == "Success"
def remote_command(self, dest_file, archive_size):
"""Build the command that extracts the archive inside the container.
The websocket exec protocol the kubernetes client speaks (v4) cannot
half-close stdin, so the only EOF the remote process can get is the
connection going away. Relying on that races with tar finishing and
truncates the file (issue #776), and tar cannot be relied on to stop at
the end-of-archive marker either -- busybox tar blocks for EOF.
Piping through ``head -c`` bounds the stream at the exact archive size,
so tar sees a clean EOF, exits on its own, and the API server reports
its exit status on the error channel. Only where the container has no
shell do we fall back to feeding tar directly, which cannot confirm
that the copy completed.
"""
command = self.tar_command(dest_file)
if not self.can_bound_stream():
self.module.warn(
"Container has no '{0}' with 'head', falling back to writing the"
" archive straight to tar. The module cannot confirm the copy"
" completed; verify the file after copying.".format(self.SHELL)
)
return command, False
return [
self.SHELL,
"-c",
"head -c {0} | {1}".format(
archive_size, " ".join(shlex.quote(arg) for arg in command)
),
], True
def _stream_tar_to_pod(self, response, tar_buffer, wait_for_exit):
"""Feed the archive to the remote extractor and wait for it to finish.
Writing the last chunk only hands the bytes to the local socket; they
still have to cross the API server and reach the container. Closing the
connection at that point kills the extractor mid-write and silently
truncates the file, which is what issue #776 reports.
"""
stdout, stderr = [], []
def drain(timeout):
response.update(timeout=timeout)
if response.peek_stdout():
stdout.append(response.read_stdout().rstrip("\n"))
if response.peek_stderr():
stderr.append(response.read_stderr().rstrip("\n"))
deadline = time.monotonic() + self.copy_timeout
chunk = tar_buffer.read(self.CHUNK_SIZE)
while chunk:
if not response.is_open():
self._fail(
response,
"connection to Pod {0}/{1} closed before the whole archive was"
" sent, the remote file is incomplete".format(
self.namespace, self.name
),
stderr,
)
if time.monotonic() > deadline:
self._fail(
response,
"timed out after {0}s sending the archive to Pod {1}/{2}".format(
self.copy_timeout, self.namespace, self.name
),
stderr,
)
# Non-blocking, keeps the receive buffer clear while we write.
drain(0)
response.write_stdin(chunk)
chunk = tar_buffer.read(self.CHUNK_SIZE)
if not wait_for_exit:
# No way to make the extractor exit, so no status to collect: read
# whatever it has already said and close, as the module always did.
drain(0)
response.close()
return None, stdout, stderr
# The archive is on the wire; wait for the extractor to consume it,
# exit, and have its status reported on the error channel.
while response.is_open():
if time.monotonic() > deadline:
self._fail(
response,
"timed out after {0}s waiting for tar to finish extracting on Pod"
" {1}/{2}".format(self.copy_timeout, self.namespace, self.name),
stderr,
)
drain(1)
error = yaml.safe_load(response.read_channel(ERROR_CHANNEL)) or {}
response.close()
return error, stdout, stderr
def run(self):
# remove trailing slash from destination path
dest_file = self.remote_path.rstrip("/")
@@ -480,46 +332,65 @@ class K8SCopyToPod(K8SCopy):
dest_file = os.path.join(dest_file, os.path.basename(src_file))
if not self.check_mode:
if self.no_preserve:
tar_command = [
"tar",
"--no-same-permissions",
"--no-same-owner",
"-xmf",
"-",
]
else:
tar_command = ["tar", "-xmf", "-"]
if dest_file.startswith("/"):
tar_command.extend(["-C", "/"])
response = stream(
self.api_instance.connect_get_namespaced_pod_exec,
self.name,
self.namespace,
command=tar_command,
stderr=True,
stdin=True,
stdout=True,
tty=False,
_preload_content=False,
**self.container_arg,
)
with TemporaryFile() as tar_buffer:
# Build the archive first: bounding the remote read needs its
# exact size.
with tarfile.open(fileobj=tar_buffer, mode="w") as tar:
tar.add(src_file, dest_file)
archive_size = tar_buffer.tell()
tar_buffer.seek(0)
commands = []
# push command in chunk mode
size = 1024 * 1024
while True:
data = tar_buffer.read(size)
if not data:
break
commands.append(data)
command, wait_for_exit = self.remote_command(dest_file, archive_size)
response = stream(
self.api_instance.connect_get_namespaced_pod_exec,
self.name,
self.namespace,
command=command,
stderr=True,
stdin=True,
stdout=True,
tty=False,
_preload_content=False,
**self.container_arg,
)
error, stdout, stderr = self._stream_tar_to_pod(
response, tar_buffer, wait_for_exit
)
if error is not None and error.get("status") != "Success":
self._fail(
response,
"".join(stderr) or error.get("message", "unknown error"),
command=command,
)
if error is None and stderr:
# Legacy path: no exit status to go on, so any output is fatal.
self._fail(response, "".join(stderr), command=command)
if stderr:
self.module.warn(
"tar wrote to stderr while extracting into Pod {0}/{1}: {2}".format(
self.namespace, self.name, "".join(stderr)
stderr, stdout = [], []
while response.is_open():
if response.peek_stdout():
stdout.append(response.read_stdout().rstrip("\n"))
if response.peek_stderr():
stderr.append(response.read_stderr().rstrip("\n"))
if commands:
cmd = commands.pop(0)
response.write_stdin(cmd)
else:
break
response.close()
if stderr:
self.close_temp_file()
self.module.fail_json(
command=tar_command,
msg="Failed to copy local file/directory into Pod due to: {0}".format(
"".join(stderr)
),
)
)
self.close_temp_file()
if self.content:
self.module.exit_json(
@@ -564,21 +435,11 @@ def check_pod(svc):
try:
result = svc.client.get(resource, name=name, namespace=namespace)
containers = dict(
{
c["name"]: c
for cl in ["initContainerStatuses", "containerStatuses"]
for c in result.to_dict()["status"].get(cl, [])
}
)
if container and container not in containers.keys():
containers = [
c["name"] for c in result.to_dict()["status"]["containerStatuses"]
]
if container and container not in containers:
module.fail_json(msg="Pod has no container {0}".format(container))
if (
container
and container in containers
and not bool(containers[container].get("started", False))
):
module.fail_json(msg="Pod container {0} is not started".format(container))
return containers.keys()
return containers
except Exception as exc:
_fail(exc)
+13 -106
View File
@@ -15,9 +15,7 @@ import tempfile
import traceback
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible_collections.kubernetes.core.plugins.module_utils.args_common import (
extract_sensitive_values_from_kubeconfig,
)
from ansible.module_utils.six import string_types
from ansible_collections.kubernetes.core.plugins.module_utils.version import (
LooseVersion,
)
@@ -32,53 +30,6 @@ except ImportError:
HAS_YAML = False
# Helm's registry client writes these progress messages to stdout as of helm 4.2.1
# (helm/helm#32056); earlier versions sent them to stderr. Anything that parses the
# stdout of a helm command which may pull from an OCI registry has to skip them.
# Kept verbatim from helm's pkg/registry/client.go so that a reworded message fails
# to match, and therefore fails loudly, rather than silently eating real output.
REGISTRY_PROGRESS_RE = re.compile(r"^(?:Pulled|Pushed|Digest): \S")
REGISTRY_UNDERSCORE_SUFFIX = " contains an underscore.\n"
REGISTRY_UNDERSCORE_MESSAGE = """
OCI artifact references (e.g. tags) do not support the plus sign (+). To support
storing semantic versions, Helm adopts the convention of changing plus (+) to
an underscore (_) in chart version tags when pushing to a registry and back to
a plus (+) when pulling from a registry.
"""
REGISTRY_UNDERSCORE_MESSAGE_LINES = len(REGISTRY_UNDERSCORE_MESSAGE.splitlines())
def strip_registry_progress(out):
"""
Drop OCI registry progress messages from the front of a helm command's stdout.
Helm emits 'Pulled:'/'Pushed:' and 'Digest:' lines, followed - when the
reference contains an underscore - by a free-text explanation that is not
valid YAML. Since helm 4.2.1 these land on stdout ahead of the real output,
so 'helm show chart' can no longer be parsed and 'helm template' no longer
returns only rendered manifests.
"""
lines = out.splitlines(keepends=True)
index = 0
while index < len(lines):
if REGISTRY_PROGRESS_RE.match(lines[index]):
index += 1
elif lines[index].endswith(REGISTRY_UNDERSCORE_SUFFIX):
# helm prints its registryUnderscoreMessage right after this line, led
# by a blank line. Anything else is not a message we know about.
start = index + 1
end = start + REGISTRY_UNDERSCORE_MESSAGE_LINES
if "".join(lines[start:end]) != REGISTRY_UNDERSCORE_MESSAGE:
break
index = end
else:
break
return "".join(lines[index:])
def parse_helm_plugin_list(output=None):
"""
Parse `helm plugin list`, return list of plugins
@@ -87,20 +38,16 @@ def parse_helm_plugin_list(output=None):
if not output:
return ret
parsing_grammar = None
for line in output:
if line.startswith("NAME"):
parsing_grammar = [s.strip().lower() for s in line.split("\t")]
continue
if parsing_grammar is None:
name, version, description = line.split("\t", 3)
name = name.strip()
version = version.strip()
description = description.strip()
if name == "":
continue
plugin = {
parsing_grammar[i]: v.strip()
for i, v in enumerate(line.split("\t", len(parsing_grammar)))
}
if plugin["name"] == "":
continue
ret.append(plugin)
ret.append((name, version, description))
return ret
@@ -130,6 +77,7 @@ def write_temp_kubeconfig(server, validate_certs=True, ca_cert=None, kubeconfig=
class AnsibleHelmModule(object):
"""
An Ansible module class for Kubernetes.core helm modules
"""
@@ -166,19 +114,12 @@ class AnsibleHelmModule(object):
kubeconfig_content = None
kubeconfig = self.params.get("kubeconfig")
if kubeconfig:
if isinstance(kubeconfig, str):
if isinstance(kubeconfig, string_types):
with open(os.path.expanduser(kubeconfig)) as fd:
kubeconfig_content = yaml.safe_load(fd)
elif isinstance(kubeconfig, dict):
kubeconfig_content = kubeconfig
# Redact sensitive fields from kubeconfig for logging purposes
if kubeconfig_content:
# Add original sensitive values to no_log_values to prevent them from appearing in logs
self._module.no_log_values.update(
extract_sensitive_values_from_kubeconfig(kubeconfig_content)
)
if self.params.get("ca_cert"):
ca_cert = self.params.get("ca_cert")
if LooseVersion(self.get_helm_version()) < LooseVersion("3.5.0"):
@@ -219,13 +160,11 @@ class AnsibleHelmModule(object):
self.helm_env = self._prepare_helm_environment()
return self.helm_env
def run_helm_command(self, command, fails_on_error=True, data=None):
def run_helm_command(self, command, fails_on_error=True):
if not HAS_YAML:
self.fail_json(msg=missing_required_lib("PyYAML"), exception=YAML_IMP_ERR)
rc, out, err = self.run_command(
command, environ_update=self.env_update, data=data
)
rc, out, err = self.run_command(command, environ_update=self.env_update)
if fails_on_error and rc != 0:
self.fail_json(
msg="Failure when executing Helm command. Exited {0}.\nstdout: {1}\nstderr: {2}".format(
@@ -245,46 +184,14 @@ class AnsibleHelmModule(object):
def get_helm_version(self):
command = self.get_helm_binary() + " version"
rc, out, err = self.run_command(command)
m = re.match(r'version.BuildInfo{Version:"v(.*?)",', out)
m = re.match(r'version.BuildInfo{Version:"v([0-9\.]*)",', out)
if m:
return m.group(1)
m = re.match(r'Client: &version.Version{SemVer:"v(.*?)", ', out)
m = re.match(r'Client: &version.Version{SemVer:"v([0-9\.]*)", ', out)
if m:
return m.group(1)
return None
def is_helm_v4(self):
helm_version = self.get_helm_version()
if helm_version is None:
return False
return LooseVersion(helm_version) >= LooseVersion("4.0.0")
def is_helm_version_compatible_with_helm_diff(self, helm_diff_version):
"""
Return true if the helm version is compatible with the helm diff version
Helm v4 requires helm diff v3.14.0
"""
if not helm_diff_version:
return False
if self.is_helm_v4():
return LooseVersion(helm_diff_version) >= LooseVersion("3.14.0")
return True
def validate_helm_version(self, version="3.0.0"):
"""
Validate that Helm version is >= version (default version=3.0.0).
"""
helm_version = self.get_helm_version()
if helm_version is None:
self.fail_json(msg="Unable to determine Helm version")
if LooseVersion(helm_version) < LooseVersion(version):
self.fail_json(
msg="Helm version must be >= {0}, current version is {1}".format(
version, helm_version
)
)
def get_values(self, release_name, get_all=False):
"""
Get Values from deployed release
+3 -3
View File
@@ -5,6 +5,7 @@ import hashlib
import os
from typing import Any, Dict, List, Optional
from ansible.module_utils.six import iteritems, string_types
from ansible_collections.kubernetes.core.plugins.module_utils.args_common import (
AUTH_ARG_MAP,
AUTH_ARG_SPEC,
@@ -114,7 +115,7 @@ def _load_config(auth: Dict) -> None:
"persist_config": auth.get("persist_config"),
}
if kubeconfig:
if isinstance(kubeconfig, str):
if isinstance(kubeconfig, string_types):
kubernetes.config.load_kube_config(config_file=kubeconfig, **optional_arg)
elif isinstance(kubeconfig, dict):
kubernetes.config.load_kube_config_from_dict(
@@ -162,7 +163,7 @@ def _create_configuration(auth: Dict):
except AttributeError:
configuration = kubernetes.client.Configuration()
for key, value in auth.items():
for key, value in iteritems(auth):
if key in AUTH_ARG_MAP.keys() and value is not None:
if key == "api_key":
setattr(
@@ -181,7 +182,6 @@ def _create_headers(module=None, **kwargs):
header_map = {
"impersonate_user": "Impersonate-User",
"impersonate_groups": "Impersonate-Group",
"accept": "Accept",
}
headers = {}
-12
View File
@@ -3,9 +3,6 @@ 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.args_common import (
extract_sensitive_values_from_kubeconfig,
)
from ansible_collections.kubernetes.core.plugins.module_utils.version import (
LooseVersion,
)
@@ -36,15 +33,6 @@ class AnsibleK8SModule:
self._module = self.settings["module_class"](**kwargs)
# Apply kubeconfig redaction for logging purposes
if hasattr(self._module, "params") and hasattr(self._module, "no_log_values"):
kubeconfig = self._module.params.get("kubeconfig")
if kubeconfig and isinstance(kubeconfig, dict):
# Add sensitive values to no_log_values to prevent them from appearing in logs
self._module.no_log_values.update(
extract_sensitive_values_from_kubeconfig(kubeconfig)
)
if self.settings["check_k8s"]:
self.requires("kubernetes")
self.has_at_least("kubernetes", "24.2.0", warn=True)
+3 -2
View File
@@ -4,6 +4,7 @@
import os
from typing import Dict, Iterable, List, Optional, Union, cast
from ansible.module_utils.six import string_types
from ansible.module_utils.urls import Request
try:
@@ -77,11 +78,11 @@ def create_definitions(params: Dict) -> List[ResourceDefinition]:
def from_yaml(definition: Union[str, List, Dict]) -> Iterable[Dict]:
"""Load resource definitions from a yaml definition."""
definitions: List[Dict] = []
if isinstance(definition, str):
if isinstance(definition, string_types):
definitions += yaml.safe_load_all(definition)
elif isinstance(definition, list):
for item in definition:
if isinstance(item, str):
if isinstance(item, string_types):
definitions += yaml.safe_load_all(item)
else:
definitions.append(item)
+1 -1
View File
@@ -3,7 +3,7 @@
from typing import Dict
from ansible.module_utils.common.text.converters import to_native
from ansible.module_utils._text import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
get_api_client,
)
+35 -124
View File
@@ -4,7 +4,7 @@
import copy
from json import loads
from re import compile
from typing import Any, Dict, List, Optional, Tuple, Union
from typing import Any, Dict, List, Optional, Tuple
from ansible.module_utils.common.dict_transformations import dict_merge
from ansible_collections.kubernetes.core.plugins.module_utils.hashes import (
@@ -473,7 +473,7 @@ class K8sService:
if label_selectors:
params["label_selector"] = ",".join(label_selectors)
if delete_options and not self.module.check_mode:
if delete_options:
body = {
"apiVersion": "v1",
"kind": "DeleteOptions",
@@ -498,105 +498,48 @@ def diff_objects(
if not diff:
return True, result
result["before"] = hide_fields(diff[0], hidden_fields)
result["after"] = hide_fields(diff[1], hidden_fields)
result["before"] = diff[0]
result["after"] = diff[1]
if list(result["after"].keys()) == ["metadata"] and list(
if list(result["after"].keys()) != ["metadata"] or list(
result["before"].keys()
) == ["metadata"]:
# If only metadata.generation and metadata.resourceVersion changed, ignore it
ignored_keys = set(["generation", "resourceVersion"])
) != ["metadata"]:
return False, result
if set(result["after"]["metadata"].keys()).issubset(ignored_keys) and set(
result["before"]["metadata"].keys()
).issubset(ignored_keys):
return True, result
# If only metadata.generation and metadata.resourceVersion changed, ignore it
ignored_keys = set(["generation", "resourceVersion"])
return False, result
if not set(result["after"]["metadata"].keys()).issubset(ignored_keys):
return False, result
if not set(result["before"]["metadata"].keys()).issubset(ignored_keys):
return False, result
result["before"] = hide_fields(result["before"], hidden_fields)
result["after"] = hide_fields(result["after"], hidden_fields)
return True, result
def hide_field_tree(hidden_field: str) -> List[str]:
result = []
key, rest = hide_field_split2(hidden_field)
result.append(key)
while rest:
key, rest = hide_field_split2(rest)
result.append(key)
return result
def build_hidden_field_tree(hidden_fields: List[str]) -> Dict[str, Any]:
"""Group hidden field targeting the same json key
Example:
Input: ['env[3]', 'env[0]']
Output: {'env': [0, 3]}
"""
output = {}
for hidden_field in hidden_fields:
current = output
tree = hide_field_tree(hidden_field)
for idx, key in enumerate(tree):
if current.get(key, "") is None:
break
if idx == (len(tree) - 1):
current[key] = None
elif key not in current:
current[key] = {}
current = current[key]
return output
# hide_field should be able to cope with simple or more complicated
# field definitions
# e.g. status or metadata.managedFields or
# spec.template.spec.containers[0].env[3].value or
# metadata.annotations[kubectl.kubernetes.io/last-applied-configuration]
def hide_field(
definition: Union[Dict[str, Any], List[Any]], hidden_field: Dict[str, Any]
) -> Dict[str, Any]:
def dict_contains_key(obj: Dict[str, Any], key: str) -> bool:
return key in obj
def list_contains_key(obj: List[Any], key: str) -> bool:
return int(key) < len(obj)
hidden_keys = list(hidden_field.keys())
field_contains_key = dict_contains_key
field_get_key = str
if isinstance(definition, list):
# Sort with reverse=true so that when we delete an item from the list, the order is not changed
hidden_keys = sorted(
[k for k in hidden_field.keys() if k.isdecimal()], reverse=True
)
field_contains_key = list_contains_key
field_get_key = int
for key in hidden_keys:
if field_contains_key(definition, key):
value = hidden_field.get(key)
convert_key = field_get_key(key)
if value is None:
del definition[convert_key]
else:
definition[convert_key] = hide_field(definition[convert_key], value)
if (
definition[convert_key] == dict()
or definition[convert_key] == list()
):
del definition[convert_key]
return definition
def hide_fields(
definition: Dict[str, Any], hidden_fields: Optional[List[str]]
) -> Dict[str, Any]:
def hide_fields(definition: dict, hidden_fields: Optional[list]) -> dict:
if not hidden_fields:
return definition
result = copy.deepcopy(definition)
hidden_field_tree = build_hidden_field_tree(hidden_fields)
return hide_field(result, hidden_field_tree)
for hidden_field in hidden_fields:
result = hide_field(result, hidden_field)
return result
# hide_field is not hugely sophisticated and designed to cope
# with e.g. status or metadata.managedFields rather than e.g.
# spec.template.spec.containers[0].env[3].value
def hide_field(definition: dict, hidden_field: str) -> dict:
split = hidden_field.split(".", 1)
if split[0] in definition:
if len(split) == 2:
definition[split[0]] = hide_field(definition[split[0]], split[1])
else:
del definition[split[0]]
return definition
def decode_response(resp) -> Tuple[Dict, List[str]]:
@@ -677,35 +620,3 @@ def parse_quoted_string(quoted_string: str) -> Tuple[str, str]:
raise ValueError("invalid quoted string: missing closing quote")
return "".join(result), remainder
# hide_field_split2 returns the first key in hidden_field and the rest of the hidden_field
# We expect the first key to either be in brackets, to be terminated by the start of a left
# bracket, or to be terminated by a dot.
# examples would be:
# field.another.next -> (field, another.next)
# field[key].value -> (field, [key].value)
# [key].value -> (key, value)
# [one][two] -> (one, [two])
def hide_field_split2(hidden_field: str) -> Tuple[str, str]:
lbracket = hidden_field.find("[")
rbracket = hidden_field.find("]")
dot = hidden_field.find(".")
if lbracket == 0:
# skip past right bracket and any following dot
rest = hidden_field[rbracket + 1 :] # noqa: E203
if rest and rest[0] == ".":
rest = rest[1:]
return (hidden_field[lbracket + 1 : rbracket], rest) # noqa: E203
if lbracket != -1 and (dot == -1 or lbracket < dot):
return (hidden_field[:lbracket], hidden_field[lbracket:])
split = hidden_field.split(".", 1)
if len(split) == 1:
return split[0], ""
return split
+7 -43
View File
@@ -47,23 +47,11 @@ def pod_ready(pod: ResourceInstance) -> bool:
)
def job_complete(job: ResourceInstance) -> bool:
return bool(
job.status
and job.status.conditions
and any(
condition["type"] in ("Complete", "Failed")
and boolean(condition["status"], strict=False)
for condition in job.status.conditions
)
)
def daemonset_ready(daemonset: ResourceInstance) -> bool:
return bool(
daemonset.status
and daemonset.status.desiredNumberScheduled is not None
and (daemonset.status.updatedNumberScheduled or 0)
and daemonset.status.updatedNumberScheduled
== daemonset.status.desiredNumberScheduled
and daemonset.status.numberReady == daemonset.status.desiredNumberScheduled
and daemonset.status.observedGeneration == daemonset.metadata.generation
@@ -101,18 +89,18 @@ def custom_condition(condition: Dict, resource: ResourceInstance) -> bool:
if not matches:
return False
# There should never be more than one condition of a specific type
match_condition: ResourceField = matches[0]
if match_condition.status == "Unknown":
if match_condition.status == condition["status"]:
match: ResourceField = matches[0]
if match.status == "Unknown":
if match.status == condition["status"]:
if "reason" not in condition:
return True
if condition["reason"]:
return match_condition.reason == condition["reason"]
return match.reason == condition["reason"]
return False
status = True if match_condition.status == "True" else False
status = True if match.status == "True" else False
if status == boolean(condition["status"], strict=False):
if condition.get("reason"):
return match_condition.reason == condition["reason"]
return match.reason == condition["reason"]
return True
return False
@@ -129,35 +117,11 @@ def exists(resource: Optional[ResourceInstance]) -> bool:
return bool(resource) and not empty_list(resource)
def cluster_operator_ready(resource: ResourceInstance) -> bool:
"""
Predicate to check if a single ClusterOperator is healthy.
Returns True if:
- "Available" is True
- "Degraded" is False
- "Progressing" is False
"""
if not resource:
return False
# Extract conditions from the resource's status
conditions = resource.get("status", {}).get("conditions", [])
status = {x.get("type", ""): x.get("status") for x in conditions}
return (
(status.get("Degraded") == "False")
and (status.get("Progressing") == "False")
and (status.get("Available") == "True")
)
RESOURCE_PREDICATES = {
"DaemonSet": daemonset_ready,
"Deployment": deployment_ready,
"Pod": pod_ready,
"Job": job_complete,
"StatefulSet": statefulset_ready,
"ClusterOperator": cluster_operator_ready,
}
-95
View File
@@ -1,95 +0,0 @@
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import hashlib
import os
import traceback
try:
import yaml
IMP_YAML = True
IMP_YAML_ERR = None
except ImportError:
IMP_YAML = False
IMP_YAML_ERR = traceback.format_exc()
def load_yaml_file(path):
if not path or not os.path.exists(path):
return {}
with open(path, "r") as f:
return yaml.safe_load(f) or {}
def deep_merge(base, updates):
result = base.copy()
for key, value in updates.items():
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
result[key] = deep_merge(result[key], value)
else:
result[key] = value
return result
def merge_by_name(existing, new):
merged = {}
for item in existing:
if isinstance(item, dict) and "name" in item:
merged[item["name"]] = item
for item in new:
if not isinstance(item, dict) or "name" not in item:
continue
name = item["name"]
behavior = item.get("behavior", "merge")
item_copy = {k: v for k, v in item.items() if k != "behavior"}
if name in merged:
if behavior == "keep":
continue
elif behavior == "remove":
del merged[name]
elif behavior == "replace":
merged[name] = item_copy
else:
result = {"name": name}
for key in ["cluster", "user", "context"]:
if key in merged[name] or key in item_copy:
existing_config = merged[name].get(key, {})
new_config = item_copy.get(key, {})
result[key] = deep_merge(existing_config, new_config)
for key in merged[name]:
if key not in ["name", "cluster", "user", "context"]:
result[key] = merged[name][key]
for key in item_copy:
if (
key not in ["name", "cluster", "user", "context"]
and key not in result
):
result[key] = item_copy[key]
merged[name] = result
else:
if behavior == "remove":
continue
merged[name] = item_copy
return list(merged.values())
def hash_data(data):
"""Generate SHA-256 hash for idempotency checking."""
return hashlib.sha256(yaml.safe_dump(data, sort_keys=True).encode()).hexdigest()
def write_file(dest, data):
if not dest:
return False
with open(dest, "w") as f:
yaml.safe_dump(data, f, sort_keys=False)
return True
+65 -543
View File
@@ -21,7 +21,7 @@ author:
- Matthieu Diehr (@d-matt)
requirements:
- "helm >= 3.0.0 (https://github.com/helm/helm/releases)"
- "helm (https://github.com/helm/helm/releases)"
- "yaml (https://pypi.org/project/PyYAML/)"
description:
@@ -132,36 +132,19 @@ options:
version_added: 2.4.0
reuse_values:
description:
- When upgrading package, specifies whether to reuse the last release's values and merge in any overrides from parameters O(release_values),
O(values_files) or O(set_values).
- Helm ignores this when C(--reset-values) is passed. Since O(reset_values) defaults to V(true), it has to be set to V(false)
for this option to take any effect.
- C(helm install) does not accept C(--reuse-values), so this option is ignored when O(replace) is set.
- The module warns whenever one of those combinations makes this option a no-op.
- When upgrading package, specifies wether to reuse the last release's values and merge in any overrides from parameters I(release_values),
I(values_files) or I(set_values).
- If I(reset_values) is set to C(True), this is ignored.
type: bool
required: false
version_added: 3.0.0
version_added: 2.5.0
reset_values:
description:
- When upgrading package, reset the values to the ones built into the chart.
- Defaults to V(true), which makes helm ignore O(reuse_values) and O(reset_then_reuse_values). Set it to V(false) to use either of them.
type: bool
required: false
default: True
version_added: 3.0.0
reset_then_reuse_values:
description:
- When upgrading package, reset the values to the ones built into the chart, apply the last release's values and merge in any overrides from
parameters O(release_values), O(values_files) or O(set_values).
- Helm ignores this when C(--reset-values) or C(--reuse-values) is passed. Since O(reset_values) defaults to V(true), it has to be
set to V(false), and O(reuse_values) left unset or V(false), for this option to take any effect.
- C(helm install) does not accept C(--reset-then-reuse-values), so this option is ignored when O(replace) is set.
- The module warns whenever one of those combinations makes this option a no-op.
- This feature requires helm diff >= 3.9.12.
type: bool
required: false
default: False
version_added: 6.0.0
version_added: 2.5.0
#Helm options
disable_hook:
@@ -172,13 +155,6 @@ options:
force:
description:
- Helm option to force reinstall, ignore on new install.
- With Helm v4 this performs a client-side replacement. Helm v4 deprecated
C(--force) (split into C(--force-replace) and C(--force-conflicts)) and
enables server-side apply by default, so for Helm v4 the module emits
C(--server-side=false --force-replace) to preserve the Helm v3 behaviour.
With Helm v3 the C(--force) flag is used. The O(force) option works the
same way regardless of the installed Helm version.
- Mutually exclusive with O(server_side) and O(force_conflicts).
default: False
type: bool
purge:
@@ -194,19 +170,10 @@ options:
It will wait for as long as I(wait_timeout). This feature requires helm>=3.7.0. Added in version 2.3.0.
default: False
type: bool
wait_for_jobs:
description:
- When I(release_state) is set to C(present), and I(wait) is set to C(True), wait until all jobs are in a
completed state before marking the release as successful.
- Ignored when used without O(wait).
- Requires Helm >= 3.5.0
version_added: 6.6.0
default: False
type: bool
wait_timeout:
description:
- Timeout when wait option is enabled (helm2 is a number of seconds, helm3 is a duration).
- The use of I(wait_timeout) to wait for kubernetes commands to complete has been deprecated and will be removed in version 7.0.0. Use O(timeout) instead.
- The use of I(wait_timeout) to wait for kubernetes commands to complete has been deprecated and will be removed after 2022-12-01.
type: str
timeout:
description:
@@ -218,44 +185,8 @@ options:
atomic:
description:
- If set, the installation process deletes the installation on failure.
- With Helm v4 this is translated to the C(--rollback-on-failure) flag, since
C(--atomic) was renamed; with Helm v3 the C(--atomic) flag is used. The
O(atomic) option works the same way regardless of the installed Helm version.
type: bool
default: False
cleanup_on_fail:
description:
- Allow deletion of new resources created during a failed upgrade.
- Maps to the C(--cleanup-on-fail) flag, which is available since helm 3.0.0 and
was not renamed in Helm v4.
- Complements O(atomic) rather than replacing it, and the two can be combined so
that a rollback also drops resources orphaned by the failed upgrade.
- Helm only accepts this flag on C(helm upgrade), so it cannot be used together
with O(replace), which deploys through C(helm install).
type: bool
default: False
version_added: 6.6.0
server_side:
description:
- Control Helm v4 server-side apply when installing or upgrading a release.
- Maps to the C(--server-side) flag, which accepts C(true), C(false) or C(auto).
- This option requires Helm v4 and is mutually exclusive with O(force).
type: str
choices:
- "auto"
- "true"
- "false"
version_added: 6.5.0
force_conflicts:
description:
- When server-side apply is enabled (the Helm v4 default), force changes
against conflicts instead of failing.
- Maps to the C(--force-conflicts) flag.
- This option requires Helm v4, cannot be combined with O(server_side=false),
and is mutually exclusive with O(force).
type: bool
default: False
version_added: 6.5.0
create_namespace:
description:
- Create the release namespace if not present.
@@ -287,36 +218,6 @@ options:
- mutually exclusive with with C(replace).
type: int
version_added: 2.2.0
insecure_skip_tls_verify:
description:
- Skip tls certificate checks for the chart download.
- Do not confuse with the C(validate_certs) option.
- This option is only available for helm >= 3.16.0.
type: bool
default: False
aliases: [ skip_tls_certs_check ]
version_added: 5.3.0
plain_http:
description:
- Use HTTP instead of HTTPS when working with OCI registries
- Requires Helm >= 3.13.0
type: bool
default: False
version_added: 6.1.0
take_ownership:
description:
- Helm will ignore the check for helm annotations and take ownership of the existing resources
- This feature requires helm >= 3.17.0
type: bool
default: False
version_added: 6.1.0
skip_schema_validation:
description:
- Disables JSON schema validation for Chart and values.
- This feature requires helm >= 3.16.0
type: bool
default: False
version_added: 6.2.0
extends_documentation_fragment:
- kubernetes.core.helm_common_options
"""
@@ -399,12 +300,6 @@ EXAMPLES = r"""
chart_ref: "https://github.com/grafana/helm-charts/releases/download/grafana-5.6.0/grafana-5.6.0.tgz"
release_namespace: monitoring
- name: Deploy Bitnami's MongoDB latest chart from OCI registry
kubernetes.core.helm:
name: test
chart_ref: "oci://registry-1.docker.io/bitnamicharts/mongodb"
release_namespace: database
# Using complex Values
- name: Deploy new-relic client chart
kubernetes.core.helm:
@@ -413,7 +308,6 @@ EXAMPLES = r"""
release_namespace: default
force: True
wait: True
wait_for_jobs: True
replace: True
update_repo_cache: True
disable_hook: True
@@ -433,30 +327,15 @@ EXAMPLES = r"""
enabled: True
# Deploy latest version
# 'reset_values' defaults to true and helm ignores '--reuse-values' when it is set,
# so it has to be turned off explicitly.
- name: Deploy latest version of Grafana chart using reuse_values
kubernetes.core.helm:
name: test
chart_ref: stable/grafana
release_namespace: monitoring
reuse_values: true
reset_values: false
values:
replicas: 2
version: 3e8ec0b2dffa40fb97d5342e4af887de95faa8c61a62480dd7f8aa03dffcf533
# Same for 'reset_then_reuse_values', which helm ignores when either
# '--reset-values' or '--reuse-values' is set.
- name: Deploy latest version of Grafana chart using reset_then_reuse_values
kubernetes.core.helm:
name: test
chart_ref: stable/grafana
release_namespace: monitoring
reset_then_reuse_values: true
reset_values: false
values:
replicas: 2
"""
RETURN = r"""
@@ -494,18 +373,9 @@ status:
returned: always
description: The Date of last update
values:
type: dict
type: str
returned: always
description:
- Dict of Values used to deploy.
- This return value has been deprecated and will be removed in version 8.0.0.
Use RV(status.release_values) instead.
release_values:
type: dict
returned: always
description:
- Dict of Values used to deploy.
version_added: 6.3.0
description: Dict of Values used to deploy
stdout:
type: str
description: Full `helm` command stdout, in case you want to display it or examine the event log
@@ -545,7 +415,6 @@ from ansible.module_utils.basic import missing_required_lib
from ansible_collections.kubernetes.core.plugins.module_utils.helm import (
AnsibleHelmModule,
parse_helm_plugin_list,
strip_registry_progress,
)
from ansible_collections.kubernetes.core.plugins.module_utils.helm_args_common import (
HELM_AUTH_ARG_SPEC,
@@ -576,13 +445,9 @@ def get_release_status(module, release_name, all_status=False):
"--filter",
release_name,
]
if all_status and not module.is_helm_v4():
# --all has been removed from `helm list` command on helm v4
if all_status:
list_command.append("--all")
elif not all_status:
# The default behavior to display only deployed releases has been removed from
# Helm v4
list_command.append("--deployed")
rc, out, err = module.run_helm_command(list_command)
release = get_release(yaml.safe_load(out), release_name)
@@ -590,15 +455,7 @@ def get_release_status(module, release_name, all_status=False):
if release is None: # not install
return None
release["release_values"] = module.get_values(release_name)
release["values"] = release["release_values"]
# Add deprecation warning for status.values
module.deprecate(
"The 'status.values' return value is deprecated and will be removed in version 8.0.0. Use 'status.release_values' instead.",
version="8.0.0",
collection_name="kubernetes.core",
)
release["values"] = module.get_values(release_name)
return release
@@ -619,76 +476,15 @@ def run_dep_update(module, chart_ref):
rc, out, err = module.run_helm_command(dep_update)
def fetch_chart_info(
module, command, chart_ref, insecure_skip_tls_verify=False, plain_http=False
):
def fetch_chart_info(module, command, chart_ref):
"""
Get chart info
"""
inspect_command = command + f" show chart '{chart_ref}'"
if insecure_skip_tls_verify:
inspect_command += " --insecure-skip-tls-verify"
if plain_http:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.13.0"):
module.fail_json(
msg="plain_http requires helm >= 3.13.0, current version is {0}".format(
helm_version
)
)
else:
inspect_command += " --plain-http"
rc, out, err = module.run_helm_command(inspect_command)
return yaml.safe_load(strip_registry_progress(out))
def validate_value_options(
module, replace, reuse_values, reset_values, reset_then_reuse_values
):
"""
Check the value-reuse options against each other and against 'replace'.
'helm install' accepts none of these flags, so 'replace' drops all three. The rest
are precedence rules helm applies silently: '--reset-values' wins over
'--reuse-values', and both win over '--reset-then-reuse-values'. Since 'reset_values'
defaults to true, requesting either of the other two on its own is a no-op.
Warn rather than fail throughout. Every one of these combinations is accepted by
playbooks today: 'reuse_values' has existed since 3.0.0, and a release that is
already converged never reaches deploy(), so the invalid command was never built.
Failing here would turn tasks that pass today into tasks that fail.
"""
if replace:
for name, requested in (
("reuse_values", reuse_values is not None),
("reset_then_reuse_values", reset_then_reuse_values),
):
if requested:
module.warn(
"{0} is ignored because replace=true deploys through 'helm install',"
" which does not accept the flag.".format(name)
)
return
if reset_values:
for name, requested in (
("reuse_values", reuse_values),
("reset_then_reuse_values", reset_then_reuse_values),
):
if requested:
module.warn(
"{0} is ignored because reset_values is true. "
"Set reset_values=false to make it take effect.".format(name)
)
elif reuse_values and reset_then_reuse_values:
module.warn(
"reset_then_reuse_values is ignored because reuse_values is true. "
"Set reuse_values=false to make it take effect."
)
return yaml.safe_load(out)
def deploy(
@@ -698,14 +494,12 @@ def deploy(
release_values,
chart_name,
wait,
wait_for_jobs,
wait_timeout,
disable_hook,
force,
values_files,
history_max,
atomic=False,
cleanup_on_fail=False,
create_namespace=False,
replace=False,
post_renderer=None,
@@ -715,13 +509,6 @@ def deploy(
set_value_args=None,
reuse_values=None,
reset_values=True,
reset_then_reuse_values=False,
insecure_skip_tls_verify=False,
plain_http=False,
take_ownership=False,
skip_schema_validation=False,
server_side=None,
force_conflicts=False,
):
"""
Install/upgrade/rollback release chart
@@ -733,99 +520,25 @@ def deploy(
deploy_command += " --dependency-update"
else:
deploy_command = command + " upgrade -i" # install/upgrade
if take_ownership:
deploy_command += " --take-ownership"
# '--reset-values', '--reuse-values' and '--reset-then-reuse-values' are all
# upgrade-only flags, so they must not leak into the 'replace' branch above.
# validate_value_options() has already warned about that combination.
if reset_values:
deploy_command += " --reset-values"
if reuse_values is not None:
deploy_command += " --reuse-values=" + str(reuse_values)
if reset_then_reuse_values:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.14.0"):
module.fail_json(
msg="reset_then_reuse_values requires helm >= 3.14.0, current version is {0}".format(
helm_version
)
)
else:
deploy_command += " --reset-then-reuse-values"
if reuse_values is not None:
deploy_command += " --reuse-values=" + str(reuse_values)
if wait:
deploy_command += " --wait"
if wait_for_jobs:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.5.0"):
module.fail_json(
msg="wait_for_jobs requires helm >= 3.5.0, current version is {0}".format(
helm_version
)
)
else:
deploy_command += " --wait-for-jobs"
if wait_timeout is not None:
deploy_command += " --timeout " + wait_timeout
if atomic:
# Helm v4 renamed '--atomic' to '--rollback-on-failure'. The old flag is
# deprecated on 'helm upgrade' and removed from 'helm install', so always
# emit the version-appropriate flag.
if module.is_helm_v4():
deploy_command += " --rollback-on-failure"
else:
deploy_command += " --atomic"
if cleanup_on_fail:
# '--cleanup-on-fail' is only accepted by 'helm upgrade', so it cannot be
# combined with 'replace', which deploys through 'helm install'. The flag
# exists since helm 3.0.0 and kept its name in v4, so no version gate is
# needed on top of the module-wide helm >= 3.0.0 requirement.
if replace:
module.fail_json(
msg="cleanup_on_fail is only supported by 'helm upgrade' and cannot be used with replace=true"
)
deploy_command += " --cleanup-on-fail"
deploy_command += " --atomic"
if timeout:
deploy_command += " --timeout " + timeout
if server_side is not None:
if not module.is_helm_v4():
module.fail_json(
msg="server_side requires helm >= 4.0.0, current version is {0}".format(
module.get_helm_version()
)
)
deploy_command += " --server-side=" + server_side
if force_conflicts:
if not module.is_helm_v4():
module.fail_json(
msg="force_conflicts requires helm >= 4.0.0, current version is {0}".format(
module.get_helm_version()
)
)
if server_side == "false":
module.fail_json(
msg="force_conflicts requires server-side apply to be enabled and cannot be used with server_side=false"
)
deploy_command += " --force-conflicts"
if force:
# Helm v4 deprecated '--force' (split into '--force-replace' and
# '--force-conflicts') and enables server-side apply by default, which is
# incompatible with '--force-replace'. Emit the version-appropriate flags,
# disabling server-side apply on v4 to preserve the v3 client-side
# replacement behaviour. 'force' is mutually exclusive with 'server_side'.
if module.is_helm_v4():
deploy_command += " --server-side=false --force-replace"
else:
deploy_command += " --force"
deploy_command += " --force"
if replace:
deploy_command += " --replace"
@@ -836,20 +549,6 @@ def deploy(
if create_namespace:
deploy_command += " --create-namespace"
if insecure_skip_tls_verify:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.16.0"):
module.fail_json(
msg="insecure_skip_tls_verify requires helm >= 3.16.0, current version is {0}".format(
helm_version
)
)
else:
deploy_command += " --insecure-skip-tls-verify"
if plain_http:
deploy_command += " --plain-http"
if values_files:
for value_file in values_files:
deploy_command += " --values=" + value_file
@@ -873,17 +572,6 @@ def deploy(
if set_value_args:
deploy_command += " " + set_value_args
if skip_schema_validation:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.16.0"):
module.fail_json(
msg="skip_schema_validation requires helm >= 3.16.0, current version is {0}".format(
helm_version
)
)
else:
deploy_command += " --skip-schema-validation"
deploy_command += " " + release_name + f" '{chart_name}'"
return deploy_command
@@ -936,8 +624,8 @@ def get_plugin_version(plugin):
return None
for line in out:
if line["name"] == plugin:
return line["version"]
if line[0] == plugin:
return line[1]
return None
@@ -954,10 +642,6 @@ def helmdiff_check(
set_value_args=None,
reuse_values=None,
reset_values=True,
reset_then_reuse_values=False,
insecure_skip_tls_verify=False,
plain_http=False,
skip_schema_validation=False,
):
"""
Use helm diff to determine if a release would change by upgrading a chart.
@@ -989,52 +673,9 @@ def helmdiff_check(
if set_value_args:
cmd += " " + set_value_args
if not replace and reuse_values:
if reuse_values:
cmd += " --reuse-values"
if not replace and reset_then_reuse_values:
helm_diff_version = get_plugin_version("diff")
helm_version = module.get_helm_version()
fail_msg = ""
if LooseVersion(helm_diff_version) < LooseVersion("3.9.12"):
fail_msg = "reset_then_reuse_values requires helm diff >= 3.9.12, current version is {0}\n".format(
helm_diff_version
)
if LooseVersion(helm_version) < LooseVersion("3.14.0"):
fail_msg += "reset_then_reuse_values requires helm >= 3.14.0, current version is {0}\n".format(
helm_version
)
if fail_msg:
module.fail_json(msg=fail_msg)
else:
cmd += " --reset-then-reuse-values"
if insecure_skip_tls_verify:
cmd += " --insecure-skip-tls-verify"
if skip_schema_validation:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.16.0"):
module.fail_json(
msg="skip_schema_validation requires helm >= 3.16.0, current version is {0}".format(
helm_version
)
)
else:
cmd += " --skip-schema-validation"
if plain_http:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.13.0"):
module.fail_json(
msg="plain_http requires helm >= 3.13.0, current version is {0}".format(
helm_version
)
)
else:
cmd += " --plain-http"
rc, out, err = module.run_helm_command(cmd)
return (len(out.strip()) > 0, out.strip())
@@ -1066,58 +707,35 @@ def default_check(release_status, chart_info, values=None, values_files=None):
def argument_spec():
arg_spec = copy.deepcopy(HELM_AUTH_ARG_SPEC)
arg_spec.update(
{
"chart_ref": {"type": "path"},
"chart_repo_url": {"type": "str"},
"chart_version": {"type": "str"},
"dependency_update": {
"type": "bool",
"default": False,
"aliases": ["dep_up"],
},
"release_name": {"type": "str", "required": True, "aliases": ["name"]},
"release_namespace": {
"type": "str",
"required": True,
"aliases": ["namespace"],
},
"release_state": {
"default": "present",
"choices": ["present", "absent"],
"aliases": ["state"],
},
"release_values": {"type": "dict", "default": {}, "aliases": ["values"]},
"values_files": {"type": "list", "default": [], "elements": "str"},
"update_repo_cache": {"type": "bool", "default": False},
"disable_hook": {"type": "bool", "default": False},
"force": {"type": "bool", "default": False},
"purge": {"type": "bool", "default": True},
"wait": {"type": "bool", "default": False},
"wait_for_jobs": {"type": "bool", "default": False},
"wait_timeout": {"type": "str"},
"timeout": {"type": "str"},
"atomic": {"type": "bool", "default": False},
"server_side": {"type": "str", "choices": ["auto", "true", "false"]},
"force_conflicts": {"type": "bool", "default": False},
"create_namespace": {"type": "bool", "default": False},
"post_renderer": {"type": "str"},
"replace": {"type": "bool", "default": False},
"skip_crds": {"type": "bool", "default": False},
"history_max": {"type": "int"},
"set_values": {"type": "list", "elements": "dict"},
"reuse_values": {"type": "bool"},
"reset_values": {"type": "bool", "default": True},
"reset_then_reuse_values": {"type": "bool", "default": False},
"insecure_skip_tls_verify": {
"type": "bool",
"default": False,
"aliases": ["skip_tls_certs_check"],
},
"plain_http": {"type": "bool", "default": False},
"take_ownership": {"type": "bool", "default": False},
"skip_schema_validation": {"type": "bool", "default": False},
"cleanup_on_fail": {"type": "bool", "default": False},
}
dict(
chart_ref=dict(type="path"),
chart_repo_url=dict(type="str"),
chart_version=dict(type="str"),
dependency_update=dict(type="bool", default=False, aliases=["dep_up"]),
release_name=dict(type="str", required=True, aliases=["name"]),
release_namespace=dict(type="str", required=True, aliases=["namespace"]),
release_state=dict(
default="present", choices=["present", "absent"], aliases=["state"]
),
release_values=dict(type="dict", default={}, aliases=["values"]),
values_files=dict(type="list", default=[], elements="str"),
update_repo_cache=dict(type="bool", default=False),
disable_hook=dict(type="bool", default=False),
force=dict(type="bool", default=False),
purge=dict(type="bool", default=True),
wait=dict(type="bool", default=False),
wait_timeout=dict(type="str"),
timeout=dict(type="str"),
atomic=dict(type="bool", default=False),
create_namespace=dict(type="bool", default=False),
post_renderer=dict(type="str"),
replace=dict(type="bool", default=False),
skip_crds=dict(type="bool", default=False),
history_max=dict(type="int"),
set_values=dict(type="list", elements="dict"),
reuse_values=dict(type="bool"),
reset_values=dict(type="bool", default=True),
)
)
return arg_spec
@@ -1134,26 +752,13 @@ def main():
("context", "ca_cert"),
("replace", "history_max"),
("wait_timeout", "timeout"),
("force", "server_side"),
("force", "force_conflicts"),
],
supports_check_mode=True,
)
# Add deprecation warning for wait_timeout
if module.params.get("wait_timeout") is not None:
module.deprecate(
"The 'wait_timeout' parameter is deprecated and will be removed in version 7.0.0. Use 'timeout' instead.",
version="7.0.0",
collection_name="kubernetes.core",
)
if not IMP_YAML:
module.fail_json(msg=missing_required_lib("yaml"), exception=IMP_YAML_ERR)
# Validate Helm version >=3.0.0
module.validate_helm_version()
changed = False
chart_ref = module.params.get("chart_ref")
@@ -1171,12 +776,8 @@ def main():
force = module.params.get("force")
purge = module.params.get("purge")
wait = module.params.get("wait")
wait_for_jobs = module.params.get("wait_for_jobs")
wait_timeout = module.params.get("wait_timeout")
atomic = module.params.get("atomic")
cleanup_on_fail = module.params.get("cleanup_on_fail")
server_side = module.params.get("server_side")
force_conflicts = module.params.get("force_conflicts")
create_namespace = module.params.get("create_namespace")
post_renderer = module.params.get("post_renderer")
replace = module.params.get("replace")
@@ -1186,11 +787,6 @@ def main():
set_values = module.params.get("set_values")
reuse_values = module.params.get("reuse_values")
reset_values = module.params.get("reset_values")
reset_then_reuse_values = module.params.get("reset_then_reuse_values")
insecure_skip_tls_verify = module.params.get("insecure_skip_tls_verify")
plain_http = module.params.get("plain_http")
take_ownership = module.params.get("take_ownership")
skip_schema_validation = module.params.get("skip_schema_validation")
if update_repo_cache:
run_repo_update(module)
@@ -1200,33 +796,6 @@ def main():
release_status = get_release_status(module, release_name, all_status=all_status)
helm_cmd = module.get_helm_binary()
if plain_http:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.13.0"):
module.fail_json(
msg="plain_http requires helm >= 3.13.0, current version is {0}".format(
helm_version
)
)
if take_ownership:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.17.0"):
module.fail_json(
msg="take_ownership requires helm >= 3.17.0, current version is {0}".format(
helm_version
)
)
if skip_schema_validation:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.16.0"):
module.fail_json(
msg="skip_schema_validation requires helm >= 3.16.0, current version is {0}".format(
helm_version
)
)
opt_result = {}
if release_state == "absent" and release_status is not None:
# skip release statuses 'uninstalled' and 'uninstalling'
@@ -1237,7 +806,8 @@ def main():
if wait:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.7.0"):
module.warn(
opt_result["warnings"] = []
opt_result["warnings"].append(
"helm uninstall support option --wait for helm release >= 3.7.0"
)
wait = False
@@ -1247,10 +817,6 @@ def main():
)
changed = True
elif release_state == "present":
validate_value_options(
module, replace, reuse_values, reset_values, reset_then_reuse_values
)
if chart_version is not None:
helm_cmd += " --version=" + chart_version
@@ -1258,9 +824,7 @@ def main():
helm_cmd += " --repo=" + chart_repo_url
# Fetch chart info to have real version and real name for chart_ref from archive, folder or url
chart_info = fetch_chart_info(
module, helm_cmd, chart_ref, insecure_skip_tls_verify, plain_http
)
chart_info = fetch_chart_info(module, helm_cmd, chart_ref)
if dependency_update:
if chart_info.get("dependencies"):
@@ -1304,15 +868,11 @@ def main():
release_values,
chart_ref,
wait,
wait_for_jobs,
wait_timeout,
disable_hook,
False,
values_files=values_files,
atomic=atomic,
cleanup_on_fail=cleanup_on_fail,
server_side=server_side,
force_conflicts=force_conflicts,
create_namespace=create_namespace,
post_renderer=post_renderer,
replace=replace,
@@ -1323,31 +883,19 @@ def main():
set_value_args=set_value_args,
reuse_values=reuse_values,
reset_values=reset_values,
reset_then_reuse_values=reset_then_reuse_values,
insecure_skip_tls_verify=insecure_skip_tls_verify,
plain_http=plain_http,
take_ownership=take_ownership,
skip_schema_validation=skip_schema_validation,
)
changed = True
else:
helm_diff_version = get_plugin_version("diff")
helm_version_compatible = module.is_helm_version_compatible_with_helm_diff(
helm_diff_version
)
if (
helm_diff_version
and helm_version_compatible
and (
not chart_repo_url
or (
chart_repo_url
and LooseVersion(helm_diff_version) >= LooseVersion("3.4.1")
)
if helm_diff_version and (
not chart_repo_url
or (
chart_repo_url
and LooseVersion(helm_diff_version) >= LooseVersion("3.4.1")
)
):
would_change, prepared = helmdiff_check(
(would_change, prepared) = helmdiff_check(
module,
release_name,
chart_ref,
@@ -1360,26 +908,14 @@ def main():
set_value_args,
reuse_values=reuse_values,
reset_values=reset_values,
reset_then_reuse_values=reset_then_reuse_values,
insecure_skip_tls_verify=insecure_skip_tls_verify,
plain_http=plain_http,
skip_schema_validation=skip_schema_validation,
)
if would_change and module._diff:
opt_result["diff"] = {"prepared": prepared}
else:
if helm_diff_version and not helm_version_compatible:
module.warn(
"Idempotency checks are currently disabled due to a version mismatch."
f" Helm version {module.get_helm_version()} requires helm-diff >= 3.14.0,"
f" but the environment is currently running {helm_diff_version}."
" Please align the plugin versions to restore standard behavior."
)
else:
module.warn(
"The default idempotency check can fail to report changes in certain cases. "
"Install helm diff >= 3.4.1 for better results."
)
module.warn(
"The default idempotency check can fail to report changes in certain cases. "
"Install helm diff >= 3.4.1 for better results."
)
would_change = default_check(
release_status, chart_info, release_values, values_files
)
@@ -1392,15 +928,11 @@ def main():
release_values,
chart_ref,
wait,
wait_for_jobs,
wait_timeout,
disable_hook,
force,
values_files=values_files,
atomic=atomic,
cleanup_on_fail=cleanup_on_fail,
server_side=server_side,
force_conflicts=force_conflicts,
create_namespace=create_namespace,
post_renderer=post_renderer,
replace=replace,
@@ -1411,24 +943,14 @@ def main():
set_value_args=set_value_args,
reuse_values=reuse_values,
reset_values=reset_values,
reset_then_reuse_values=reset_then_reuse_values,
insecure_skip_tls_verify=insecure_skip_tls_verify,
plain_http=plain_http,
take_ownership=take_ownership,
skip_schema_validation=skip_schema_validation,
)
changed = True
if module.check_mode:
check_status = {
"values": {"current": {}, "declared": {}},
"release_values": {"current": {}, "declared": {}},
}
check_status = {"values": {"current": {}, "declared": {}}}
if release_status:
check_status["values"]["current"] = release_status["release_values"]
check_status["values"]["current"] = release_status["values"]
check_status["values"]["declared"] = release_status
check_status["release_values"]["current"] = release_status["release_values"]
check_status["release_values"]["declared"] = release_status
module.exit_json(
changed=changed,
+4 -25
View File
@@ -20,7 +20,7 @@ author:
- Lucas Boisserie (@LucasBoisserie)
requirements:
- "helm >= 3.0.0 (https://github.com/helm/helm/releases)"
- "helm (https://github.com/helm/helm/releases)"
- "yaml (https://pypi.org/project/PyYAML/)"
description:
@@ -115,18 +115,9 @@ status:
returned: always
description: The Date of last update
values:
type: dict
type: str
returned: always
description:
- Dict of Values used to deploy
- This return value has been deprecated and will be removed in version 8.0.0.
Use RV(status.release_values) instead.
release_values:
type: dict
returned: always
description:
- Dict of Values used to deploy.
version_added: 6.3.0
description: Dict of Values used to deploy
hooks:
type: list
elements: dict
@@ -211,16 +202,7 @@ def get_release_status(module, release_name, release_state, get_all_values=False
if release is None: # not install
return None
release["release_values"] = module.get_values(release_name, get_all_values)
release["values"] = release["release_values"]
# Add deprecation warning for status.values
module.deprecate(
"The 'status.values' return value is deprecated and will be removed in version 8.0.0. Use 'status.release_values' instead.",
version="8.0.0",
collection_name="kubernetes.core",
)
release["values"] = module.get_values(release_name, get_all_values)
release["manifest"] = module.get_manifest(release_name)
release["notes"] = module.get_notes(release_name)
release["hooks"] = module.get_hooks(release_name)
@@ -253,9 +235,6 @@ def main():
if not IMP_YAML:
module.fail_json(msg=missing_required_lib("yaml"), exception=IMP_YAML_ERR)
# Validate Helm version >=3.0.0
module.validate_helm_version()
release_name = module.params.get("release_name")
release_state = module.params.get("release_state")
get_all_values = module.params.get("get_all_values")
+17 -69
View File
@@ -16,7 +16,7 @@ version_added: 1.0.0
author:
- Abhijeet Kasurde (@Akasurde)
requirements:
- "helm >= 3.0.0 (https://github.com/helm/helm/releases)"
- "helm (https://github.com/helm/helm/releases)"
description:
- Manages Helm plugins.
options:
@@ -48,22 +48,6 @@ options:
required: false
type: str
version_added: 2.3.0
verify:
description:
- Verify the plugin signature before installing.
- This option requires helm version >= 4.0.0
- Used with I(state=present).
type: bool
default: true
version_added: 6.4.0
keyring:
description:
- Location of public keys used for verification.
- Only valid with C(state=present), which maps to the C(helm plugin install) subcommand.
- This option requires helm version >= 4.0.0.
type: path
required: false
version_added: 6.5.0
extends_documentation_fragment:
- kubernetes.core.helm_common_options
"""
@@ -134,9 +118,6 @@ from ansible_collections.kubernetes.core.plugins.module_utils.helm_args_common i
HELM_AUTH_ARG_SPEC,
HELM_AUTH_MUTUALLY_EXCLUSIVE,
)
from ansible_collections.kubernetes.core.plugins.module_utils.version import (
LooseVersion,
)
def argument_spec():
@@ -157,14 +138,6 @@ def argument_spec():
default="present",
choices=["present", "absent", "latest"],
),
verify=dict(
type="bool",
default=True,
),
keyring=dict(
type="path",
required=False,
),
)
)
return arg_spec
@@ -188,50 +161,15 @@ def main():
mutually_exclusive=mutually_exclusive(),
)
# Validate helm version >= 3.0.0
module.validate_helm_version()
state = module.params.get("state")
# The ``--keyring`` flag is only supported by the ``install``, ``verify`` and
# ``package`` plugin subcommands. Of those, this module only implements
# ``install`` (state=present); using ``keyring`` with other states emits a
# warning and the option is not passed to Helm.
if module.params.get("keyring") is not None and state != "present":
module.warn(
"The 'keyring' option is only supported with state=present "
"(the 'helm plugin install' subcommand)."
)
helm_cmd_common = module.get_helm_binary() + " plugin"
if state == "present":
helm_cmd_common += " install %s" % module.params.get("plugin_path")
plugin_version = module.params.get("plugin_version")
verify = module.params.get("verify")
keyring = module.params.get("keyring")
if plugin_version is not None:
helm_cmd_common += " --version=%s" % plugin_version
if not verify or keyring is not None:
helm_version = module.get_helm_version()
if not verify:
if LooseVersion(helm_version) < LooseVersion("4.0.0"):
module.warn(
"verify parameter requires helm >= 4.0.0, current version is {0}".format(
helm_version
)
)
else:
helm_cmd_common += " --verify=false"
if keyring is not None:
if LooseVersion(helm_version) < LooseVersion("4.0.0"):
module.warn(
"keyring parameter requires helm >= 4.0.0, current version is {0}".format(
helm_version
)
)
else:
helm_cmd_common += " --keyring=" + keyring
if not module.check_mode:
rc, out, err = module.run_helm_command(
helm_cmd_common, fails_on_error=False
@@ -270,9 +208,9 @@ def main():
elif state == "absent":
plugin_name = module.params.get("plugin_name")
rc, output, err, command = module.get_helm_plugin_list()
plugins = parse_helm_plugin_list(output=output.splitlines())
out = parse_helm_plugin_list(output=output.splitlines())
if not plugins:
if not out:
module.exit_json(
failed=False,
changed=False,
@@ -283,7 +221,12 @@ def main():
rc=rc,
)
if all(plugin["name"] != plugin_name for plugin in plugins):
found = False
for line in out:
if line[0] == plugin_name:
found = True
break
if not found:
module.exit_json(
failed=False,
changed=False,
@@ -321,9 +264,9 @@ def main():
elif state == "latest":
plugin_name = module.params.get("plugin_name")
rc, output, err, command = module.get_helm_plugin_list()
plugins = parse_helm_plugin_list(output=output.splitlines())
out = parse_helm_plugin_list(output=output.splitlines())
if not plugins:
if not out:
module.exit_json(
failed=False,
changed=False,
@@ -334,7 +277,12 @@ def main():
rc=rc,
)
if all(plugin["name"] != plugin_name for plugin in plugins):
found = False
for line in out:
if line[0] == plugin_name:
found = True
break
if not found:
module.exit_json(
failed=False,
changed=False,
+18 -8
View File
@@ -16,7 +16,7 @@ version_added: 1.0.0
author:
- Abhijeet Kasurde (@Akasurde)
requirements:
- "helm >= 3.0.0 (https://github.com/helm/helm/releases)"
- "helm (https://github.com/helm/helm/releases)"
description:
- Gather information about Helm plugins installed in namespace.
options:
@@ -98,16 +98,26 @@ def main():
supports_check_mode=True,
)
# Validate helm version >= 3.0.0
module.validate_helm_version()
plugin_name = module.params.get("plugin_name")
plugin_list = []
rc, output, err, command = module.get_helm_plugin_list()
plugins = parse_helm_plugin_list(output=output.splitlines())
if plugin_name is not None:
plugins = [plugin for plugin in plugins if plugin.get("name") == plugin_name]
out = parse_helm_plugin_list(output=output.splitlines())
for line in out:
if plugin_name is None:
plugin_list.append(
{"name": line[0], "version": line[1], "description": line[2]}
)
continue
if plugin_name == line[0]:
plugin_list.append(
{"name": line[0], "version": line[1], "description": line[2]}
)
break
module.exit_json(
changed=True,
@@ -115,7 +125,7 @@ def main():
stdout=output,
stderr=err,
rc=rc,
plugin_list=plugins,
plugin_list=plugin_list,
)
+10 -236
View File
@@ -21,7 +21,7 @@ description:
- There are options for unpacking the chart after download.
requirements:
- "helm >= 3.0.0 (https://github.com/helm/helm/releases)"
- "helm >= 3.0 (https://github.com/helm/helm/releases)"
options:
chart_ref:
@@ -75,10 +75,9 @@ options:
skip_tls_certs_check:
description:
- Whether or not to check tls certificate for the chart download.
- Requires helm >= 3.3.0. Alias C(insecure_skip_tls_verify) added in 5.3.0.
- Requires helm >= 3.3.0.
type: bool
default: False
aliases: [ insecure_skip_tls_verify ]
chart_devel:
description:
- Use development versions, too. Equivalent to version '>0.0.0-0'.
@@ -89,14 +88,6 @@ options:
- if set to true, will untar the chart after downloading it.
type: bool
default: False
force:
description:
- Force download of the chart even if it already exists in the destination directory.
- By default, the module will skip downloading if the chart with the same version already exists for idempotency.
- When used with O(untar_chart=true), will remove any existing chart directory before extracting.
type: bool
default: False
version_added: 6.3.0
destination:
description:
- location to write the chart.
@@ -122,13 +113,6 @@ options:
- The path of a helm binary to use.
required: false
type: path
plain_http:
description:
- Use HTTP instead of HTTPS when working with OCI registries
- Requires Helm >= 3.13.0
type: bool
default: False
version_added: 6.1.0
"""
EXAMPLES = r"""
@@ -160,23 +144,6 @@ EXAMPLES = r"""
destination: /path/to/chart
username: myuser
password: mypassword123
- name: Download Chart (force re-download even if exists)
kubernetes.core.helm_pull:
chart_ref: redis
repo_url: https://charts.bitnami.com/bitnami
chart_version: '17.0.0'
destination: /path/to/chart
force: yes
- name: Download and untar chart (force re-extraction even if directory exists)
kubernetes.core.helm_pull:
chart_ref: redis
repo_url: https://charts.bitnami.com/bitnami
chart_version: '17.0.0'
destination: /path/to/chart
untar_chart: yes
force: yes
"""
RETURN = r"""
@@ -195,11 +162,6 @@ command:
description: Full `helm pull` command built by this module, in case you want to re-run the command outside the module or debug a problem.
returned: always
sample: helm pull --repo test ...
msg:
type: str
description: A message indicating the result of the operation.
returned: when chart already exists
sample: Chart redis version 17.0.0 already exists in destination directory
rc:
type: int
description: Helm pull command return code
@@ -207,18 +169,6 @@ rc:
sample: 1
"""
import os
import shutil
import tarfile
import uuid
try:
import yaml
HAS_YAML = True
except ImportError:
HAS_YAML = False
from ansible_collections.kubernetes.core.plugins.module_utils.helm import (
AnsibleHelmModule,
)
@@ -227,115 +177,6 @@ from ansible_collections.kubernetes.core.plugins.module_utils.version import (
)
def extract_chart_name(chart_ref):
"""
Extract chart name from chart reference.
Args:
chart_ref (str): Chart reference (name, URL, or OCI reference)
Returns:
str: Extracted chart name
"""
chart_name = chart_ref.split("/")[-1]
# Remove any query parameters or fragments from URL-based refs
if "?" in chart_name:
chart_name = chart_name.split("?")[0]
if "#" in chart_name:
chart_name = chart_name.split("#")[0]
# Remove .tgz extension if present
if chart_name.endswith(".tgz"):
chart_name = chart_name[:-4]
return chart_name
def chart_exists(destination, chart_ref, chart_version, untar_chart):
"""
Check if the chart already exists in the destination directory.
For untarred charts: check if directory exists with Chart.yaml matching version
For tarred charts: check if .tgz file exists and contains matching version
Args:
destination (str): Destination directory path
chart_ref (str): Chart reference (name or URL)
chart_version (str): Chart version to check for
untar_chart (bool): Whether to check for untarred or tarred chart
Returns:
bool: True if chart with matching version exists, False otherwise
"""
# YAML is required for version checking
if not HAS_YAML:
return False
# Without version, we can't reliably check
if not chart_version:
return False
# Extract chart name from chart_ref using shared helper
chart_name = extract_chart_name(chart_ref)
if untar_chart:
# Check for extracted directory
chart_dir = os.path.join(destination, chart_name)
chart_yaml_path = os.path.join(chart_dir, "Chart.yaml")
if os.path.isdir(chart_dir) and os.path.isfile(chart_yaml_path):
try:
with open(chart_yaml_path, "r", encoding="utf-8") as chart_file:
chart_metadata = yaml.safe_load(chart_file)
# Ensure chart_metadata is a dict and has a version that matches
if (
chart_metadata
and isinstance(chart_metadata, dict)
and chart_metadata.get("version") == chart_version
and chart_metadata.get("name") == chart_name
):
return True
except (yaml.YAMLError, IOError, OSError, TypeError):
# If we can't read or parse the file, treat as non-existent
pass
else:
# Check for .tgz file
chart_file = os.path.join(destination, f"{chart_name}-{chart_version}.tgz")
if os.path.isfile(chart_file):
try:
# Verify it's a valid tarball with matching version
with tarfile.open(chart_file, "r:gz") as tar:
# Try to extract Chart.yaml to verify version
# Look for Chart.yaml at the expected path: <chart-name>/Chart.yaml
expected_chart_yaml = f"{chart_name}/Chart.yaml"
try:
member = tar.getmember(expected_chart_yaml)
chart_yaml_file = tar.extractfile(member)
if chart_yaml_file:
try:
chart_metadata = yaml.safe_load(chart_yaml_file)
# Ensure chart_metadata is a dict and has a version that matches
if (
chart_metadata
and isinstance(chart_metadata, dict)
and chart_metadata.get("version") == chart_version
and chart_metadata.get("name") == chart_name
):
return True
except (yaml.YAMLError, TypeError):
# If we can't parse the YAML, treat as non-existent
pass
finally:
chart_yaml_file.close()
except KeyError:
# Chart.yaml not found at expected path
pass
except (tarfile.TarError, yaml.YAMLError, IOError, OSError, TypeError):
# If we can't read or parse the tarball, treat as non-existent
pass
return False
def main():
argspec = dict(
chart_ref=dict(type="str", required=True),
@@ -348,19 +189,15 @@ def main():
repo_password=dict(
type="str", no_log=True, aliases=["password", "chart_repo_password"]
),
pass_credentials=dict(type="bool", default=False, no_log=False),
skip_tls_certs_check=dict(
type="bool", default=False, aliases=["insecure_skip_tls_verify"]
),
pass_credentials=dict(type="bool", default=False),
skip_tls_certs_check=dict(type="bool", default=False),
chart_devel=dict(type="bool"),
untar_chart=dict(type="bool", default=False),
force=dict(type="bool", default=False),
destination=dict(type="path", required=True),
chart_ca_cert=dict(type="path"),
chart_ssl_cert_file=dict(type="path"),
chart_ssl_key_file=dict(type="path"),
binary_path=dict(type="path"),
plain_http=dict(type="bool", default=False),
)
module = AnsibleHelmModule(
argument_spec=argspec,
@@ -372,17 +209,19 @@ def main():
mutually_exclusive=[("chart_version", "chart_devel")],
)
# Validate Helm version >=3.0.0
module.validate_helm_version()
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.0.0"):
module.fail_json(
msg="This module requires helm >= 3.0.0, current version is {0}".format(
helm_version
)
)
helm_pull_opt_versionning = dict(
skip_tls_certs_check="3.3.0",
chart_ca_cert="3.1.0",
chart_ssl_cert_file="3.1.0",
chart_ssl_key_file="3.1.0",
plain_http="3.13.0",
)
def test_version_requirement(opt):
@@ -422,7 +261,6 @@ def main():
skip_tls_certs_check=dict(key="insecure-skip-tls-verify"),
chart_devel=dict(key="devel"),
untar_chart=dict(key="untar"),
plain_http=dict(key="plain-http"),
)
for k, v in helm_flag_args.items():
@@ -435,72 +273,8 @@ def main():
module.params.get("chart_ref"),
" ".join(helm_pull_opts),
)
# Check if chart already exists (idempotency)
if module.params.get("chart_version") and not module.params.get("force"):
chart_exists_locally = chart_exists(
module.params.get("destination"),
module.params.get("chart_ref"),
module.params.get("chart_version"),
module.params.get("untar_chart"),
)
if chart_exists_locally:
module.exit_json(
failed=False,
changed=False,
msg="Chart {0} version {1} already exists in destination directory".format(
module.params.get("chart_ref"), module.params.get("chart_version")
),
command="",
stdout="",
stderr="",
rc=0,
)
# When both untar_chart and force are enabled, we need to remove the existing chart directory
# BEFORE running helm pull to prevent helm's "directory already exists" error.
# We do this by:
# 1. Renaming the existing directory to a temporary name (if it exists)
# 2. Running helm pull
# 3. On success: remove the temporary directory
# 4. On failure: restore the temporary directory and report the error
chart_dir_renamed = False
chart_dir = None
chart_dir_backup = None
if module.params.get("untar_chart") and module.params.get("force"):
chart_name = extract_chart_name(module.params.get("chart_ref"))
chart_dir = os.path.join(module.params.get("destination"), chart_name)
# Check if directory exists and contains a Chart.yaml (to be safe)
if os.path.isdir(chart_dir):
chart_yaml_path = os.path.join(chart_dir, "Chart.yaml")
# Only rename if it looks like a Helm chart directory (have Chart.yaml)
if os.path.isfile(chart_yaml_path):
if not module.check_mode:
# Rename to temporary backup name using uuid for uniqueness
backup_suffix = uuid.uuid4().hex[:8]
chart_dir_backup = os.path.join(
module.params.get("destination"),
f".{chart_name}_backup_{backup_suffix}",
)
os.rename(chart_dir, chart_dir_backup)
chart_dir_renamed = True
if not module.check_mode:
rc, out, err = module.run_helm_command(helm_cmd_common, fails_on_error=False)
# Handle cleanup/restore based on helm command result
if chart_dir_renamed:
if rc == 0:
# Success: remove the backup directory
if os.path.isdir(chart_dir_backup):
shutil.rmtree(chart_dir_backup)
else:
# Failure: restore the backup directory
if os.path.isdir(chart_dir_backup) and not os.path.exists(chart_dir):
os.rename(chart_dir_backup, chart_dir)
else:
rc, out, err = (0, "", "")
-290
View File
@@ -1,290 +0,0 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: © Ericsson AB 2024
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r"""
---
module: helm_registry_auth
short_description: Helm registry authentication module
version_added: 5.1.0
author:
- Yuriy Novostavskiy (@yurnov)
requirements:
- "helm (https://github.com/helm/helm/releases) >= 3.8.0"
description:
- Helm registry authentication module allows you to login C(helm registry login) and logout C(helm registry logout) from a Helm registry.
options:
state:
description:
- Desired state of the registry.
- If set to V(present) attempt to log in to the remote registry server using the URL specified in O(host).
- If set to V(absent) attempt to log out from the remote registry server using the URL specified in O(host).
- As helm >= 3.18.0 reports successful logout even if the user is not logged in, this module will report a change regardless of the current state.
required: false
default: present
choices: ['present', 'absent']
type: str
host:
description:
- Provide a URL for accessing the registry.
required: true
aliases: [ registry_url ]
type: str
insecure:
description:
- Allow connections to SSL sites without certs.
required: false
default: false
type: bool
username:
description:
- Username for the registry.
required: false
type: str
aliases: [ repo_username ]
password:
description:
- Password for the registry.
required: false
type: str
aliases: [ repo_password ]
key_file:
description:
- Path to the client key SSL file for identify registry client using this key file.
required: false
type: path
cert_file:
description:
- Path to the client certificate SSL file for identify registry client using this certificate file.
required: false
type: path
ca_file:
description:
- Path to the CA certificate SSL file for verify registry server certificate.
required: false
type: path
plain_http:
description:
- Use insecure HTTP connections for C(helm registry login).
- Requires Helm >= 3.18.0
required: false
type: bool
default: False
version_added: 6.4.0
binary_path:
description:
- The path of a helm binary to use.
required: false
type: path
"""
EXAMPLES = r"""
- name: Login to remote registry
kubernetes.core.helm_registry_auth:
username: admin
password: "sample_password"
host: localhost:5000
- name: Logout from remote registry
kubernetes.core.helm_registry_auth:
state: absent
host: localhost:5000
"""
RETURN = r"""
stdout:
type: str
description:
- Full C(helm) command stdout, in case you want to display it or examine the event log.
- As of Helm 4.2.1 success messages such as C(Login Succeeded) are printed to stdout
(see U(https://github.com/helm/helm/pull/32056)). On earlier versions they are printed to stderr.
returned: always
sample: 'Login Succeeded\n'
stdout_lines:
type: list
description: Full C(helm) command stdout, in case you want to display it or examine the event log
returned: always
stderr:
type: str
description:
- Full C(helm) command stderr, in case you want to display it or examine the event log.
- Please note that the helm binary may print messages to stderr even if the command is successful.
- On Helm versions earlier than 4.2.1, success messages such as C(Login Succeeded) are printed
here; as of Helm 4.2.1 they are printed to stdout (see U(https://github.com/helm/helm/pull/32056)).
returned: always
sample: 'Login Succeeded\n'
stderr_lines:
type: list
description: Full C(helm) command stderr, in case you want to display it or examine the event log
returned: always
command:
type: str
description: Full C(helm) command executed
returned: always
sample: '/usr/local/bin/helm registry login oci-registry.domain.example --username=admin --password-stdin --insecure'
failed:
type: bool
description: Indicate if the C(helm) command failed
returned: always
sample: false
"""
from ansible_collections.kubernetes.core.plugins.module_utils.helm import (
AnsibleHelmModule,
)
from ansible_collections.kubernetes.core.plugins.module_utils.version import (
LooseVersion,
)
def arg_spec():
return dict(
binary_path=dict(type="path", required=False),
host=dict(type="str", aliases=["registry_url"], required=True),
state=dict(default="present", choices=["present", "absent"], required=False),
insecure=dict(type="bool", default=False, required=False),
username=dict(type="str", aliases=["repo_username"], required=False),
password=dict(
type="str", aliases=["repo_password"], no_log=True, required=False
),
key_file=dict(type="path", required=False),
cert_file=dict(type="path", required=False),
ca_file=dict(type="path", required=False),
plain_http=dict(type="bool", default=False),
)
def login(
command,
host,
insecure,
username,
password,
key_file,
cert_file,
ca_file,
plain_http,
):
login_command = command + " registry login " + host
if username is not None and password is not None:
login_command += " --username=" + username + " --password-stdin"
if insecure:
login_command += " --insecure"
if key_file is not None:
login_command += " --key-file=" + key_file
if cert_file is not None:
login_command += " --cert-file=" + cert_file
if ca_file is not None:
login_command += " --ca-file=" + ca_file
if plain_http:
login_command += " --plain-http"
return login_command
def logout(command, host):
return command + " registry logout " + host
def main():
global module
module = AnsibleHelmModule(
argument_spec=arg_spec(),
required_together=[["username", "password"]],
supports_check_mode=True,
)
# Validate Helm version >=3.8.0
module.validate_helm_version(version="3.8.0")
changed = False
host = module.params.get("host")
state = module.params.get("state")
insecure = module.params.get("insecure")
username = module.params.get("username")
password = module.params.get("password")
key_file = module.params.get("key_file")
cert_file = module.params.get("cert_file")
ca_file = module.params.get("ca_file")
plain_http = module.params.get("plain_http")
helm_version = module.get_helm_version()
if plain_http:
if LooseVersion(helm_version) < LooseVersion("3.18.0"):
module.warn(
"plain_http option requires helm >= 3.18.0, current version is {0}".format(
helm_version
)
)
# reset option
plain_http = False
helm_cmd = module.get_helm_binary()
if state == "absent":
helm_cmd = logout(helm_cmd, host)
changed = True
elif state == "present":
helm_cmd = login(
helm_cmd,
host,
insecure,
username,
password,
key_file,
cert_file,
ca_file,
plain_http,
)
changed = True
if module.check_mode:
module.exit_json(changed=changed, command=helm_cmd)
rc, out, err = module.run_helm_command(
helm_cmd, data=password, fails_on_error=False
)
if rc != 0:
if state == "absent" and "Error: not logged in" in err:
changed = False
else:
module.fail_json(
msg="Failure when executing Helm command. Exited {0}.\nstdout: {1}\nstderr: {2}".format(
rc, out, err
),
stderr=err,
command=helm_cmd,
)
if LooseVersion(helm_version) >= LooseVersion("3.18.0") and state == "absent":
# https://github.com/ansible-collections/kubernetes.core/issues/944
module.warn(
"The helm_registry_auth is not idempotent with helm >= 3.18.0, always report a change."
)
module.exit_json(changed=changed, stdout=out, stderr=err, command=helm_cmd)
if __name__ == "__main__":
main()
+2 -23
View File
@@ -20,7 +20,7 @@ author:
- Lucas Boisserie (@LucasBoisserie)
requirements:
- "helm >= 3.0.0 (https://github.com/helm/helm/releases)"
- "helm (https://github.com/helm/helm/releases)"
- "yaml (https://pypi.org/project/PyYAML/)"
description:
@@ -119,13 +119,6 @@ options:
aliases: [ force ]
default: False
version_added: 2.4.0
insecure_skip_tls_verify:
description:
- Skip tls certificate checks for the repository url.
type: bool
default: False
aliases: [ skip_tls_certs_check ]
version_added: "5.3.0"
"""
EXAMPLES = r"""
@@ -233,7 +226,6 @@ def install_repository(
repository_password,
pass_credentials,
force_update,
insecure_skip_tls_verify,
):
install_command = command + " repo add " + repository_name + " " + repository_url
@@ -247,9 +239,6 @@ def install_repository(
if force_update:
install_command += " --force-update"
if insecure_skip_tls_verify:
install_command += " --insecure-skip-tls-verify"
return install_command
@@ -273,9 +262,6 @@ def argument_spec():
),
pass_credentials=dict(type="bool", default=False, no_log=True),
force_update=dict(type="bool", default=False, aliases=["force"]),
insecure_skip_tls_verify=dict(
type="bool", default=False, aliases=["skip_tls_certs_check"]
),
)
)
return arg_spec
@@ -295,21 +281,15 @@ def main():
if not IMP_YAML:
module.fail_json(msg=missing_required_lib("yaml"), exception=IMP_YAML_ERR)
# Validate Helm version >= 3.0.0
module.validate_helm_version()
changed = False
repo_name = module.params.get("repo_name")
repo_url = module.params.get("repo_url")
if repo_url:
repo_url = repo_url.rstrip("/")
repo_username = module.params.get("repo_username")
repo_password = module.params.get("repo_password")
repo_state = module.params.get("repo_state")
pass_credentials = module.params.get("pass_credentials")
force_update = module.params.get("force_update")
insecure_skip_tls_verify = module.params.get("insecure_skip_tls_verify")
helm_cmd = module.get_helm_binary()
@@ -328,10 +308,9 @@ def main():
repo_password,
pass_credentials,
force_update,
insecure_skip_tls_verify,
)
changed = True
elif repository_status["url"].rstrip("/") != repo_url:
elif repository_status["url"] != repo_url:
module.fail_json(
msg="Repository already have a repository named {0}".format(repo_name)
)
-51
View File
@@ -21,10 +21,6 @@ author:
description:
- Render chart templates to an output directory or as text of concatenated yaml documents.
requirements:
- "helm >= 3.0.0 (https://github.com/helm/helm/releases)"
- "yaml (https://pypi.org/project/PyYAML/)"
options:
binary_path:
description:
@@ -76,13 +72,6 @@ options:
- If the directory already exists, it will be overwritten.
required: false
type: path
insecure_registry:
description:
- Skip TLS certificate checks for the chart download
required: false
type: bool
default: false
version_added: 5.1.0
release_name:
description:
- Release name to use in rendered templates.
@@ -151,13 +140,6 @@ options:
- json
- file
version_added: 2.4.0
plain_http:
description:
- Use HTTP instead of HTTPS when working with OCI registries
- Requires Helm >= 3.13.0
type: bool
default: False
version_added: 6.1.0
"""
EXAMPLES = r"""
@@ -228,10 +210,6 @@ except ImportError:
from ansible.module_utils.basic import missing_required_lib
from ansible_collections.kubernetes.core.plugins.module_utils.helm import (
AnsibleHelmModule,
strip_registry_progress,
)
from ansible_collections.kubernetes.core.plugins.module_utils.version import (
LooseVersion,
)
@@ -243,7 +221,6 @@ def template(
dependency_update=None,
disable_hook=None,
output_dir=None,
insecure_registry=None,
show_only=None,
release_name=None,
release_namespace=None,
@@ -251,7 +228,6 @@ def template(
values_files=None,
include_crds=False,
set_values=None,
plain_http=False,
):
cmd += " template "
@@ -275,12 +251,6 @@ def template(
if output_dir:
cmd += " --output-dir=" + output_dir
if insecure_registry:
cmd += " --insecure-skip-tls-verify"
if plain_http:
cmd += " --plain-http"
if show_only:
for template in show_only:
cmd += " -s " + template
@@ -319,14 +289,12 @@ def main():
include_crds=dict(type="bool", default=False),
release_name=dict(type="str", aliases=["name"]),
output_dir=dict(type="path"),
insecure_registry=dict(type="bool", default=False),
release_namespace=dict(type="str"),
release_values=dict(type="dict", default={}, aliases=["values"]),
show_only=dict(type="list", default=[], elements="str"),
values_files=dict(type="list", default=[], elements="str"),
update_repo_cache=dict(type="bool", default=False),
set_values=dict(type="list", elements="dict"),
plain_http=dict(type="bool", default=False),
),
supports_check_mode=True,
)
@@ -340,32 +308,18 @@ def main():
include_crds = module.params.get("include_crds")
release_name = module.params.get("release_name")
output_dir = module.params.get("output_dir")
insecure_registry = module.params.get("insecure_registry")
show_only = module.params.get("show_only")
release_namespace = module.params.get("release_namespace")
release_values = module.params.get("release_values")
values_files = module.params.get("values_files")
update_repo_cache = module.params.get("update_repo_cache")
set_values = module.params.get("set_values")
plain_http = module.params.get("plain_http")
if not IMP_YAML:
module.fail_json(msg=missing_required_lib("yaml"), exception=IMP_YAML_ERR)
# Validate Helm version >=3.0.0
module.validate_helm_version()
helm_cmd = module.get_helm_binary()
if plain_http:
helm_version = module.get_helm_version()
if LooseVersion(helm_version) < LooseVersion("3.13.0"):
module.fail_json(
msg="plain_http requires helm >= 3.13.0, current version is {0}".format(
helm_version
)
)
if update_repo_cache:
update_cmd = helm_cmd + " repo update"
module.run_helm_command(update_cmd)
@@ -383,21 +337,16 @@ def main():
disable_hook=disable_hook,
release_name=release_name,
output_dir=output_dir,
insecure_registry=insecure_registry,
release_namespace=release_namespace,
release_values=release_values,
show_only=show_only,
values_files=values_files,
include_crds=include_crds,
set_values=set_values_args,
plain_http=plain_http,
)
if not check_mode:
rc, out, err = module.run_helm_command(tmpl_cmd)
# 'stdout' is documented to hold the rendered templates, so keep helm's
# OCI registry progress messages out of it.
out = strip_registry_progress(out)
else:
out = err = ""
rc = 0
+12 -49
View File
@@ -181,18 +181,17 @@ options:
- This parameter can be used with C(label_selectors) to restrict the resources to be deleted.
type: bool
default: false
version_added: 3.0.0
version_added: 2.5.0
aliases:
- all
hidden_fields:
description:
- Hide fields matching this option in the result
- An example might be C(hidden_fields=[metadata.managedFields])
or V(hidden_fields=[spec.containers[0].env[3].value])
or V(hidden_fields=[metadata.annotations[kubectl.kubernetes.io/last-applied-configuration]])
- Only field definitions that don't reference list items are supported (so V(spec.containers[0]) would not work)
type: list
elements: str
version_added: 3.0.0
version_added: 2.5.0
requirements:
- "python >= 3.9"
@@ -383,24 +382,28 @@ result:
contains:
api_version:
description: The versioned schema of this representation of an object.
returned: when O(resource_definition) or O(src) contains a single object.
returned: success
type: str
kind:
description: Represents the REST resource this object represents.
returned: when O(resource_definition) or O(src) contains a single object.
returned: success
type: str
metadata:
description: Standard object metadata. Includes name, namespace, annotations, labels, etc.
returned: when O(resource_definition) or O(src) contains a single object.
returned: success
type: complex
spec:
description: Specific attributes of the object. Will vary based on the I(api_version) and I(kind).
returned: when O(resource_definition) or O(src) contains a single object.
returned: success
type: complex
status:
description: Current status details for the object.
returned: when O(resource_definition) or O(src) contains a single object.
returned: success
type: complex
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
@@ -410,46 +413,6 @@ result:
description: error while trying to create/delete the object.
returned: error
type: complex
results:
description: An array of created, patched, or otherwise present objects.
returned: when O(resource_definition) or O(src) contains a list of objects.
type: complex
contains:
api_version:
description: The versioned schema of this representation of an object.
returned: when O(resource_definition) or O(src) contains a single object.
type: str
kind:
description: Represents the REST resource this object represents.
returned: when O(resource_definition) or O(src) contains a single object.
type: str
metadata:
description: Standard object metadata. Includes name, namespace, annotations, labels, etc.
returned: when O(resource_definition) or O(src) contains a single object.
type: complex
spec:
description: Specific attributes of the object. Will vary based on the I(api_version) and I(kind).
returned: when O(resource_definition) or O(src) contains a single object.
type: complex
status:
description: Current status details for the object.
returned: when O(resource_definition) or O(src) contains a single object.
type: complex
duration:
description: elapsed time of task in seconds
returned: when C(wait) is true
type: int
sample: 48
error:
description: error while trying to create/delete the object.
returned: error
type: complex
method:
description:
- The method used to deploy the resource.
returned: success
type: str
sample: create
"""
import copy
+1 -15
View File
@@ -76,22 +76,9 @@ options:
- This option is ignored when I(content) is set or when I(state) is set to C(from_pod).
type: bool
default: False
copy_timeout:
description:
- Maximum time in seconds to spend streaming the archive to the pod and waiting for the remote
C(tar) process to finish extracting it.
- Raise this when copying large files over a slow connection.
- This option is ignored when I(state) is set to C(from_pod).
type: int
default: 300
version_added: 6.6.0
notes:
- the tar binary is required on the container when copying from local filesystem to pod.
- a POSIX shell at C(/bin/sh) and C(head) are also used, when present, to bound the archive
sent to the container so that the module can confirm the copy finished. Without them the
copy still runs but completion cannot be verified, and a warning is emitted.
- the (init) container has to be started before you copy files or directories to it.
"""
EXAMPLES = r"""
@@ -152,7 +139,7 @@ result:
import copy
from ansible.module_utils.common.text.converters import to_native
from ansible.module_utils._text import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
AnsibleModule,
)
@@ -192,7 +179,6 @@ def argspec():
"choices": ["to_pod", "from_pod"],
}
argument_spec["no_preserve"] = {"type": "bool", "default": False}
argument_spec["copy_timeout"] = {"type": "int", "default": 300}
return argument_spec
+56 -84
View File
@@ -47,7 +47,7 @@ options:
- This option has effect only when C(state) is set to I(drain).
type: list
elements: str
version_added: 3.0.0
version_added: 2.5.0
aliases:
- label_selectors
delete_options:
@@ -106,8 +106,7 @@ EXAMPLES = r"""
kubernetes.core.k8s_drain:
state: drain
name: foo
delete_options:
force: yes
force: yes
- name: Drain node "foo", but abort if there are pods not managed by a ReplicationController, Job, or DaemonSet, and use a grace period of 15 minutes.
kubernetes.core.k8s_drain:
@@ -144,12 +143,11 @@ result:
"""
import copy
import json
import time
import traceback
from datetime import datetime
from ansible.module_utils.common.text.converters import to_native
from ansible.module_utils._text import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
AnsibleModule,
)
@@ -189,17 +187,6 @@ except ImportError:
HAS_EVICTION_API = False
def format_dynamic_api_exc(exc):
if exc.body:
if exc.headers and exc.headers.get("Content-Type") == "application/json":
message = json.loads(exc.body).get("message")
if message:
return message
return exc.body
else:
return "%s Reason: %s" % (exc.status, exc.reason)
def filter_pods(pods, force, ignore_daemonset, delete_emptydir_data):
k8s_kind_mirror = "kubernetes.io/config.mirror"
daemonSet, unmanaged, mirror, localStorage, to_delete = [], [], [], [], []
@@ -214,23 +201,23 @@ def filter_pods(pods, force, ignore_daemonset, delete_emptydir_data):
to_delete.append((pod.metadata.namespace, pod.metadata.name))
continue
# Check replicated Pod
owner_ref = pod.metadata.owner_references or []
has_local_storage = bool(
pod.spec.volumes and any(vol.empty_dir for vol in pod.spec.volumes)
)
is_daemonset_managed = any(owner.kind == "DaemonSet" for owner in owner_ref)
if is_daemonset_managed:
daemonSet.append((pod.metadata.namespace, pod.metadata.name))
elif has_local_storage:
# Pod with local storage cannot be deleted
if pod.spec.volumes and any(vol.empty_dir for vol in pod.spec.volumes):
localStorage.append((pod.metadata.namespace, pod.metadata.name))
elif not owner_ref:
continue
# Check replicated Pod
owner_ref = pod.metadata.owner_references
if not owner_ref:
unmanaged.append((pod.metadata.namespace, pod.metadata.name))
else:
to_delete.append((pod.metadata.namespace, pod.metadata.name))
for owner in owner_ref:
if owner.kind == "DaemonSet":
daemonSet.append((pod.metadata.namespace, pod.metadata.name))
else:
to_delete.append((pod.metadata.namespace, pod.metadata.name))
warnings, errors, info = [], [], []
warnings, errors = [], []
if unmanaged:
pod_names = ",".join([pod[0] + "/" + pod[1] for pod in unmanaged])
if not force:
@@ -242,7 +229,7 @@ def filter_pods(pods, force, ignore_daemonset, delete_emptydir_data):
)
else:
# Pod not managed will be deleted as 'force' is true
info.append(
warnings.append(
"Deleting Pods not managed by ReplicationController, ReplicaSet, Job, DaemonSet or StatefulSet: {0}.".format(
pod_names
)
@@ -264,7 +251,7 @@ def filter_pods(pods, force, ignore_daemonset, delete_emptydir_data):
"cannot delete Pods with local storage: {0}.".format(pod_names)
)
else:
info.append("Deleting Pods with local storage: {0}.".format(pod_names))
warnings.append("Deleting Pods with local storage: {0}.".format(pod_names))
for pod in localStorage:
to_delete.append((pod[0], pod[1]))
@@ -278,8 +265,8 @@ def filter_pods(pods, force, ignore_daemonset, delete_emptydir_data):
)
)
else:
info.append("Ignoring DaemonSet-managed Pods: {0}.".format(pod_names))
return to_delete, warnings, errors, info
warnings.append("Ignoring DaemonSet-managed Pods: {0}.".format(pod_names))
return to_delete, warnings, errors
class K8sDrainAnsible(object):
@@ -304,19 +291,16 @@ class K8sDrainAnsible(object):
return (datetime.now() - start).seconds
response = None
pod = None
pod = pods.pop()
while (_elapsed_time() < wait_timeout or wait_timeout == 0) and pods:
if not pod:
pod = pods[-1]
pod = pods.pop()
try:
response = self._api_instance.read_namespaced_pod(
namespace=pod[0], name=pod[1]
)
if not response or response.spec.node_name != self._module.params.get(
"name"
):
if not response:
pod = None
del pods[-1]
time.sleep(wait_sleep)
except ApiException as exc:
if exc.reason != "Not Found":
@@ -324,7 +308,6 @@ class K8sDrainAnsible(object):
msg="Exception raised: {0}".format(exc.reason)
)
pod = None
del pods[-1]
except Exception as e:
self._module.fail_json(msg="Exception raised: {0}".format(to_native(e)))
if not pods:
@@ -334,25 +317,24 @@ class K8sDrainAnsible(object):
def evict_pods(self, pods):
for namespace, name in pods:
try:
if not self._module.check_mode:
if self._drain_options.get("disable_eviction"):
self._api_instance.delete_namespaced_pod(
name=name, namespace=namespace, body=self._delete_options
)
else:
body = v1_eviction(
delete_options=self._delete_options,
metadata=V1ObjectMeta(name=name, namespace=namespace),
)
self._api_instance.create_namespaced_pod_eviction(
name=name, namespace=namespace, body=body
)
if self._drain_options.get("disable_eviction"):
self._api_instance.delete_namespaced_pod(
name=name, namespace=namespace, body=self._delete_options
)
else:
body = v1_eviction(
delete_options=self._delete_options,
metadata=V1ObjectMeta(name=name, namespace=namespace),
)
self._api_instance.create_namespaced_pod_eviction(
name=name, namespace=namespace, body=body
)
self._changed = True
except ApiException as exc:
if exc.reason != "Not Found":
self._module.fail_json(
msg="Failed to delete pod {0}/{1} due to: {2}".format(
namespace, name, to_native(format_dynamic_api_exc(exc))
namespace, name, exc.reason
)
)
except Exception as exc:
@@ -363,7 +345,11 @@ class K8sDrainAnsible(object):
)
def list_pods(self):
params = {"field_selector": "spec.nodeName=" + self._module.params.get("name")}
params = {
"field_selector": "spec.nodeName={name}".format(
name=self._module.params.get("name")
)
}
pod_selectors = self._module.params.get("pod_selectors")
if pod_selectors:
params["label_selector"] = ",".join(pod_selectors)
@@ -373,8 +359,7 @@ class K8sDrainAnsible(object):
# Mark node as unschedulable
result = []
if not node_unschedulable:
if not self._module.check_mode:
self.patch_node(unschedulable=True)
self.patch_node(unschedulable=True)
result.append(
"node {0} marked unschedulable.".format(self._module.params.get("name"))
)
@@ -389,8 +374,7 @@ class K8sDrainAnsible(object):
def _revert_node_patch():
if self._changed:
self._changed = False
if not self._module.check_mode:
self.patch_node(unschedulable=False)
self.patch_node(unschedulable=False)
try:
pod_list = self.list_pods()
@@ -400,7 +384,7 @@ class K8sDrainAnsible(object):
delete_emptydir_data = self._drain_options.get(
"delete_emptydir_data", False
)
pods, warnings, errors, info = filter_pods(
pods, warnings, errors = filter_pods(
pod_list.items, force, ignore_daemonset, delete_emptydir_data
)
if errors:
@@ -430,25 +414,17 @@ class K8sDrainAnsible(object):
if pods:
self.evict_pods(pods)
number_pod = len(pods)
if self._module.check_mode:
result.append(
"Would have deleted {0} Pod(s) from node if not in check mode.".format(
number_pod
)
if self._drain_options.get("wait_timeout") is not None:
warn = self.wait_for_pod_deletion(
pods,
self._drain_options.get("wait_timeout"),
self._drain_options.get("wait_sleep"),
)
else:
wait_timeout = self._drain_options.get("wait_timeout")
wait_sleep = self._drain_options.get("wait_sleep")
if wait_timeout is not None:
warn = self.wait_for_pod_deletion(pods, wait_timeout, wait_sleep)
if warn:
warnings.append(warn)
result.append("{0} Pod(s) deleted from node.".format(number_pod))
if warn:
warnings.append(warn)
result.append("{0} Pod(s) deleted from node.".format(number_pod))
if warnings:
for warning in warnings:
self._module.warn(warning)
for line in info:
self._module.debug(line)
return dict(result=" ".join(result), warnings=warnings)
return dict(result=" ".join(result))
def patch_node(self, unschedulable):
@@ -489,8 +465,7 @@ class K8sDrainAnsible(object):
self._module.exit_json(
result="node {0} already marked unschedulable.".format(name)
)
if not self._module.check_mode:
self.patch_node(unschedulable=True)
self.patch_node(unschedulable=True)
result["result"] = "node {0} marked unschedulable.".format(name)
self._changed = True
@@ -499,8 +474,7 @@ class K8sDrainAnsible(object):
self._module.exit_json(
result="node {0} already marked schedulable.".format(name)
)
if not self._module.check_mode:
self.patch_node(unschedulable=False)
self.patch_node(unschedulable=False)
result["result"] = "node {0} marked schedulable.".format(name)
self._changed = True
@@ -543,9 +517,7 @@ def argspec():
def main():
module = AnsibleK8SModule(
module_class=AnsibleModule, argument_spec=argspec(), supports_check_mode=True
)
module = AnsibleK8SModule(module_class=AnsibleModule, argument_spec=argspec())
if not HAS_EVICTION_API:
module.fail_json(
+2 -9
View File
@@ -118,7 +118,7 @@ result:
type: int
version_added: 2.2.0
return_code:
description: The command status code. This attribute is deprecated and will be removed in version 7.0.0. Use RV(result.rc) instead.
description: The command status code. This attribute is deprecated and will be removed in a future release. Please use rc instead.
type: int
"""
@@ -131,7 +131,7 @@ except ImportError:
# ImportError are managed by the common module already.
pass
from ansible.module_utils.common.text.converters import to_native
from ansible.module_utils._text import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
AnsibleModule,
)
@@ -219,13 +219,6 @@ def execute_module(module, client):
else:
rc = int(err["details"]["causes"][0]["message"])
# Add deprecation warning for return_code return value
module.deprecate(
"The 'return_code' return value is deprecated and will be removed in version 7.0.0. Use 'rc' instead.",
version="7.0.0",
collection_name="kubernetes.core",
)
module.exit_json(
# Some command might change environment, but ultimately failing at end
changed=True,
+12 -58
View File
@@ -48,20 +48,10 @@ options:
description:
- Hide fields matching any of the field definitions in the result
- An example might be C(hidden_fields=[metadata.managedFields])
or V(hidden_fields=[spec.containers[0].env[3].value])
or V(hidden_fields=[metadata.annotations[kubectl.kubernetes.io/last-applied-configuration]])
- Only field definitions that don't reference list items are supported (so V(spec.containers[0]) would not work)
type: list
elements: str
version_added: 3.0.0
metadata_only:
description:
- Request metadata only response from the Kubernetes API server.
- This feature is useful for clients that only need to check for the existence of an object,
- or that only need to read its metadata.
- It can significantly reduce the size of the response from the API server.
type: bool
default: false
version_added: 6.6.0
version_added: 2.5.0
extends_documentation_fragment:
- kubernetes.core.k8s_auth_options
@@ -129,27 +119,6 @@ EXAMPLES = r"""
namespace: default
wait_sleep: 10
wait_timeout: 360
- name: Wait for OpenShift bootstrap to complete
kubernetes.core.k8s_info:
api_version: v1
kind: ConfigMap
name: bootstrap
namespace: kube-system
register: ocp_bootstrap_status
until: >
ocp_bootstrap_status.resources is defined and
(ocp_bootstrap_status.resources | length > 0) and
(ocp_bootstrap_status.resources[0].data.status is defined) and
(ocp_bootstrap_status.resources[0].data.status == 'complete')
retries: 60
delay: 15
- name: Get a list of all pods metadata only
kubernetes.core.k8s_info:
kind: Pod
metadata_only: true
register: pod_metadata_list
"""
RETURN = r"""
@@ -194,8 +163,6 @@ from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule impo
)
from ansible_collections.kubernetes.core.plugins.module_utils.args_common import (
AUTH_ARG_SPEC,
METADATA_ONLY_HEADER_VALUES,
METADATA_ONLY_HEADERS_SPEC,
WAIT_ARG_SPEC,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
@@ -233,16 +200,15 @@ def argspec():
args = copy.deepcopy(AUTH_ARG_SPEC)
args.update(WAIT_ARG_SPEC)
args.update(
{
"kind": {"required": True},
"api_version": {"default": "v1", "aliases": ["api", "version"]},
"name": {},
"namespace": {},
"label_selectors": {"type": "list", "elements": "str", "default": []},
"field_selectors": {"type": "list", "elements": "str", "default": []},
"hidden_fields": {"type": "list", "elements": "str"},
"metadata_only": {"type": "bool", "default": False},
}
dict(
kind=dict(required=True),
api_version=dict(default="v1", aliases=["api", "version"]),
name=dict(),
namespace=dict(),
label_selectors=dict(type="list", elements="str", default=[]),
field_selectors=dict(type="list", elements="str", default=[]),
hidden_fields=dict(type="list", elements="str"),
)
)
return args
@@ -251,20 +217,8 @@ def main():
module = AnsibleK8SModule(
module_class=AnsibleModule, argument_spec=argspec(), supports_check_mode=True
)
metadata_only_headers = {}
if module.params["metadata_only"]:
metadata_only_headers = copy.deepcopy(METADATA_ONLY_HEADERS_SPEC)
metadata_only_headers.update(
{"accept": METADATA_ONLY_HEADER_VALUES["partial_object_list"]}
)
if module.params["name"]:
metadata_only_headers.update(
{"accept": METADATA_ONLY_HEADER_VALUES["partial_object"]}
)
try:
client = get_api_client(module, **metadata_only_headers)
client = get_api_client(module)
svc = K8sService(client, module)
execute_module(module, svc)
except CoreException as e:
+3 -14
View File
@@ -33,14 +33,6 @@ options:
aliases:
- api
- version
hidden_fields:
description:
- List of fields to hide from the diff output.
- This is useful for fields that are not relevant to the patch operation, such as `metadata.managedFields`.
type: list
elements: str
default: []
version_added: 6.1.0
kind:
description:
- Use to specify an object model.
@@ -135,8 +127,8 @@ error:
import copy
import traceback
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import missing_required_lib
from ansible.module_utils.common.text.converters import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
AnsibleModule,
)
@@ -155,7 +147,6 @@ from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions imp
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.service import (
diff_objects,
hide_fields,
)
from ansible_collections.kubernetes.core.plugins.module_utils.k8s.waiter import (
get_waiter,
@@ -183,7 +174,6 @@ JSON_PATCH_ARGS = {
"namespace": {"type": "str"},
"name": {"type": "str", "required": True},
"patch": {"type": "list", "required": True, "elements": "dict"},
"hidden_fields": {"type": "list", "elements": "str", "default": []},
}
@@ -213,7 +203,6 @@ def execute_module(module, client):
namespace = module.params.get("namespace")
patch = module.params.get("patch")
hidden_fields = module.params.get("hidden_fields")
wait = module.params.get("wait")
wait_sleep = module.params.get("wait_sleep")
wait_timeout = module.params.get("wait_timeout")
@@ -271,13 +260,13 @@ def execute_module(module, client):
module.fail_json(msg=msg, error=to_native(exc), status="", reason="")
success = True
result = {"result": hide_fields(obj, hidden_fields)}
result = {"result": obj}
if wait and not module.check_mode:
waiter = get_waiter(client, resource, condition=wait_condition)
success, result["result"], result["duration"] = waiter.wait(
wait_timeout, wait_sleep, name, namespace
)
match, diffs = diff_objects(existing.to_dict(), obj, hidden_fields)
match, diffs = diff_objects(existing.to_dict(), obj)
result["changed"] = not match
if module._diff:
result["diff"] = diffs
+1 -3
View File
@@ -168,9 +168,7 @@ def perform_action(svc, resource):
module.params["kind"],
resource["metadata"]["name"],
)
if warn:
module.warn(warn)
result = {"changed": False}
result = {"changed": False, "warnings": [warn]}
return result
if module.params["kind"] == "Deployment":
+3 -5
View File
@@ -149,7 +149,7 @@ except ImportError:
# Handled in module setup
pass
from ansible.module_utils.common.text.converters import to_native
from ansible.module_utils._text import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
AnsibleModule,
)
@@ -243,12 +243,10 @@ def execute_module(client, module):
module.fail_json(msg=error, **return_attributes)
def _continue_or_exit(warn):
if warn:
module.warn(warn)
if multiple_scale:
return_attributes["results"].append({"changed": False})
return_attributes["results"].append({"warning": warn, "changed": False})
else:
module.exit_json(**return_attributes)
module.exit_json(warning=warn, **return_attributes)
for existing in existing_items:
if kind.lower() == "job":
-10
View File
@@ -36,7 +36,6 @@ options:
- If more than one C(merge_type) is given, the merge_types will be tried in order
- This defaults to C(['strategic-merge', 'merge']), which is ideal for using the same parameters
on resource kinds that combine Custom Resources and built-in resources.
- I(merge_type=json) has been deprecated and will be removed in version 7.0.0. Use M(kubernetes.core.k8s_json_patch) instead.
choices:
- json
- merge
@@ -252,15 +251,6 @@ def main():
supports_check_mode=True,
)
# Add deprecation warning for merge_type=json
merge_type = module.params.get("merge_type")
if merge_type and "json" in merge_type:
module.deprecate(
"The 'merge_type=json' option is deprecated and will be removed in version 7.0.0. Use the 'kubernetes.core.k8s_json_patch' module instead.",
version="7.0.0",
collection_name="kubernetes.core",
)
try:
client = get_api_client(module=module)
svc = K8sService(client, module)
+1 -1
View File
@@ -126,7 +126,7 @@ result:
import copy
from ansible.module_utils.common.text.converters import to_native
from ansible.module_utils._text import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
AnsibleModule,
)
-490
View File
@@ -1,490 +0,0 @@
#!/usr/bin/python
#
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r"""
---
module: kubeconfig
short_description: Generate, update, and optionally write Kubernetes kubeconfig files
version_added: "6.5.0"
author: "Youssef Khalid Ali (@YoussefKhalidAli)"
description:
- Build, update, and manage Kubernetes kubeconfig files using structured input.
- Supports loading an existing kubeconfig file and merging clusters, users, and contexts.
- Can optionally write the resulting kubeconfig to a destination path.
- Ensures idempotent behavior by only updating files when changes occur.
requirements:
- "PyYAML >= 5.1"
notes:
- Input data is merged by resource name (cluster, user, context).
- Updates under O(clusters), O(users), and O(contexts) are matched by C(name) against the kubeconfig loaded from O(path).
- For an existing C(name), each entry's C(behavior) suboption controls the update.
- The default is V(merge), which merges nested C(cluster), C(user), and C(context) data so unspecified keys are preserved.
- With V(replace), the previous entry for that name is dropped and only the new definition is used.
- With V(keep), the existing entry is left unchanged.
- With V(remove), the existing entry is deleted from the kubeconfig entirely. If no entry with that name exists, the operation is silently skipped.
- This can be used to move kubeconfig files to a different location with different content.
- This module does not validate cluster connectivity or authentication.
- The module supports C(check_mode) and will not write files when enabled.
- The structure follows standard Kubernetes kubeconfig format as defined in the Kubernetes documentation.
- Tokens and sensitive data should be protected using ansible-vault or environment variables.
options:
path:
description:
- Path to an existing kubeconfig file to load and merge from.
- If the file does not exist, a new kubeconfig will be created.
- This becomes the default destination if O(dest) is not specified.
type: str
required: true
dest:
description:
- Destination path where the final kubeconfig should be written.
- If not specified, the kubeconfig will be saved to O(path).
- Allows copying and modifying a kubeconfig to a new location.
type: str
required: false
clusters:
description:
- List of cluster definitions to merge into the kubeconfig.
- Each cluster is identified by its C(name).
- When C(name) matches an existing cluster, the default C(behavior) is V(merge).
- See the C(behavior) suboption for V(replace), V(keep), and V(remove).
type: list
elements: dict
required: false
default: []
suboptions:
name:
description:
- Unique name identifier for the cluster.
type: str
required: true
behavior:
description:
- How to handle merging if a cluster with this name already exists.
- C(merge) - Update only the specified fields, preserve others (default).
- C(replace) - Replace the entire cluster definition.
- C(keep) - Keep existing cluster, skip this entry.
- C(remove) - Remove the cluster entry entirely. Silently skipped if the entry does not exist.
type: str
choices: ['merge', 'replace', 'keep', 'remove']
default: merge
cluster:
description:
- Cluster configuration details.
- Not required when C(behavior) is V(remove).
type: dict
suboptions:
server:
description:
- Kubernetes API server URL (e.g., C(https://k8s.example.com:6443)).
type: str
required: true
certificate-authority:
description:
- Path to a CA certificate file for validating the API server certificate.
type: str
certificate-authority-data:
description:
- Base64 encoded CA certificate data.
- Use this instead of C(certificate-authority) for embedded certificates.
type: str
insecure-skip-tls-verify:
description:
- If true, the server's certificate will not be validated.
type: bool
proxy-url:
description:
- Optional proxy URL for cluster connections.
type: str
tls-server-name:
description:
- Server name to use for server certificate validation.
type: str
users:
description:
- List of user authentication configurations.
- Each user is identified by its C(name).
- When C(name) matches an existing user, the default C(behavior) is V(merge).
- See the C(behavior) suboption for V(replace), V(keep), and V(remove).
type: list
elements: dict
required: false
default: []
suboptions:
name:
description:
- Unique name identifier for the user.
type: str
required: true
behavior:
description:
- How to handle merging if a user with this name already exists.
- C(merge) - Update only the specified fields, preserve others (default).
- C(replace) - Replace the entire user definition.
- C(keep) - Keep existing user, skip this entry.
- C(remove) - Remove the user entry entirely. Silently skipped if the entry does not exist.
type: str
choices: ['merge', 'replace', 'keep', 'remove']
default: merge
user:
description:
- User authentication configuration.
- Not required when C(behavior) is V(remove).
type: dict
suboptions:
token:
description:
- Bearer token for authentication.
type: str
username:
description:
- Username for basic authentication.
type: str
password:
description:
- Password for basic authentication.
type: str
client-certificate:
description:
- Path to client certificate file.
- Used for certificate-based authentication.
type: str
client-key:
description:
- Path to client private key file.
- Must be provided with C(client-certificate).
type: str
client-certificate-data:
description:
- Base64 encoded client certificate.
- Use instead of C(client-certificate) for embedded certificates.
type: str
client-key-data:
description:
- Base64 encoded client private key.
- Use instead of C(client-key) for embedded keys.
type: str
auth-provider:
description:
- Authentication provider configuration (e.g., for GCP, Azure).
type: dict
exec:
description:
- Exec-based credential plugin configuration.
- Used for external authentication providers.
type: dict
contexts:
description:
- List of context definitions linking users and clusters.
- Each context is identified by its C(name).
- When C(name) matches an existing context, the default C(behavior) is V(merge).
- See the C(behavior) suboption for V(replace), V(keep), and V(remove).
type: list
elements: dict
required: false
default: []
suboptions:
name:
description:
- Unique name identifier for the context.
type: str
required: true
behavior:
description:
- How to handle merging if a context with this name already exists.
- C(merge) - Update only the specified fields, preserve others (default).
- C(replace) - Replace the entire context definition.
- C(keep) - Keep existing context, skip this entry.
- C(remove) - Remove the context entry entirely. Silently skipped if the entry does not exist.
type: str
choices: ['merge', 'replace', 'keep', 'remove']
default: merge
context:
description:
- Context configuration linking cluster and user.
- Not required when C(behavior) is V(remove).
type: dict
suboptions:
cluster:
description:
- Name of the cluster to use (must match a cluster name in O(clusters)).
type: str
required: true
user:
description:
- Name of the user to authenticate as (must match a user name in O(users)).
type: str
required: true
namespace:
description:
- Default namespace to use for this context.
- If not specified, defaults to C(default).
type: str
preferences:
description:
- Kubeconfig preferences.
- Used for client-side settings like color output, default editor, etc.
type: dict
required: false
default: {}
current_context:
description:
- Name of the context to set as current/active.
- This context will be used by default when using kubectl.
- Must match one of the context names defined in O(contexts).
type: str
required: false
seealso:
- name: Kubernetes kubeconfig documentation
description: Official Kubernetes documentation for kubeconfig files
link: https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/
- name: kubectl config documentation
description: kubectl commands for working with kubeconfig files
link: https://kubernetes.io/docs/reference/kubectl/generated/kubectl_config/
"""
EXAMPLES = r"""
# Create a new kubeconfig file with a single cluster
- name: Create basic kubeconfig
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
clusters:
- name: production-cluster
cluster:
server: https://prod.k8s.example.com:6443
certificate-authority-data: LS0tLS1CRUdJTi...
users:
- name: admin-user
user:
token: eyJhbGciOiJSUzI1NiIsImtpZCI6IiJ9...
contexts:
- name: prod-admin
context:
cluster: production-cluster
user: admin-user
namespace: production
current_context: prod-admin
- name: Add a second cluster to an existing kubeconfig without touching other entries
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
clusters:
- name: staging-cluster
cluster:
server: https://staging.k8s.example.com:6443
insecure-skip-tls-verify: true
users:
- name: staging-user
user:
client-certificate: /path/to/staging.crt
client-key: /path/to/staging.key
contexts:
- name: staging-admin
context:
cluster: staging-cluster
user: staging-user
namespace: staging
- name: Update only the token for an existing user, preserving all other user fields
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
users:
- name: admin-user
behavior: merge
user:
token: "{{ new_admin_token }}"
- name: Replace a cluster definition entirely.
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
clusters:
- name: production-cluster
behavior: replace
cluster:
server: https://new-prod.k8s.example.com:6443
certificate-authority-data: LS0tLS1CRUdJTi...
- name: Remove a decommissioned cluster, user, and context
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
clusters:
- name: old-cluster
behavior: remove
users:
- name: old-user
behavior: remove
contexts:
- name: old-context
behavior: remove
- name: Switch the active context
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
current_context: staging-admin
- name: Copy a kubeconfig to a new location with an additional cluster merged in
kubernetes.core.kubeconfig:
path: /home/user/.kube/config
dest: /home/user/.kube/config-ci
clusters:
- name: ci-cluster
cluster:
server: https://ci.k8s.example.com:6443
insecure-skip-tls-verify: true
"""
RETURN = r"""
kubeconfig:
description: The complete kubeconfig data structure.
type: dict
returned: always
dest:
description: The path where the kubeconfig was written.
type: str
returned: always
sample: /home/user/.kube/config
"""
import os
import traceback
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.common.text.converters import to_native
from ansible_collections.kubernetes.core.plugins.module_utils.args_common import (
extract_sensitive_values_from_kubeconfig,
)
from ansible_collections.kubernetes.core.plugins.module_utils.kubeconfig import (
hash_data,
load_yaml_file,
merge_by_name,
write_file,
)
try:
import yaml
IMP_YAML = True
IMP_YAML_ERR = None
except ImportError:
IMP_YAML = False
IMP_YAML_ERR = traceback.format_exc()
def run_module():
module_args = dict(
path=dict(type="str", required=True),
dest=dict(type="str", required=False),
clusters=dict(type="list", elements="dict", required=False, default=[]),
users=dict(type="list", elements="dict", required=False, default=[]),
contexts=dict(type="list", elements="dict", required=False, default=[]),
preferences=dict(type="dict", required=False, default={}),
current_context=dict(type="str", required=False),
)
module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)
path = module.params["path"]
dest = module.params["dest"] or path
clusters_input = module.params["clusters"]
users_input = module.params["users"]
contexts_input = module.params["contexts"]
preferences = module.params["preferences"]
current_context = module.params["current_context"]
# Load existing kubeconfig
try:
if not IMP_YAML:
module.fail_json(
msg=missing_required_lib("pyyaml"),
exception=IMP_YAML_ERR,
)
existing = load_yaml_file(path) if path else {}
except Exception as e:
module.fail_json(
msg="Failed to load existing kubeconfig: %s" % to_native(e),
exception=traceback.format_exc(),
)
clusters = merge_by_name(existing.get("clusters", []), clusters_input)
users = merge_by_name(existing.get("users", []), users_input)
contexts = merge_by_name(existing.get("contexts", []), contexts_input)
# Build final kubeconfig
kubeconfig = {
"apiVersion": "v1",
"kind": "Config",
"preferences": preferences or existing.get("preferences", {}),
"clusters": clusters,
"users": users,
"contexts": contexts,
"current-context": current_context or existing.get("current-context") or "",
}
changed = False
old_data = {}
if os.path.exists(dest):
try:
with open(dest, "r") as f:
old_data = yaml.safe_load(f) or {}
except Exception as e:
module.fail_json(
msg="Failed to read destination file: %s" % to_native(e),
exception=traceback.format_exc(),
)
old_hash = hash_data(old_data)
new_hash = hash_data(kubeconfig)
if old_hash != new_hash:
if not module.check_mode:
try:
write_file(dest, kubeconfig)
except Exception as e:
module.fail_json(
msg="Failed to write kubeconfig: %s" % to_native(e),
exception=traceback.format_exc(),
)
changed = True
if isinstance(kubeconfig, dict):
module.no_log_values.update(
extract_sensitive_values_from_kubeconfig(kubeconfig)
)
module.exit_json(
changed=changed,
kubeconfig=kubeconfig,
dest=dest,
msg=(
"Kubeconfig file has been updated."
if changed
else "Kubeconfig file is already up to date."
),
)
def main():
run_module()
if __name__ == "__main__":
main()
-47
View File
@@ -1,47 +0,0 @@
# SonarCloud project configuration for kubernetes.core
# Parameters: https://docs.sonarqube.org/latest/analysis/analysis-parameters/
sonar.projectKey=ansible-collections_kubernetes.core
sonar.organization=ansible-collections
sonar.sources=.
sonar.projectName=kubernetes.core
sonar.python.coverage.reportPaths=coverage.xml
sonar.tests=tests/unit,tests/integration
sonar.python.version=3.12
sonar.newCode.referenceBranch=stable-6
sonar.exclusions=tests/**,.tox/**
# Exclude test code from copy/paste detection. 'sonar.exclusions' above only
# filters the *source* set (it disambiguates 'sonar.sources=.' from
# 'sonar.tests'), so test files are still indexed as tests and still scored for
# duplication. Unit tests here are unittest.TestCase classes: every class needs
# its own setUp, and per-case arrange/assert blocks are deliberately repeated so
# a failing test reads on its own. Because SonarCloud scores only *new code* on
# a pull request, any PR adding cases to an already-repetitive test module
# inherits duplication accrued across earlier PRs. Production code under
# plugins/ stays fully covered by duplication analysis.
sonar.cpd.exclusions=tests/**
# Ansible module argument_spec is conventionally defined with the dict(...)
# constructor (not {...} literals) for readability and consistency across the
# collection. Suppress python:S7498 ("prefer literal syntax"), which conflicts
# with that convention and otherwise re-fires on every new module argument.
sonar.issue.ignore.multicriteria=e1,e2,e3
sonar.issue.ignore.multicriteria.e1.ruleKey=python:S7498
sonar.issue.ignore.multicriteria.e1.resourceKey=**/*.py
# Unit tests pass hardcoded '/tmp/...' strings as fake module arguments (e.g.
# chart_ref) to fully mocked commands; no file is ever created there. Suppress
# python:S5443 ("temporary files in publicly writable directories") for test
# code only. Production code creates temp files via tempfile.mkstemp /
# NamedTemporaryFile and stays covered by the rule.
sonar.issue.ignore.multicriteria.e2.ruleKey=python:S5443
sonar.issue.ignore.multicriteria.e2.resourceKey=tests/**/*.py
# GitHub Actions workflows in this repo use @main for internal reusable actions
# (ansible-network/github_actions, ansible-collections/cloud-content-ci-automation)
# to simplify maintenance. Suppress githubactions:S7637 ("use full commit SHA").
sonar.issue.ignore.multicriteria.e3.ruleKey=githubactions:S7637
sonar.issue.ignore.multicriteria.e3.resourceKey=.github/workflows/**/*.yaml
+1 -1
View File
@@ -1,2 +1,2 @@
modules:
python_requires: ">=3.9"
python_requires: ">=3.6"
+4 -1
View File
@@ -1 +1,4 @@
disabled # used by test targets helm_vX_XX_XX
time=100
helm_info
helm_repository
helm_template
@@ -3,32 +3,26 @@ helm_default_archive_name: "helm-{{ helm_version }}-{{ ansible_system | lower }}
helm_binary: "/tmp/helm/{{ ansible_system | lower }}-amd64/helm"
chart_test: "ingress-nginx"
chart_test_oci: "oci://registry-1.docker.io/bitnamicharts/redis"
chart_test_local_path: "nginx-ingress"
chart_test_version: 4.2.4
chart_test_version_local_path: 1.32.0
chart_test_version_upgrade: 4.2.5
chart_test_version_upgrade_local_path: 1.33.0
chart_test_repo: "https://stenic.github.io/k8status/"
chart_test_repo: "https://kubernetes.github.io/ingress-nginx"
chart_test_git_repo: "http://github.com/helm/charts.git"
chart_test_values:
revisionHistoryLimit: 0
myValue: "changed"
test_namespace:
- "helm-test-crds-{{ helm_version | replace('.', '-') }}"
- "helm-uninstall-{{ helm_version | replace('.', '-') }}"
- "helm-read-envvars-{{ helm_version | replace('.', '-') }}"
- "helm-dep-update-{{ helm_version | replace('.', '-') }}"
- "helm-local-path-001-{{ helm_version | replace('.', '-') }}"
- "helm-local-path-002-{{ helm_version | replace('.', '-') }}"
- "helm-local-path-003-{{ helm_version | replace('.', '-') }}"
- "helm-from-repository-{{ helm_version | replace('.', '-') }}"
- "helm-from-url-{{ helm_version | replace('.', '-') }}"
- "helm-reuse-values-{{ helm_version | replace('.', '-') }}"
- "helm-chart-with-space-into-name-{{ helm_version | replace('.', '-') }}"
- "helm-reset-then-reuse-values-{{ helm_version | replace('.', '-') }}"
- "helm-insecure-{{ helm_version | replace('.', '-') }}"
- "helm-test-take-ownership-{{ helm_version | replace('.', '-') }}"
- "helm-skip-schema-validation-{{ helm_version | replace('.', '-') }}"
- "helm-wait-for-jobs-{{ helm_version | replace('.', '-') }}"
- "helm-test-crds"
- "helm-uninstall"
- "helm-read-envvars"
- "helm-dep-update"
- "helm-local-path-001"
- "helm-local-path-002"
- "helm-local-path-003"
- "helm-from-repository"
- "helm-from-url"
- "helm-reuse-values"
- "helm-chart-with-space-into-name"
@@ -1,6 +0,0 @@
apiVersion: v2
name: test-chart-job
description: A chart with a Job for testing wait_for_jobs
type: application
version: 0.1.0
appVersion: "default"
@@ -1,21 +0,0 @@
apiVersion: batch/v1
kind: Job
metadata:
name: "{{ .Release.Name }}-job"
spec:
backoffLimit: 0
template:
spec:
automountServiceAccountToken: false
restartPolicy: Never
containers:
- name: test
image: "busybox:1.37"
command: ["sh", "-c", "echo done"]
resources:
requests:
cpu: "50m"
memory: "32Mi"
ephemeral-storage: "16Mi"
limits:
memory: "64Mi"
@@ -52,9 +52,7 @@ import json
import subprocess
import time
from ansible_collections.kubernetes.core.plugins.module_utils.helm import (
AnsibleHelmModule,
)
from ansible.module_utils.basic import AnsibleModule
class HelmReleaseNotFoundError(Exception):
@@ -62,9 +60,7 @@ class HelmReleaseNotFoundError(Exception):
super().__init__(message)
def create_pending_install_release(
module, helm_binary, chart_ref, chart_release, namespace
):
def create_pending_install_release(helm_binary, chart_ref, chart_release, namespace):
# create pending-install release
command = [
helm_binary,
@@ -82,14 +78,13 @@ def create_pending_install_release(
command = [
helm_binary,
"list",
"--all",
"--output=json",
"--namespace",
namespace,
"--filter",
chart_release,
]
if not module.is_helm_v4():
command.append("--all")
cmd = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = cmd.communicate()
@@ -97,11 +92,11 @@ def create_pending_install_release(
if not data:
error = "Release %s not found." % chart_release
raise HelmReleaseNotFoundError(message=error)
return data[0]["status"] in ("pending-install", "failed"), data[0]["status"]
return data[0]["status"] == "pending-install", data[0]["status"]
def main():
module = AnsibleHelmModule(
module = AnsibleModule(
argument_spec=dict(
binary_path=dict(type="path", required=True),
chart_ref=dict(type="str", required=True),
@@ -111,7 +106,6 @@ def main():
)
params = dict(
module=module,
helm_binary=module.params.get("binary_path"),
chart_release=module.params.get("chart_release"),
chart_ref=module.params.get("chart_ref"),
@@ -122,7 +116,7 @@ def main():
result, status = create_pending_install_release(**params)
if not result:
module.fail_json(
msg="unable to create pending-install/failed release, current status is %s"
msg="unable to create pending-install release, current status is %s"
% status
)
module.exit_json(changed=True, msg="Release created with status '%s'" % status)
@@ -1,3 +1,5 @@
---
collections:
- kubernetes.core
dependencies:
- remove_namespace

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