def setup_job_and_deployment_service_accounts(namespace: str) -> None: """Setup a jobs-and-deployments service-account with required roles. :param namespace: Namespace in which the service-account will be placed. """ service_account_object = k8s.V1ServiceAccount( metadata=k8s.V1ObjectMeta( namespace=namespace, name=BODYWORK_JOBS_DEPLOYMENTS_SERVICE_ACCOUNT ) ) k8s.CoreV1Api().create_namespaced_service_account( namespace=namespace, body=service_account_object ) role_object = k8s.V1Role( metadata=k8s.V1ObjectMeta( namespace=namespace, name=BODYWORK_JOBS_DEPLOYMENTS_SERVICE_ACCOUNT ), rules=[ k8s.V1PolicyRule( api_groups=[""], resources=["secrets", "configmaps"], verbs=["get", "list"], ) ], ) k8s.RbacAuthorizationV1Api().create_namespaced_role( namespace=namespace, body=role_object ) role_binding_object = k8s.V1RoleBinding( metadata=k8s.V1ObjectMeta( namespace=namespace, name=BODYWORK_JOBS_DEPLOYMENTS_SERVICE_ACCOUNT ), role_ref=k8s.V1RoleRef( kind="Role", name=BODYWORK_JOBS_DEPLOYMENTS_SERVICE_ACCOUNT, api_group="rbac.authorization.k8s.io", ), subjects=[ k8s.V1Subject( kind="ServiceAccount", name=BODYWORK_JOBS_DEPLOYMENTS_SERVICE_ACCOUNT, namespace=namespace, ) ], ) k8s.RbacAuthorizationV1Api().create_namespaced_role_binding( namespace=namespace, body=role_binding_object )
def api_init(host=None, token_filename=None, cert_filename=None, context=None): global CoreV1Api global RbacAuthorizationV1Api global api_temp if host and token_filename: # remotely token_filename = os.path.abspath(token_filename) if cert_filename: cert_filename = os.path.abspath(cert_filename) BearerTokenLoader(host=host, token_filename=token_filename, cert_filename=cert_filename).load_and_set() else: if running_in_docker_container(): # TODO: Consider using config.load_incluster_config() from container created by Kubernetes. Required service account with privileged permissions. # Must have mounted volume container_volume_prefix = '/tmp' kube_config_bak_path = '/KubiScan/config_bak' if not os.path.isfile(kube_config_bak_path): copyfile(container_volume_prefix + os.path.expandvars('$CONF_PATH'), kube_config_bak_path) replace(kube_config_bak_path, ': /', ': /tmp/') config.load_kube_config(kube_config_bak_path, context=context) else: config.load_kube_config(context=context) CoreV1Api = client.CoreV1Api() RbacAuthorizationV1Api = client.RbacAuthorizationV1Api() api_temp = ApiClientTemp()
def __init__(self): config.load_kube_config() self.K8SAppsV1Client = client.AppsV1Api() self.K8SCoreV1Client = client.CoreV1Api() self.K8SStorageV1Client = client.StorageV1Api() self.K8SRbacAuthorizationV1Client = client.RbacAuthorizationV1Api() self.K8SPolicyV1beta1Client = client.PolicyV1beta1Api()
def get_rbac_api_instance(self, custom_token_auth=None): if custom_token_auth == None: """ Use default auth mounted into pod """ self.__set_default_auth() else: self.__get_custom_token_auth(custom_token_auth) return client.RbacAuthorizationV1Api()
def get_cluster_role_list(): myclient = client.RbacAuthorizationV1Api() cluster_roles = myclient.list_cluster_role() i = 0 cluster_role_list = [] for cluster_role in cluster_roles.items: if (i >= 0): # print(cluster_role) meta = cluster_role.metadata create_time = time_to_string(meta.creation_timestamp) name = meta.name labels = meta.labels rules = cluster_role.rules rule_list = [] if rules != None: for rule in rules: # print(rule) my_rule = {} my_rule['api_groups'] = rule.api_groups my_rule['resources'] = rule.resources my_rule['verbs'] = rule.verbs rule_list.append(my_rule) my_cluster_role = {} my_cluster_role["name"] = name # my_cluster_role["labels"] = labels my_cluster_role["rule_list"] = rule_list my_cluster_role["create_time"] = create_time cluster_role_list.append(my_cluster_role) # print(cluster_role_list) i = i + 1 return json.dumps(cluster_role_list, indent=4, cls=MyEncoder)
def get_cluster_role_detail(): data = json.loads(request.get_data().decode("utf-8")) current_app.logger.debug("收到的数据:{}".format(data)) cluster_role_name = handle_input(data.get('name')) myclient = client.RbacAuthorizationV1Api() field_selector = "metadata.name={}".format(cluster_role_name) cluster_roles = myclient.list_cluster_role(field_selector=field_selector) cluster_role = None for item in cluster_roles.items: if item.metadata.name == cluster_role_name: cluster_role = item break if cluster_role == None: return simple_error_handle("找不到cluster_role相关信息") meta = cluster_role.metadata name = meta.name create_time = time_to_string(meta.creation_timestamp) rules = cluster_role.rules rule_list = [] if rules != None: for rule in rules: # print(rule) my_rule = {} my_rule['api_groups'] = rule.api_groups my_rule['resources'] = rule.resources my_rule['verbs'] = rule.verbs rule_list.append(my_rule) my_cluster_role_detail = { "name": name, "rule_list": rule_list, "create_time": create_time, } # print(my_cluster_role_detail) return json.dumps(my_cluster_role_detail, indent=4, cls=MyEncoder)
def manager_service_account(kubernetes_client, namespace): try: path = YAML_DIR + "pods-list-role-binding.yaml" def create_role_binding() -> None: cmd = "kubectl apply -f {}".format(path) run_kubectl_command(cmd) yield create_role_binding() finally: body = client.V1DeleteOptions() client.CoreV1Api().delete_namespaced_service_account( SERVICE_ACCOUNT, NAMESPACE, body) client.RbacAuthorizationV1Api().delete_cluster_role("pods-list", body) client.RbacAuthorizationV1Api().delete_cluster_role_binding( "pods-list", body)
def create_k8s_rolebinding(self, k8s_role, aws_user): """Create k8s role-binding for specified role and user.""" rolebinding_name = self.generate_rolebinding_name() label_selector = self.label_selector.split('=') role_binding = client.V1RoleBinding( metadata=client.V1ObjectMeta( namespace=self.namespace, name=rolebinding_name, labels={label_selector[0]: label_selector[1]}, annotations={ self.expire_annotation: str(int(self.now + self.DAY_AND_NIGHT)) }), subjects=[ client.V1Subject(name=aws_user, kind="User", api_group="rbac.authorization.k8s.io") ], role_ref=client.V1RoleRef(kind="Role", api_group="rbac.authorization.k8s.io", name=k8s_role)) self.rbac_api = client.RbacAuthorizationV1Api() try: self.rbac_api.create_namespaced_role_binding( namespace=self.namespace, body=role_binding) except ApiException as e: print( "Exception when calling RbacAuthorizationV1Api->create_namespaced_role_binding: %s\n" % e) return rolebinding_name
def test_a_create_user_cluster_role(self): # create service account and cluster role bindings try: utils.create_from_yaml( aApiClient, filepath + "cluster/files/" + "dashboard-adminuser.yaml") core_api = client.CoreV1Api(aApiClient) user_resp = core_api.read_namespaced_service_account( name="admin-user", namespace="kube-system") #print("user response %s " %user_resp) self.assertIsNotNone(user_resp) rbac_body = utils.create_from_yaml( aApiClient, filepath + "cluster/files/" + "dashboard-adminrolebind.yaml") rbac_api = client.RbacAuthorizationV1Api(aApiClient) cluster_resp = rbac_api.read_cluster_role_binding( name="admin-user") #print("cluster response %s " %cluster_resp) self.assertIsNotNone(user_resp) except ApiException as e: print("Exception creating user role: %s\n" % e) # tidy up created settings """ try: