Skip to content

Commit 763b0fe

Browse files
committed
create from yaml file
1 parent 8b3391f commit 763b0fe

9 files changed

+223
-39
lines changed

examples/create_from_yaml.py renamed to examples/create_deployment_from_yaml.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,16 +16,15 @@
1616

1717
import yaml
1818

19-
from kubernetes import utils, config
19+
from kubernetes import client, config, utils
2020

2121

2222
def main():
2323
# Configs can be set in Configuration class directly or using helper
2424
# utility. If no argument provided, the config will be loaded from
2525
# default location.
2626
config.load_kube_config()
27-
k8s_client, resp = utils.create_deployment_from_yaml("./nginx-deployment.yaml")
28-
print("Deployment created. status='%s'" % str(resp.status))
27+
k8s_api = utils.create_from_yaml("nginx-deployment.yaml")
2928

3029

3130
if __name__ == '__main__':

kubernetes/e2e_test/test_utils.py

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# -*- coding: utf-8 -*-
2+
3+
# Licensed under the Apache License, Version 2.0 (the "License"); you may
4+
# not use this file except in compliance with the License. You may obtain
5+
# 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, WITHOUT
11+
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12+
# License for the specific language governing permissions and limitations
13+
# under the License.
14+
15+
import unittest
16+
17+
from kubernetes import utils, client
18+
from kubernetes.e2e_test import base
19+
20+
class TestUtils(unittest.TestCase):
21+
22+
@classmethod
23+
def setUpClass(cls):
24+
cls.config = base.get_e2e_configuration()
25+
26+
def test_app_yaml(self):
27+
k8s_api = utils.create_from_yaml(
28+
"kubernetes/e2e_test/test_yaml/app.yaml",
29+
configuration=self.config)
30+
self.assertEqual("apps/v1beta1",
31+
k8s_api.get_api_resources().group_version)
32+
deployments = k8s_api.list_namespaced_deployment(
33+
namespace="default").items
34+
deployment_name = []
35+
for item in deployments:
36+
deployment_name.append(item.metadata.name)
37+
self.assertIn("nginx-app", deployment_name)
38+
resp = k8s_api.delete_namespaced_deployment(
39+
name="nginx-app", namespace="default",
40+
body={})
41+
42+
def test_extension_yaml(self):
43+
k8s_api = utils.create_from_yaml(
44+
"kubernetes/e2e_test/test_yaml/extension.yaml",
45+
configuration=self.config)
46+
self.assertEqual("extensions/v1beta1",
47+
k8s_api.get_api_resources().group_version)
48+
deployments = k8s_api.list_namespaced_deployment(
49+
namespace="default").items
50+
deployment_name = []
51+
for item in deployments:
52+
deployment_name.append(item.metadata.name)
53+
self.assertIn("nginx-deployment", deployment_name)
54+
resp = k8s_api.delete_namespaced_deployment(
55+
name="nginx-deployment", namespace="default",
56+
body={})
57+
58+
def test_core_pod_yaml(self):
59+
k8s_api = utils.create_from_yaml(
60+
"kubernetes/e2e_test/test_yaml/core-pod.yaml",
61+
configuration=self.config)
62+
self.assertEqual("v1",
63+
k8s_api.get_api_resources().group_version)
64+
pods = k8s_api.list_namespaced_pod(namespace="default").items
65+
pod_name = []
66+
for item in pods:
67+
pod_name.append(item.metadata.name)
68+
self.assertIn("myapp-pod", pod_name)
69+
resp = k8s_api.delete_namespaced_pod(
70+
name="myapp-pod", namespace="default",
71+
body={})
72+
73+
def test_core_service_yaml(self):
74+
k8s_api = utils.create_from_yaml(
75+
"kubernetes/e2e_test/test_yaml/core-service.yaml",
76+
configuration=self.config)
77+
self.assertEqual("v1",
78+
k8s_api.get_api_resources().group_version)
79+
svcs = k8s_api.list_namespaced_service(namespace="default").items
80+
svc_name = []
81+
for item in svcs:
82+
svc_name.append(item.metadata.name)
83+
self.assertIn("my-service", svc_name)
84+
resp = k8s_api.delete_namespaced_service(
85+
name="my-service", namespace="default",
86+
body={})
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
apiVersion: apps/v1beta1
2+
kind: Deployment
3+
metadata:
4+
name: nginx-app
5+
labels:
6+
app: nginx
7+
spec:
8+
replicas: 3
9+
selector:
10+
matchLabels:
11+
app: nginx
12+
template:
13+
metadata:
14+
labels:
15+
app: nginx
16+
spec:
17+
containers:
18+
- name: nginx
19+
image: nginx:1.15.4
20+
ports:
21+
- containerPort: 80
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
apiVersion: v1
2+
kind: Pod
3+
metadata:
4+
name: myapp-pod
5+
labels:
6+
app: myapp
7+
spec:
8+
containers:
9+
- name: myapp-container
10+
image: busybox
11+
command: ['sh', '-c', 'echo Hello Kubernetes! && sleep 3600']
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
kind: Service
2+
apiVersion: v1
3+
metadata:
4+
name: my-service
5+
spec:
6+
selector:
7+
app: MyApp
8+
ports:
9+
- protocol: TCP
10+
port: 80
11+
targetPort: 9376
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
apiVersion: extensions/v1beta1
2+
kind: Deployment
3+
metadata:
4+
name: nginx-deployment
5+
spec:
6+
replicas: 3
7+
template:
8+
metadata:
9+
labels:
10+
app: nginx
11+
spec:
12+
containers:
13+
- name: nginx
14+
image: nginx:1.7.9
15+
ports:
16+
- containerPort: 80
17+

