feat(kubernetes): Handle empty --kubeconfig-file (#3980)

Co-authored-by: Sergio <sergio@prowler.com>
This commit is contained in:
Pedro Martín
2024-05-15 15:00:46 +02:00
committed by GitHub
co-authored by Sergio
parent c6786881fb
commit c33c3e3e21
4 changed files with 23 additions and 12 deletions
+2
View File
@@ -324,6 +324,8 @@ For non in-cluster execution, you can provide the location of the KubeConfig fil
```console
prowler kubernetes --kubeconfig-file path
```
???+ note
If no `--kubeconfig-file` is provided, Prowler will use the default KubeConfig file location (`~/.kube/config`).
For in-cluster execution, you can use the supplied yaml to run Prowler as a job within a new Prowler namespace:
```console
@@ -3,6 +3,7 @@ import sys
from argparse import Namespace
from colorama import Fore, Style
from kubernetes.config.config_exception import ConfigException
from kubernetes import client, config
from prowler.config.config import load_and_validate_config_file
@@ -124,19 +125,18 @@ class KubernetesProvider(Provider):
Tuple: A tuple containing the API client and the context.
"""
try:
if kubeconfig_file:
logger.info(f"Using kubeconfig file: {kubeconfig_file}")
logger.info(f"Using kubeconfig file: {kubeconfig_file}")
try:
config.load_kube_config(
config_file=os.path.abspath(kubeconfig_file), context=input_context
config_file=(
os.path.abspath(kubeconfig_file)
if kubeconfig_file != "~/.kube/config"
else os.path.expanduser(kubeconfig_file)
),
context=input_context,
)
if input_context:
contexts = config.list_kube_config_contexts()[0]
for context_item in contexts:
if context_item["name"] == input_context:
context = context_item
else:
context = config.list_kube_config_contexts()[1]
else:
except ConfigException:
# If the kubeconfig file is not found, try to use the in-cluster config
logger.info("Using in-cluster config")
config.load_incluster_config()
context = {
@@ -146,6 +146,14 @@ class KubernetesProvider(Provider):
"user": "service-account-name", # Also a placeholder
},
}
else:
if input_context:
contexts = config.list_kube_config_contexts()[0]
for context_item in contexts:
if context_item["name"] == input_context:
context = context_item
else:
context = config.list_kube_config_contexts()[1]
return KubernetesSession(api_client=client.ApiClient(), context=context)
except Exception as error:
logger.critical(
@@ -12,6 +12,7 @@ def init_parser(self):
nargs="?",
metavar="FILE_PATH",
help="Path to the kubeconfig file to use for CLI requests. Not necessary for in-cluster execution.",
default="~/.kube/config",
)
k8s_auth_subparser.add_argument(
"--context",
+1 -1
View File
@@ -189,7 +189,7 @@ class Test_Parser:
assert not parsed.list_compliance
assert not parsed.list_compliance_requirements
assert not parsed.list_categories
assert not parsed.kubeconfig_file
assert parsed.kubeconfig_file == "~/.kube/config"
assert not parsed.context
assert not parsed.namespace