diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ef84f97..9776ca44 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 +### Added + +- `K8s.Conn` - Add namespace info in case of service account connection. + ## [2.4.2] - 2023-10-18 diff --git a/lib/k8s/conn.ex b/lib/k8s/conn.ex index 83368285..05b602b1 100644 --- a/lib/k8s/conn.ex +++ b/lib/k8s/conn.ex @@ -61,11 +61,13 @@ defmodule K8s.Conn do discovery_driver: K8s.default_discovery_driver(), discovery_opts: K8s.default_discovery_opts(), http_provider: K8s.default_http_provider(), - cacertfile: K8s.default_cacertfile() + cacertfile: K8s.default_cacertfile(), + namespace: nil @typedoc ~S""" * `cluster_name` - The cluster name if read from a kubeconfig file * `user_name` - The user name if read from a kubeconfig file + * `namespace` - The namespace if read from a service account token * `url` - The Kubernetes API URL """ @type t :: %__MODULE__{ @@ -79,7 +81,8 @@ defmodule K8s.Conn do discovery_driver: module(), discovery_opts: Keyword.t(), http_provider: module(), - cacertfile: String.t() + cacertfile: String.t(), + namespace: String.t() } @doc ~S""" @@ -202,15 +205,23 @@ defmodule K8s.Conn do def from_service_account(service_account_path, opts) do cert_path = Path.join(service_account_path, "ca.crt") token_path = Path.join(service_account_path, "token") + namespace_path = Path.join(service_account_path, "namespace") insecure_skip_tls_verify = Keyword.get(opts, :insecure_skip_tls_verify, false) with {:ok, token} <- File.read(token_path), {:ok, ca_cert} <- PKI.cert_from_pem(cert_path) do + namespace = + case File.read(namespace_path) do + {:ok, namespace} -> namespace + _ -> nil + end + conn = %Conn{ url: kubernetes_service_url(), ca_cert: ca_cert, auth: %K8s.Conn.Auth.Token{token: token}, - insecure_skip_tls_verify: insecure_skip_tls_verify + insecure_skip_tls_verify: insecure_skip_tls_verify, + namespace: namespace } {:ok, conn} diff --git a/test/k8s/conn_test.exs b/test/k8s/conn_test.exs index e087c572..f22f2f65 100644 --- a/test/k8s/conn_test.exs +++ b/test/k8s/conn_test.exs @@ -147,7 +147,8 @@ defmodule K8s.ConnTest do assert conn.cluster_name == nil assert conn.url == "https://kewlhost:1337" assert conn.ca_cert - assert conn.auth.token + assert conn.auth.token == "imatoken" + assert conn.namespace == "imanamespace" end end diff --git a/test/support/tls/namespace b/test/support/tls/namespace new file mode 100644 index 00000000..804b2ec9 --- /dev/null +++ b/test/support/tls/namespace @@ -0,0 +1 @@ +imanamespace \ No newline at end of file diff --git a/test/support/tls/token b/test/support/tls/token index 97c9206b..5eacb697 100644 --- a/test/support/tls/token +++ b/test/support/tls/token @@ -1 +1 @@ -imatoken +imatoken \ No newline at end of file