kubernetes/utils/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,4 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
from .create_deployment_from_yaml import create_deployment_from_yaml
15+
from .create_from_yaml import create_from_yaml

kubernetes/utils/create_deployment_from_yaml.py

Lines changed: 0 additions & 35 deletions
This file was deleted.

kubernetes/utils/create_from_yaml.py

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
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+
from os import path
16+
import sys
17+
18+
from six import iteritems
19+
20+
import yaml
21+
22+
from kubernetes import client
23+
24+
def create_from_yaml(yaml_file, verbose=0, **kwargs):
25+
"""
26+
Perform an action from a yaml file. Pass 1 for verbose to
27+
print confirmation information.
28+
29+
Available parameters for generating the client:
30+
:param configuration: Configuration for the client.
31+
:param host: The base path for the server to call.
32+
:param header_name: a header to pass when making calls to the API.
33+
:param header_value: a header value to pass when making calls to the API.
34+
35+
Available parameters for performing the subsequent action:
36+
:param async_req bool
37+
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
38+
:param str pretty: If 'true', then the output is pretty printed.
39+
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
40+
"""
41+
42+
client_params = ["configuration", "host", "header_name", "header_value"]
43+
action_params = ["async_req", "include_unitialized", "pretty", "dry_run",
44+
'_return_http_data_only', '_preload_content', '_request_timeout']
45+
client_args = {}
46+
action_args = {}
47+
params = locals()
48+
for key, val in iteritems(params["kwargs"]):
49+
if key in client_params:
50+
client_args[key] = val
51+
elif key in action_params:
52+
action_args[key] = val
53+
54+
k8s_client = client.api_client.ApiClient(**client_args)
55+
with open(path.abspath(yaml_file)) as f:
56+
dep = yaml.load(f)
57+
api_type, _, api_version = dep["apiVersion"].partition("/")
58+
if api_version == "":
59+
api_version = api_type
60+
api_type = "core"
61+
fcn_to_call = "{0}{1}Api".format(api_type.capitalize(),
62+
api_version.capitalize())
63+
k8s_api = getattr(client, fcn_to_call)(k8s_client)
64+
action_type = dep["kind"]
65+
if "namespace" in dep["metadata"]:
66+
dep_namespace = dep["metadata"]["namespace"]
67+
else:
68+
dep_namespace = "default"
69+
resp = getattr(k8s_api, "create_namespaced_{0}".format(action_type.lower()))(
70+
body=dep, namespace=dep_namespace, **action_args)
71+
if verbose:
72+
print("{0} created. status='{1}'".format(action_type, str(resp.status)))
73+
return k8s_api
74+

0 commit comments

Comments
 (0)