Skip to content

Add proxy support to Kubernetes client configuration in get_client #2291

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
0ed97d6
Add proxy support to Kubernetes client configuration in get_client
sbahar619 Jan 26, 2025
e58e6c8
Simplify docstring by removing redundant default value explanation
sbahar619 Jan 26, 2025
705372c
Update proxy configuration logic and README documentation
sbahar619 Jan 26, 2025
0f89b00
Simplify use_proxy docstring in get_client method
sbahar619 Jan 26, 2025
0fb9702
Add support for enabling proxy with use_proxy flag
sbahar619 Jan 26, 2025
a9b4c6f
Remove client_configuration from get_client and initialize only for p…
sbahar619 Jan 26, 2025
479f42f
Refactor proxy handling in get_client function
sbahar619 Jan 26, 2025
251eee6
Refactor docstring to clarify proxy behavior
sbahar619 Jan 26, 2025
6d43194
Simplify proxy configuration logic in get_client
sbahar619 Jan 26, 2025
6bf30f6
Improve error message for missing proxy configuration in get_client
sbahar619 Jan 26, 2025
948fac0
Remove redundant dot in README
sbahar619 Jan 26, 2025
90d5bbb
Remove unnecessary check for client_configuration in get_client
sbahar619 Jan 26, 2025
595cea7
Update README to clarify proxy enablement instructions
sbahar619 Jan 27, 2025
6bea2c9
Clarify proxy enablement in README
sbahar619 Jan 27, 2025
84b9023
Clarify use_proxy argument type in README
sbahar619 Jan 27, 2025
1898f5c
Retrieve client_configuration from kwargs if provided
sbahar619 Jan 27, 2025
59367f4
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jan 27, 2025
776c447
Ensure environment variable overrides use_proxy
sbahar619 Jan 28, 2025
4a92fbb
Remove redundant proxy configuration log
sbahar619 Jan 28, 2025
f6673b2
Preserve client_configuration from kwargs when setting proxy
sbahar619 Jan 28, 2025
f375dad
Update docstring to clarify proxy conf behavior with env var
sbahar619 Jan 28, 2025
040a1c9
Refactor proxy configuration logic for clarity
sbahar619 Jan 28, 2025
3f86433
Update README with proxy enablement details
sbahar619 Jan 28, 2025
10ee9f2
Refactor client_configuration retrieval in get_client
sbahar619 Jan 28, 2025
cbf9f0d
Refactor proxy configuration in get_client for improved clarity
sbahar619 Jan 28, 2025
cae73aa
Refactor use_proxy argument in get_client to support None as default …
sbahar619 Jan 29, 2025
e3e958c
Merge remote-tracking branch 'upstream/main' into CNV-46351/add-proxy…
sbahar619 Jan 29, 2025
b010e7b
Remove use_proxy argument from get_client and update README
sbahar619 Jan 30, 2025
148d834
Ensure proxy settings are always applied when enabled
sbahar619 Jan 30, 2025
aa63891
Check for proxy conflicts in client_configuration and environment var…
sbahar619 Jan 30, 2025
de9c6a8
Add test to verify proxy conflict raises ValueError for mismatched pr…
sbahar619 Jan 30, 2025
85965ca
Refactor test for proxy conflict in get_client method
sbahar619 Jan 30, 2025
b617c53
Refactor test for proxy conflict to use pytest.raises match exp
sbahar619 Jan 30, 2025
798ef9e
Add test for proxy enabled without proxy env variables set
sbahar619 Jan 30, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,23 @@ export OPENSHIFT_PYTHON_WRAPPER_LOG_LEVEL=<LOG_LEVEL> # can be: "DEBUG", "INFO",
export OPENSHIFT_PYTHON_WRAPPER_HASH_LOG_DATA="false"
```

## Proxy Enablement

This configuration allows the client to route traffic through a specified proxy server.
It can be enabled via the environment variable `OPENSHIFT_PYTHON_WRAPPER_CLIENT_USE_PROXY`.

To enable proxy configuration for the client:

1. Set the environment variable `OPENSHIFT_PYTHON_WRAPPER_CLIENT_USE_PROXY=<any value>`

2. Define either `HTTPS_PROXY` or `HTTP_PROXY` environment variable with your proxy URL:
```bash
export HTTPS_PROXY="http://proxy.example.com:8080"
# or
export HTTP_PROXY="http://proxy.example.com:8080"
```
If neither variable is set when proxy is enabled, a `ValueError` will be raised.

## Code check

We use pre-commit for code check.
Expand Down
29 changes: 26 additions & 3 deletions ocp_resources/resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,10 @@ def _get_api_version(dyn_client: DynamicClient, api_group: str, kind: str) -> st


def get_client(
config_file: str = "", config_dict: dict[str, Any] | None = None, context: str = "", **kwargs: Any
config_file: str = "",
config_dict: dict[str, Any] | None = None,
context: str = "",
**kwargs: Any,
) -> DynamicClient:
"""
Get a kubernetes client.
Expand Down Expand Up @@ -104,6 +107,7 @@ def get_client(
config_dict=config_dict, context=context or None, **kwargs
)
)
client_configuration = kwargs.get("client_configuration", kubernetes.client.Configuration())
try:
# Ref: https://github.com/kubernetes-client/python/blob/v26.1.0/kubernetes/base/config/__init__.py
LOGGER.info("Trying to get client via new_client_from_config")
Expand All @@ -112,15 +116,34 @@ def get_client(
# If `KUBECONFIG` environment variable is set via code, the `KUBE_CONFIG_DEFAULT_LOCATION` will be None since
# is populated during import which comes before setting the variable in code.
config_file = config_file or os.environ.get("KUBECONFIG", "~/.kube/config")

if os.environ.get("OPENSHIFT_PYTHON_WRAPPER_CLIENT_USE_PROXY"):
proxy = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY")
if not proxy:
raise ValueError(
"Proxy configuration is enabled but neither HTTPS_PROXY nor HTTP_PROXY environment variables are set."
)
if client_configuration.proxy and client_configuration.proxy != proxy:
raise ValueError(
f"Conflicting proxy settings: client_configuration.proxy={client_configuration.proxy}, "
f"but the environment variable 'OPENSHIFT_PYTHON_WRAPPER_CLIENT_USE_PROXY' defines proxy as {proxy}."
)
client_configuration.proxy = proxy

return kubernetes.dynamic.DynamicClient(
client=kubernetes.config.new_client_from_config(config_file=config_file, context=context or None, **kwargs)
client=kubernetes.config.new_client_from_config(
config_file=config_file,
client_configuration=client_configuration,
context=context or None,
**kwargs,
)
)
except MaxRetryError:
# Ref: https://github.com/kubernetes-client/python/blob/v26.1.0/kubernetes/base/config/incluster_config.py
LOGGER.info("Trying to get client via incluster_config")
return kubernetes.dynamic.DynamicClient(
client=kubernetes.config.incluster_config.load_incluster_config(
client_configuration=kwargs.get("client_configuration"),
client_configuration=client_configuration,
try_refresh_token=kwargs.get("try_refresh_token", True),
)
)
Expand Down
24 changes: 24 additions & 0 deletions tests/test_resources.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import pytest
import yaml
import kubernetes
from testcontainers.k3s import K3SContainer

from ocp_resources.exceptions import ResourceTeardownError
Expand Down Expand Up @@ -103,3 +104,26 @@ def test_resource_context_manager_exit(self, client):
with pytest.raises(ResourceTeardownError):
with TestSecretExit(name="test-context-manager-exit", namespace="default", client=client):
pass

def test_proxy_enabled_but_no_proxy_set(self, monkeypatch):
monkeypatch.setenv(name="OPENSHIFT_PYTHON_WRAPPER_CLIENT_USE_PROXY", value="1")

with pytest.raises(
ValueError,
match="Proxy configuration is enabled but neither HTTPS_PROXY nor HTTP_PROXY environment variables are set.",
):
get_client()

def test_proxy_conflict_raises_value_error(self, monkeypatch):
monkeypatch.setenv(name="OPENSHIFT_PYTHON_WRAPPER_CLIENT_USE_PROXY", value="1")
monkeypatch.setenv(name="HTTPS_PROXY", value="http://env-proxy.com")

client_configuration = kubernetes.client.Configuration()
client_configuration.proxy = "http://not-env-proxy.com"

with pytest.raises(
ValueError,
match="Conflicting proxy settings: client_configuration.proxy=http://not-env-proxy.com, "
"but the environment variable 'OPENSHIFT_PYTHON_WRAPPER_CLIENT_USE_PROXY' defines proxy as http://env-proxy.com.",
):
get_client(client_configuration=client_configuration)