8000 Add incluster config support · kubernetes-client/python@4b1c41f · GitHub
[go: up one dir, main page]

Skip to content

Commit 4b1c41f

Browse files
committed
Add incluster config support
1 parent 149d0ad commit 4b1c41f

File tree

3 files changed

+179
-0
lines changed

3 files changed

+179
-0
lines changed

kubernetes/config/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,5 @@
1313
# limitations under the License.
1414

1515
from .kube_config import load_kube_config
16+
from .incluster_config import load_incluster_config
17+
from .incluster_config import ConfigException

kubernetes/config/incluster_config.py

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# Copyright 2016 The Kubernetes Authors.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import os
16+
17+
from kubernetes.client import configuration
18+
19+
_SERVICE_HOST_ENV_NAME = "KUBERNETES_SERVICE_HOST"
20+
_SERVICE_PORT_ENV_NAME = "KUBERNETES_SERVICE_PORT"
21+
_SERVICE_TOKEN_FILENAME = "/var/run/secrets/kubernetes.io/serviceaccount/token"
22+
_SERVICE_CERT_FILENAME = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt"
23+
24+
25+
def _join_host_port(host, port):
26+
"""Adapted golang's net.JoinHostPort"""
27+
if ':' in host or '%' in host:
28+
return "[%s]:%s" % (host, str(port))
29+
return "%s:%s" % (host, str(port))
30+
31+
32+
class ConfigException(Exception):
33+
pass
34+
35+
36+
class InClusterConfigLoader(object):
37+
38+
def __init__(self, host_env_name, port_env_name, token_filename,
39+
cert_filename, environ=os.environ):
40+
self._host_env_name = host_env_name
41+
self._port_env_name = port_env_name
42+
self._token_filename = token_filename
43+
self._cert_filename = cert_filename
44+
self._environ = environ
45+
46+
def load(self):
47+
if (self._host_env_name not in self._environ or
48+
self._port_env_name not in self._environ):
49+
raise ConfigException("Service host/port is not set.")
50+
51+
configuration.host = (
52+
"https://" + _join_host_port(self._environ[self._host_env_name],
53+
self._environ[self._port_env_name]))
54+
55+
if not os.path.isfile(self._token_filename):
56+
raise ConfigException("Service token file does not exists.")
57+
58+
with open(self._token_filename, 'r') as f:
59+
configuration.api_key['authorization'] = "bearer " + f.read()
60+
61+
if not os.path.isfile(self._cert_filename):
62+
raise ConfigException(
63+
"Service certification file does not exists.")
64+
65+
configuration.ssl_ca_cert = self._cert_filename
66+
67+
68+
def load_incluster_config():
69+
"""Use the service account kubernetes gives to pods to connect to kubernetes
70+
cluster. It's intended for clients that expect to be running inside a pod
71+
running on kubernetes. It will raise an exception if called from a process
72+
not running in a kubernetes environment."""
73+
InClusterConfigLoader(host_env_name=_SERVICE_HOST_ENV_NAME,
74+
port_env_name=_SERVICE_PORT_ENV_NAME,
75+
token_filename=_SERVICE_TOKEN_FILENAME,
76+
cert_filename=_SERVICE_CERT_FILENAME).load()
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
# Copyright 2016 The Kubernetes Authors.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import os
16+
import tempfile
17+
import unittest
18+
19+
from kubernetes.client import configuration
20+
21+
from .incluster_config import ConfigException, InClusterConfigLoader
22+
23+
_TEST_PORT_ENV_NAME = "port"
24+
_TEST_HOST_ENV_NAME = "host"
25+
_TEST_TOKEN = "temp_token"
26+
_TEST_HOST = "127.0.0.1"
27+
_TEST_PORT = "80"
28+
_TEST_ENVIRON = {_TEST_HOST_ENV_NAME: _TEST_HOST,
29+
_TEST_PORT_ENV_NAME: _TEST_PORT}
30+
31+
32+
class InClusterConfigTest(unittest.TestCase):
33+
34+
def setUp(self):
35+
self._temp_files = []
36+
37+
def tearDown(self):
38+
for f in self._temp_files:
39+
os.remove(f)
40+
41+
def _create_file_with_temp_content(self, content=""):
42+
handler, name = tempfile.mkstemp()
43+
self._temp_files.append(name)
44+
os.write(handler, str.encode(content))
45+
os.close(handler)
46+
return name
47+
48+
def get_test_loader(
49+
self,
50+
host_env_name=_TEST_HOST_ENV_NAME,
51+
port_env_name=_TEST_PORT_ENV_NAME,
52+
token_filename=None,
53+
cert_filename=None,
54+
environ=_TEST_ENVIRON):
55+
if not token_filename:
56+
token_filename = self._create_file_with_temp_content(_TEST_TOKEN)
57+
if not cert_filename:
58+
cert_filename = self._create_file_with_temp_content()
59+
return InClusterConfigLoader(
60+
host_env_name=host_env_name,
61+
port_env_name=port_env_name,
62+
token_filename=token_filename,
63+
cert_filename=cert_filename,
64+
environ=environ)
65+
66+
def test_load_config(self):
67+
cert_filename = self._create_file_with_temp_content()
68+
self.get_test_loader(cert_filename=cert_filename).load()
69+
self.assertEqual("https://%s:%s" % (_TEST_HOST, _TEST_PORT),
70+
configuration.host)
71+
self.assertEqual(cert_filename, configuration.ssl_ca_cert)
72+
self.assertEqual("bearer %s" % _TEST_TOKEN,
73+
configuration.api_key['authorization'])
74+
75+
def _should_fail_load(self, config_loader, reason):
76+
try:
77+
config_loader.load()
78+
self.fail("Should fail because %s" % reason)
79+
except ConfigException:
80+
# expected
81+
pass
82+
83+
def test_no_port(self):
84+
loader = self.get_test_loader(port_env_name="not_exists_port")
85+
self._should_fail_load(loader, "no port specified")
86+
87+
def test_no_host(self):
88+
loader = self.get_test_loader(host_env_name="not_exists_host")
89+
self._should_fail_load(loader, "no host specified")
90+
91+
def test_no_cert_file(self):
92+
loader = self.get_test_loader(cert_filename="not_exists_file_1123")
93+
self._should_fail_load(loader, "cert file does not exists")
94+
95+
def test_no_token_file(self):
96+
loader = self.get_test_loader(token_filename="not_exists_file_1123")
97+
self._should_fail_load(loader, "token file does not exists")
98+
99+
100+
if __name__ == '__main__':
101+
unittest.main()

0 commit comments

Comments
 (0)
0