11"""Service Account object for Kubernetes"""
22
3+ import yaml
4+
5+ import openshift_client as oc
6+
37from testsuite .kubernetes import KubernetesObject
4- from testsuite .kubernetes .client import KubernetesClient
58
69
710class ServiceAccount (KubernetesObject ):
811 """Kubernetest ServiceAccount"""
912
10- def __init__ (self , cluster : KubernetesClient , model : dict ):
11- self .cluster = cluster
12- super ().__init__ (model , context = cluster .context )
13-
1413 @classmethod
15- def create_instance (cls , openshift : KubernetesClient , name : str , labels : dict [str , str ] = None ):
14+ def create_instance (cls , cluster , name : str , labels : dict [str , str ] = None ):
1615 """Creates new instance of service account"""
1716 model = {
1817 "kind" : "ServiceAccount" ,
@@ -23,9 +22,38 @@ def create_instance(cls, openshift: KubernetesClient, name: str, labels: dict[st
2322 },
2423 }
2524
26- return cls (openshift , model )
25+ return cls (model , context = cluster . context )
2726
28- def get_auth_token (self , audiences : list [str ] = None ) -> str :
27+ def get_auth_token (self , audiences : list [str ] = None , duration : str = None ) -> str :
2928 """Requests and returns bound token for service account"""
30- audiences_args = [f"--audience={ a } " for a in audiences or []]
31- return self .cluster .do_action ("create" , "token" , self .name (), * audiences_args ).out ().strip ()
29+ args = ["token" , self .name ()]
30+ if audiences :
31+ args .extend ([f"--audience={ a } " for a in audiences ])
32+ if duration :
33+ args .append (f"--duration={ duration } " )
34+ with self .context :
35+ return oc .invoke ("create" , args ).out ().strip ()
36+
37+ def get_kubeconfig (self , context_name , user_name , cluster_name , api_url ) -> str :
38+ """Assembles and returns kubeconfig with service account token"""
39+ kubeconfig = {
40+ "apiVersion" : "v1" ,
41+ "kind" : "Config" ,
42+ "clusters" : [
43+ {
44+ "cluster" : {"insecure-skip-tls-verify" : True , "server" : api_url }, # insecure clusters only for now
45+ "name" : cluster_name ,
46+ }
47+ ],
48+ "contexts" : [
49+ {
50+ "context" : {"cluster" : cluster_name , "namespace" : self .context .project_name , "user" : user_name },
51+ "name" : context_name ,
52+ }
53+ ],
54+ "current-context" : context_name ,
55+ "preferences" : {},
56+ "users" : [{"name" : user_name , "user" : {"token" : self .get_auth_token (duration = "1h" )}}],
57+ }
58+
59+ return yaml .dump (kubeconfig )
0 commit comments