Helm - Fix issue with alternative kubeconfig (#563)

Helm - Fix issue with alternative kubeconfig

SUMMARY

closes #538

ISSUE TYPE


Bugfix Pull Request

COMPONENT NAME

helm modules

Reviewed-by: Mike Graves <mgraves@redhat.com>
This commit is contained in:
Bikouo Aubin
2023-01-12 10:46:42 +01:00
committed by GitHub
parent 26cd550bc0
commit 804b9ab57c
20 changed files with 872 additions and 384 deletions

View File

@@ -1,5 +1,5 @@
---
helm_archive_name: "helm-{{ helm_version }}-{{ ansible_system | lower }}-amd64.tar.gz"
helm_default_archive_name: "helm-{{ helm_version }}-{{ ansible_system | lower }}-amd64.tar.gz"
helm_binary: "/tmp/helm/{{ ansible_system | lower }}-amd64/helm"
chart_test: "ingress-nginx"
@@ -14,6 +14,8 @@ chart_test_values:
revisionHistoryLimit: 0
myValue: "changed"
default_kubeconfig_path: "~/.kube/config"
test_namespace:
- "helm-diff"
- "helm-envvars"
@@ -26,4 +28,6 @@ test_namespace:
- "helm-local-path-002"
- "helm-local-path-003"
- "helm-dep"
- "helm-kubeconfig"
- "helm-in-memory-kubeconfig"
- "helm-kubeconfig-with-insecure-skip-tls-verify"
- "helm-kubeconfig-with-ca-cert"

View File

@@ -6,7 +6,7 @@
- name: Unarchive Helm binary
unarchive:
src: 'https://get.helm.sh/{{ helm_archive_name }}'
src: 'https://get.helm.sh/{{ helm_archive_name | default(helm_default_archive_name) }}'
dest: /tmp/helm/
remote_src: yes
retries: 10

View File

@@ -43,8 +43,8 @@
- name: Test Skip CRDS feature in helm chart install
include_tasks: test_crds.yml
- name: Test in-memory kubeconfig
include_tasks: tests_in_memory_kubeconfig.yml
- name: Test helm modules with custom kube config, validate_certs and/or ca_cert
include_tasks: tests_helm_kubeconfig.yml
- name: Test helm pull
include_tasks: tests_helm_pull.yml

View File

@@ -1,30 +1,41 @@
---
- name: create temporary directory
tempfile:
state: directory
suffix: .helm
register: _dir
- name: Install helm binary
block:
- name: "Install {{ test_helm_version }}"
include_tasks: install.yml
vars:
helm_archive_name: "helm-{{ test_helm_version }}-{{ ansible_system | lower }}-amd64.tar.gz"
when: test_helm_version is defined
- set_fact:
custom_kubeconfig_path: "~/.kube/customconfig"
default_kubeconfig_path: "~/.kube/config"
helm_in_mem_kubeconf_ns: "{{ test_namespace[11] }}"
saved_kubeconfig_path: "{{ _dir.path }}/config"
- block:
- name: Copy default kubeconfig
copy:
remote_src: true
src: "{{ default_kubeconfig_path }}"
dest: "{{ custom_kubeconfig_path }}"
dest: "{{ saved_kubeconfig_path }}"
- name: Delete default kubeconfig
file:
path: "{{ default_kubeconfig_path }}"
state: absent
- set_fact:
custom_kubeconfig: "{{ lookup('file', custom_kubeconfig_path) | from_yaml }}"
no_log: true
# helm_plugin and helm_plugin_info
- name: Install subenv plugin
helm_plugin:
binary_path: "{{ helm_binary }}"
kubeconfig: "{{ custom_kubeconfig }}"
kubeconfig: "{{ test_kubeconfig | default(omit) }}"
validate_certs: "{{ test_validate_certs | default(omit) }}"
ca_cert: "{{ test_ca_cert | default(omit) }}"
state: present
plugin_path: https://github.com/hydeenoble/helm-subenv
register: plugin
@@ -36,7 +47,9 @@
- name: Gather info about all plugin
helm_plugin_info:
binary_path: "{{ helm_binary }}"
kubeconfig: "{{ custom_kubeconfig }}"
kubeconfig: "{{ test_kubeconfig | default(omit) }}"
validate_certs: "{{ test_validate_certs | default(omit) }}"
ca_cert: "{{ test_ca_cert | default(omit) }}"
register: plugin_info
- assert:
@@ -49,7 +62,9 @@
helm_repository:
binary_path: "{{ helm_binary }}"
name: test_bitnami
kubeconfig: "{{ custom_kubeconfig }}"
kubeconfig: "{{ test_kubeconfig | default(omit) }}"
validate_certs: "{{ test_validate_certs | default(omit) }}"
ca_cert: "{{ test_ca_cert | default(omit) }}"
repo_url: https://charts.bitnami.com/bitnami
register: repository
@@ -63,9 +78,11 @@
binary_path: "{{ helm_binary }}"
name: rabbitmq
chart_ref: test_bitnami/rabbitmq
namespace: "{{ helm_in_mem_kubeconf_ns }}"
namespace: "{{ helm_namespace }}"
update_repo_cache: true
kubeconfig: "{{ custom_kubeconfig }}"
kubeconfig: "{{ test_kubeconfig | default(omit) }}"
validate_certs: "{{ test_validate_certs | default(omit) }}"
ca_cert: "{{ test_ca_cert | default(omit) }}"
create_namespace: true
register: deploy
@@ -77,9 +94,11 @@
- name: Get chart content
helm_info:
binary_path: "{{ helm_binary }}"
kubeconfig: "{{ custom_kubeconfig }}"
kubeconfig: "{{ test_kubeconfig | default(omit) }}"
validate_certs: "{{ test_validate_certs | default(omit) }}"
ca_cert: "{{ test_ca_cert | default(omit) }}"
name: "rabbitmq"
namespace: "{{ helm_in_mem_kubeconf_ns }}"
namespace: "{{ helm_namespace }}"
register: chart_info
- name: Assert chart was successfully deployed
@@ -93,8 +112,10 @@
helm:
binary_path: "{{ helm_binary }}"
name: rabbitmq
namespace: "{{ helm_in_mem_kubeconf_ns }}"
kubeconfig: "{{ custom_kubeconfig }}"
namespace: "{{ helm_namespace }}"
kubeconfig: "{{ test_kubeconfig | default(omit) }}"
validate_certs: "{{ test_validate_certs | default(omit) }}"
ca_cert: "{{ test_ca_cert | default(omit) }}"
state: absent
register: remove_chart
@@ -106,9 +127,11 @@
- name: Get chart content
helm_info:
binary_path: "{{ helm_binary }}"
kubeconfig: "{{ custom_kubeconfig }}"
kubeconfig: "{{ test_kubeconfig | default(omit) }}"
validate_certs: "{{ test_validate_certs | default(omit) }}"
ca_cert: "{{ test_ca_cert | default(omit) }}"
name: "rabbitmq"
namespace: "{{ helm_in_mem_kubeconf_ns }}"
namespace: "{{ helm_namespace }}"
register: chart_info
- name: Assert chart was successfully deployed
@@ -120,7 +143,9 @@
helm_repository:
binary_path: "{{ helm_binary }}"
name: test_bitnami
kubeconfig: "{{ custom_kubeconfig }}"
kubeconfig: "{{ test_kubeconfig | default(omit) }}"
validate_certs: "{{ test_validate_certs | default(omit) }}"
ca_cert: "{{ test_ca_cert | default(omit) }}"
state: absent
register: remove
@@ -133,16 +158,23 @@
- name: Return kubeconfig
copy:
remote_src: true
src: "{{ custom_kubeconfig_path }}"
src: "{{ saved_kubeconfig_path }}"
dest: "{{ default_kubeconfig_path }}"
ignore_errors: true
- name: Delete custom config
- name: Delete temporary directory
file:
path: "{{ custom_kubeconfig_path }}"
path: "{{ _dir.path }}"
state: absent
ignore_errors: true
- name: Delete temporary directory for helm install
file:
path: "{{ _helm_install.path }}"
state: absent
ignore_errors: true
when: _helm_install is defined
- name: Remove subenv plugin
helm_plugin:
binary_path: "{{ helm_binary }}"
@@ -153,7 +185,7 @@
- name: Delete namespace
k8s:
kind: Namespace
name: "{{ helm_in_mem_kubeconf_ns }}"
name: "{{ helm_namespace }}"
ignore_errors: true
- name: Delete helm repository

View File

@@ -2,6 +2,7 @@
- name: Test helm diff functionality
vars:
test_chart_ref: "/tmp/test-chart"
redis_chart_version: '17.0.5'
block:
- set_fact:
@@ -182,7 +183,7 @@
chart_ref: redis
namespace: "{{ helm_namespace }}"
name: redis-chart
chart_version: '16.0.0'
chart_version: "{{ redis_chart_version }}"
release_values: "{{ redis_chart_values }}"
- name: Upgrade Redis chart
@@ -192,7 +193,7 @@
chart_ref: redis
namespace: "{{ helm_namespace }}"
name: redis-chart
chart_version: '16.0.0'
chart_version: "{{ redis_chart_version }}"
release_values: "{{ redis_chart_values }}"
check_mode: yes
register: redis_upgrade
@@ -226,7 +227,7 @@
chart_ref: redis
namespace: "{{ helm_namespace }}"
name: redis-chart
chart_version: '16.0.0'
chart_version: "{{ redis_chart_version }}"
release_values: "{{ redis_chart_values }}"
check_mode: yes
register: redis_upgrade_2

View File

@@ -0,0 +1,22 @@
---
- name: Test helm with in-memory kubeconfig
include_tasks: "tests_kubeconfig/from_in_memory_kubeconfig.yml"
- name: Test helm with custom kubeconfig and validate_certs=false
include_tasks: "tests_kubeconfig/from_kubeconfig_with_validate_certs.yml"
loop_control:
loop_var: test_helm_version
with_items:
- "v3.10.3"
- "v3.8.2"
- name: Test helm with custom kubeconfig and ca_cert
include_tasks: "tests_kubeconfig/from_kubeconfig_with_cacert.yml"
loop_control:
loop_var: test_helm_version
with_items:
- "v3.5.1"
- "v3.4.2"
- name: install default helm archive version
include_tasks: install.yml

View File

@@ -0,0 +1,9 @@
---
- set_fact:
custom_config: "{{ lookup('file', default_kubeconfig_path | expanduser) | from_yaml }}"
- name: Test helm modules using in-memory kubeconfig
include_tasks: "../tests_helm_auth.yml"
vars:
test_kubeconfig: "{{ custom_config }}"
helm_namespace: "{{ test_namespace[11] }}"

View File

@@ -0,0 +1,76 @@
---
- set_fact:
content: "{{ lookup('file', default_kubeconfig_path) | from_yaml }}"
custom_content: {}
clusters: []
- set_fact:
custom_content: "{{ custom_content | combine({item.key: item.value}) }}"
when: "{{ item.key not in ['clusters'] }}"
with_dict: "{{ content }}"
- set_fact:
clusters: "{{ clusters + [item | combine({'cluster': {'certificate-authority-data': omit}}, recursive=true)] }}"
with_items: "{{ content.clusters }}"
- set_fact:
custom_content: "{{ custom_content | combine({'clusters': clusters}) }}"
- name: create temporary file for ca_cert
tempfile:
suffix: .cacert
register: ca_file
- name: copy content into certificate file
copy:
content: "{{ content.clusters.0.cluster['certificate-authority-data'] | b64decode }}"
dest: "{{ ca_file.path }}"
- name: create temporary file to save config in
tempfile:
suffix: .config
register: tfile
- name: create custom config
copy:
content: "{{ custom_content | to_yaml }}"
dest: "{{ tfile.path }}"
- block:
- name: Install Redis chart without ca_cert (should fail)
helm:
binary_path: "{{ helm_binary }}"
chart_repo_url: https://charts.bitnami.com/bitnami
chart_ref: redis
namespace: "{{ helm_namespace }}"
create_namespace: true
name: redis-chart
chart_version: '17.0.5'
release_values:
architecture: standalone
release_state: present
kubeconfig: "{{ tfile.path }}"
ignore_errors: true
register: _install
- name: assert task failed
assert:
that:
- _install is failed
- '"Error: Kubernetes cluster unreachable" in _install.msg'
- name: Test helm modules using in-memory kubeconfig
include_tasks: "../tests_helm_auth.yml"
vars:
test_kubeconfig: "{{ tfile.path }}"
test_ca_cert: "{{ ca_file.path }}"
vars:
helm_namespace: "{{ test_namespace[13] }}"
always:
- name: Delete temporary file
file:
state: absent
path: "{{ tfile.path }}"
ignore_errors: true

View File

@@ -0,0 +1,67 @@
---
- set_fact:
content: "{{ lookup('file', default_kubeconfig_path) | from_yaml }}"
custom_content: {}
clusters: []
- set_fact:
custom_content: "{{ custom_content | combine({item.key: item.value}) }}"
when: "{{ item.key not in ['clusters'] }}"
with_dict: "{{ content }}"
- set_fact:
clusters: "{{ clusters + [item | combine({'cluster': {'certificate-authority-data': omit}}, recursive=true)] }}"
with_items: "{{ content.clusters }}"
- set_fact:
custom_content: "{{ custom_content | combine({'clusters': clusters}) }}"
- name: create temporary file to save config in
tempfile:
suffix: .config
register: tfile
- name: create custom config
copy:
content: "{{ custom_content | to_yaml }}"
dest: "{{ tfile.path }}"
- block:
- name: Install Redis chart without validate_certs=false (should fail)
helm:
binary_path: "{{ helm_binary }}"
chart_repo_url: https://charts.bitnami.com/bitnami
chart_ref: redis
namespace: "{{ helm_namespace }}"
create_namespace: true
name: redis-chart
chart_version: '17.0.5'
release_values:
architecture: standalone
release_state: present
kubeconfig: "{{ tfile.path }}"
validate_certs: true
ignore_errors: true
register: _install
- name: assert task failed
assert:
that:
- _install is failed
- '"Error: Kubernetes cluster unreachable" in _install.msg'
- name: Test helm modules using in-memory kubeconfig
include_tasks: "../tests_helm_auth.yml"
vars:
test_kubeconfig: "{{ tfile.path }}"
test_validate_certs: false
vars:
helm_namespace: "{{ test_namespace[12] }}"
always:
- name: Delete temporary file
file:
state: absent
path: "{{ tfile.path }}"
ignore_errors: true

View File

@@ -9,53 +9,43 @@ __metaclass__ = type
import os.path
import yaml
import tempfile
import json
import pytest
from ansible_collections.kubernetes.core.plugins.module_utils.helm import (
run_helm,
AnsibleHelmModule,
write_temp_kubeconfig,
)
from unittest.mock import MagicMock
import random
import string
class MockedModule:
def __init__(self):
@pytest.fixture()
def ansible_helm_module():
module = MagicMock()
module.params = {
"api_key": None,
"ca_cert": None,
"host": None,
"kube_context": None,
"kubeconfig": None,
"release_namespace": None,
"validate_certs": None,
}
module.fail_json = MagicMock()
module.fail_json.side_effect = SystemExit(1)
module.run_command = MagicMock()
self.params = {
"api_key": None,
"ca_cert": None,
"host": None,
"kube_context": None,
"kubeconfig": None,
"release_namespace": None,
"validate_certs": None,
}
helm_module = AnsibleHelmModule(module=module)
helm_module.get_helm_binary = MagicMock()
helm_module.get_helm_binary.return_value = "some/path/to/helm/executable"
self.r = {}
self.files_to_delete = []
def run_command(self, command, environ_update=None):
self.r = {"command": command, "environ_update": environ_update}
return 0, "", ""
def add_cleanup_file(self, file_path):
self.files_to_delete.append(file_path)
def do_cleanup_files(self):
for file in self.files_to_delete:
try:
os.remove(file)
except Exception:
pass
return helm_module
def test_write_temp_kubeconfig_server_only():
file_name = write_temp_kubeconfig("ff")
try:
with open(file_name, "r") as fd:
content = yaml.safe_load(fd)
finally:
os.remove(file_name)
content = write_temp_kubeconfig("ff")
assert content == {
"apiVersion": "v1",
@@ -69,12 +59,7 @@ def test_write_temp_kubeconfig_server_only():
def test_write_temp_kubeconfig_server_inscure_certs():
file_name = write_temp_kubeconfig("ff", False, "my-certificate")
try:
with open(file_name, "r") as fd:
content = yaml.safe_load(fd)
finally:
os.remove(file_name)
content = write_temp_kubeconfig("ff", False, "my-certificate")
assert content["clusters"][0]["cluster"]["insecure-skip-tls-verify"] is True
assert (
@@ -82,87 +67,351 @@ def test_write_temp_kubeconfig_server_inscure_certs():
)
def test_run_helm_naked():
module = MockedModule()
run_helm(module, "helm foo")
assert module.r["command"] == "helm foo"
assert module.r["environ_update"] == {}
def test_run_helm_with_params():
module = MockedModule()
module.params = {
"api_key": "my-api-key",
"ca_cert": "my-ca-cert",
"host": "some-host",
"context": "my-context",
"release_namespace": "a-release-namespace",
"validate_certs": False,
}
run_helm(module, "helm foo")
assert module.r["command"] == "helm foo"
assert module.r["environ_update"]["HELM_KUBEAPISERVER"] == "some-host"
assert module.r["environ_update"]["HELM_KUBECONTEXT"] == "my-context"
assert module.r["environ_update"]["HELM_KUBETOKEN"] == "my-api-key"
assert module.r["environ_update"]["HELM_NAMESPACE"] == "a-release-namespace"
assert module.r["environ_update"]["KUBECONFIG"]
assert os.path.exists(module.r["environ_update"]["KUBECONFIG"])
module.do_cleanup_files()
def test_run_helm_with_kubeconfig():
custom_config = {
def test_write_temp_kubeconfig_with_kubeconfig():
kubeconfig = {
"apiVersion": "v1",
"kind": "Config",
"clusters": [
{"cluster": {"server": "myfirstserver"}, "name": "cluster-01"},
{"cluster": {"server": "mysecondserver"}, "name": "cluster-02"},
],
"contexts": [{"context": {"cluster": "cluster-01"}, "name": "test-context"}],
"current-context": "test-context",
}
content = write_temp_kubeconfig(
server="mythirdserver",
validate_certs=False,
ca_cert="some-ca-cert-for-test",
kubeconfig=kubeconfig,
)
expected = {
"apiVersion": "v1",
"kind": "Config",
"clusters": [
{
"cluster": {
"certificate-authority-data": "LS0tLS1CRUdJTiBDRV",
"server": "https://api.cluster.testing:6443",
"server": "mythirdserver",
"insecure-skip-tls-verify": True,
"certificate-authority": "some-ca-cert-for-test",
},
"name": "api-cluster-testing:6443",
}
],
"contexts": [
"name": "cluster-01",
},
{
"context": {
"cluster": "api-cluster-testing:6443",
"namespace": "default",
"user": "kubeadmin",
"cluster": {
"server": "mythirdserver",
"insecure-skip-tls-verify": True,
"certificate-authority": "some-ca-cert-for-test",
},
"name": "context-1",
}
],
"current-context": "context-1",
"kind": "Config",
"users": [
{
"name": "developer",
"user": {"token": "sha256~jbIvVieBC_8W6Pb-iH5vqC_BvvPHIxQMxUPLDnYvHYM"},
}
"name": "cluster-02",
},
],
"contexts": [{"context": {"cluster": "cluster-01"}, "name": "test-context"}],
"current-context": "test-context",
}
# kubeconfig defined as path
_fd, tmpfile_name = tempfile.mkstemp()
with os.fdopen(_fd, "w") as fp:
yaml.dump(custom_config, fp)
assert content == expected
k1_module = MockedModule()
k1_module.params = {"kubeconfig": tmpfile_name}
run_helm(k1_module, "helm foo")
assert k1_module.r["environ_update"] == {"KUBECONFIG": tmpfile_name}
os.remove(tmpfile_name)
# kubeconfig defined as string
k2_module = MockedModule()
k2_module.params = {"kubeconfig": custom_config}
run_helm(k2_module, "helm foo")
def test_module_get_helm_binary_from_params():
assert os.path.exists(k2_module.r["environ_update"]["KUBECONFIG"])
with open(k2_module.r["environ_update"]["KUBECONFIG"]) as f:
assert json.loads(f.read()) == custom_config
k2_module.do_cleanup_files()
helm_binary_path = MagicMock()
helm_sys_binary_path = MagicMock()
module = MagicMock()
module.params = {
"binary_path": helm_binary_path,
}
module.get_bin_path.return_value = helm_sys_binary_path
helm_module = AnsibleHelmModule(module=module)
assert helm_module.get_helm_binary() == helm_binary_path
def test_module_get_helm_binary_from_system():
helm_sys_binary_path = MagicMock()
module = MagicMock()
module.params = {}
module.get_bin_path.return_value = helm_sys_binary_path
helm_module = AnsibleHelmModule(module=module)
assert helm_module.get_helm_binary() == helm_sys_binary_path
def test_module_get_helm_plugin_list(ansible_helm_module):
ansible_helm_module.run_helm_command = MagicMock()
ansible_helm_module.run_helm_command.return_value = (0, "output", "error")
rc, out, err, command = ansible_helm_module.get_helm_plugin_list()
assert (rc, out, err) == (0, "output", "error")
assert command == "some/path/to/helm/executable plugin list"
ansible_helm_module.get_helm_binary.assert_called_once()
ansible_helm_module.run_helm_command.assert_called_once_with(
"some/path/to/helm/executable plugin list"
)
def test_module_get_helm_plugin_list_failure(ansible_helm_module):
ansible_helm_module.run_helm_command = MagicMock()
ansible_helm_module.run_helm_command.return_value = (-1, "output", "error")
with pytest.raises(SystemExit):
ansible_helm_module.get_helm_plugin_list()
ansible_helm_module.fail_json.assert_called_once_with(
msg="Failed to get Helm plugin info",
command="some/path/to/helm/executable plugin list",
stdout="output",
stderr="error",
rc=-1,
)
@pytest.mark.parametrize("no_values", [True, False])
@pytest.mark.parametrize("get_all", [True, False])
def test_module_get_values(ansible_helm_module, no_values, get_all):
expected = {"test": "units"}
output = "---\ntest: units\n"
if no_values:
expected = {}
output = "null"
ansible_helm_module.run_helm_command = MagicMock()
ansible_helm_module.run_helm_command.return_value = (0, output, "error")
release_name = "".join(
random.choice(string.ascii_letters + string.digits) for x in range(10)
)
result = ansible_helm_module.get_values(release_name, get_all=get_all)
ansible_helm_module.get_helm_binary.assert_called_once()
command = f"some/path/to/helm/executable get values --output=yaml {release_name}"
if get_all:
command += " -a"
ansible_helm_module.run_helm_command.assert_called_once_with(command)
assert result == expected
@pytest.mark.parametrize(
"output,expected",
[
(
'version.BuildInfo{Version:"v3.10.3", GitCommit:7870ab3ed4135f136eec, GoVersion:"go1.18.9"}',
"3.10.3",
),
('Client: &version.Version{SemVer:"v3.12.3", ', "3.12.3"),
('Client: &version.Version{SemVer:"v3.12.3"', None),
],
)
def test_module_get_helm_version(ansible_helm_module, output, expected):
ansible_helm_module.run_command = MagicMock()
ansible_helm_module.run_command.return_value = (0, output, "error")
result = ansible_helm_module.get_helm_version()
ansible_helm_module.get_helm_binary.assert_called_once()
command = "some/path/to/helm/executable version"
ansible_helm_module.run_command.assert_called_once_with(command)
assert result == expected
def test_module_run_helm_command(ansible_helm_module):
error = "".join(
random.choice(string.ascii_letters + string.digits) for x in range(10)
)
output = "".join(
random.choice(string.ascii_letters + string.digits) for x in range(10)
)
ansible_helm_module.run_command.return_value = (0, output, error)
ansible_helm_module._prepare_helm_environment = MagicMock()
env_update = {x: random.choice(string.ascii_letters) for x in range(10)}
ansible_helm_module._prepare_helm_environment.return_value = env_update
command = "".join(
random.choice(string.ascii_letters + string.digits) for x in range(10)
)
rc, out, err = ansible_helm_module.run_helm_command(command)
assert (rc, out, err) == (0, output, error)
ansible_helm_module.run_command.assert_called_once_with(
command, environ_update=env_update
)
@pytest.mark.parametrize("fails_on_error", [True, False])
def test_module_run_helm_command_failure(ansible_helm_module, fails_on_error):
error = "".join(
random.choice(string.ascii_letters + string.digits) for x in range(10)
)
output = "".join(
random.choice(string.ascii_letters + string.digits) for x in range(10)
)
return_code = random.randint(1, 10)
ansible_helm_module.run_command.return_value = (return_code, output, error)
ansible_helm_module._prepare_environment = MagicMock()
command = "".join(
random.choice(string.ascii_letters + string.digits) for x in range(10)
)
if fails_on_error:
with pytest.raises(SystemExit):
rc, out, err = ansible_helm_module.run_helm_command(
command, fails_on_error=fails_on_error
)
ansible_helm_module.fail_json.assert_called_with(
msg="Failure when executing Helm command. Exited {0}.\nstdout: {1}\nstderr: {2}".format(
return_code, output, error
),
stdout=output,
stderr=error,
command=command,
)
else:
rc, out, err = ansible_helm_module.run_helm_command(
command, fails_on_error=fails_on_error
)
assert (rc, out, err) == (return_code, output, error)
@pytest.mark.parametrize(
"params,env_update,kubeconfig",
[
(
{
"api_key": "my-api-key",
"host": "some-host",
"context": "my-context",
"release_namespace": "a-release-namespace",
},
{
"HELM_KUBEAPISERVER": "some-host",
"HELM_KUBECONTEXT": "my-context",
"HELM_KUBETOKEN": "my-api-key",
"HELM_NAMESPACE": "a-release-namespace",
},
False,
),
({"kubeconfig": {"kube": "config"}}, {}, True),
({"kubeconfig": "path_to_a_config_file"}, {}, True),
],
)
def test_module_prepare_helm_environment(params, env_update, kubeconfig):
module = MagicMock()
module.params = params
helm_module = AnsibleHelmModule(module=module)
p_kubeconfig = params.get("kubeconfig")
tmpfile_name = None
if isinstance(p_kubeconfig, str):
_fd, tmpfile_name = tempfile.mkstemp()
with os.fdopen(_fd, "w") as fp:
yaml.dump({"some_custom": "kube_config"}, fp)
params["kubeconfig"] = tmpfile_name
result = helm_module._prepare_helm_environment()
kubeconfig_path = result.pop("KUBECONFIG", None)
assert env_update == result
if kubeconfig:
assert os.path.exists(kubeconfig_path)
if not tmpfile_name:
module.add_cleanup_file.assert_called_with(kubeconfig_path)
else:
assert kubeconfig_path is None
if tmpfile_name:
os.remove(tmpfile_name)
@pytest.mark.parametrize(
"helm_version, is_env_var_set",
[
("3.10.1", True),
("3.10.0", True),
("3.5.0", False),
("3.8.0", False),
("3.9.35", False),
],
)
def test_module_prepare_helm_environment_with_validate_certs(
helm_version, is_env_var_set
):
module = MagicMock()
module.params = {"validate_certs": False}
helm_module = AnsibleHelmModule(module=module)
helm_module.get_helm_version = MagicMock()
helm_module.get_helm_version.return_value = helm_version
result = helm_module._prepare_helm_environment()
if is_env_var_set:
assert result == {"HELM_KUBEINSECURE_SKIP_TLS_VERIFY": "true"}
else:
assert list(result.keys()) == ["KUBECONFIG"]
kubeconfig_path = result["KUBECONFIG"]
assert os.path.exists(kubeconfig_path)
with open(kubeconfig_path) as fd:
content = yaml.safe_load(fd)
assert content["clusters"][0]["cluster"]["insecure-skip-tls-verify"] is True
os.remove(kubeconfig_path)
@pytest.mark.parametrize(
"helm_version, is_env_var_set",
[
("3.10.0", True),
("3.5.0", True),
("3.4.9", False),
],
)
def test_module_prepare_helm_environment_with_ca_cert(helm_version, is_env_var_set):
ca_cert = "".join(
random.choice(string.ascii_letters + string.digits) for i in range(50)
)
module = MagicMock()
module.params = {"ca_cert": ca_cert}
helm_module = AnsibleHelmModule(module=module)
helm_module.get_helm_version = MagicMock()
helm_module.get_helm_version.return_value = helm_version
result = helm_module._prepare_helm_environment()
if is_env_var_set:
assert list(result.keys()) == ["HELM_KUBECAFILE"]
assert result["HELM_KUBECAFILE"] == ca_cert
else:
assert list(result.keys()) == ["KUBECONFIG"]
kubeconfig_path = result["KUBECONFIG"]
assert os.path.exists(kubeconfig_path)
with open(kubeconfig_path) as fd:
content = yaml.safe_load(fd)
import json
print(json.dumps(content, indent=2))
assert content["clusters"][0]["cluster"]["certificate-authority"] == ca_cert
os.remove(kubeconfig_path)