def __init__(self, config_file='/etc/kubernetes/admin.conf', logger=None, cluster=None): if cluster: config_file = cluster['kube_config_file'] cfg = client.Configuration() config.load_kube_config(config_file=config_file, client_configuration=cfg) cfg.assert_hostname = False if cluster: (proto, _, port) = cfg.host.split(':') host = proto + '://' + cluster['master_public_ip'] + ':' + port cfg.host = host cfg.verify_ssl = False self.api_client = client.ApiClient(cfg) #self.res_v1_beta1_h = client.ApiextensionsV1beta1Api(self.api_client) self.res_v1_obj_h = client.CustomObjectsApi(self.api_client) self.v1_h = client.CoreV1Api(self.api_client) self.v1_h.read_namespace('default') self.v1_beta_h = client.ExtensionsV1beta1Api(self.api_client) self.v1_networking = client.NetworkingV1Api(self.api_client) self.apps_v1_beta1_h = client.AppsV1beta1Api(self.api_client) self.logger = logger or contrail_logging.getLogger(__name__)
def __init__(self): Controller.__init__(self, "kubernetes") ConfigCaller.__init__(self) config.load_incluster_config() self.__corev1 = client.CoreV1Api() self.__networkingv1 = client.NetworkingV1Api() self.__internal_lock = Lock()
def create_policy(namespace, use_kubectl=USE_KUBECTL): if use_kubectl: response = kubemunch('create', '-n', namespace, '-f', POLICY_FILENAME) else: md = client.V1ObjectMeta(name=AWS_NETWORK_POLICY_NAME, namespace=namespace) match_expression = client.V1LabelSelectorRequirement( key='k8s-app', operator='DoesNotExist') pod_selector = client.V1LabelSelector( match_expressions=[match_expression]) ip_block = client.V1beta1IPBlock( cidr='0.0.0.0/0', _except=['169.254.0.0/16']) peer = client.V1beta1NetworkPolicyPeer(ip_block=ip_block) egress = client.V1beta1NetworkPolicyEgressRule(to=[peer]) spec = client.V1beta1NetworkPolicySpec( pod_selector=pod_selector, egress=[egress], policy_types=['Egress']) policy = client.V1beta1NetworkPolicy(metadata=md, spec=spec) networkingv1 = client.NetworkingV1Api() response = networkingv1.create_namespaced_network_policy(namespace, policy) print("\tCreated {} in ns {}".format(response.metadata.name, response.metadata.namespace))
def create_api_client(api: str = "BatchV1"): """Create Kubernetes API client using config. :param api: String which represents which Kubernetes API to spawn. By default BatchV1. :returns: Kubernetes python client object for a specific API i.e. BatchV1. """ k8s_config.load_incluster_config() api_configuration = client.Configuration() api_configuration.verify_ssl = False if api == "CoreV1": api_client = client.CoreV1Api() elif api == "StorageV1": api_client = client.StorageV1Api() elif api == "AppsV1": api_client = client.AppsV1Api() elif api == "networking.k8s.io/v1": api_client = client.NetworkingV1Api() elif api == "CustomObjectsApi": api_client = client.CustomObjectsApi() elif api == "BatchV1": api_client = client.BatchV1Api() else: raise Exception(f"Cannot create api_client of a given type: {api}") return api_client
def create_kube_apiserver_instance_client(cluster_url,service_account_secret,node_type): """ Kubernetes library have several core kinds for getting data with cluster api server. For each Object type we have different core and we should use those function to get correct and reliable result. create_kube_apiserver_instance_client function pass core instance due to node type. """ node_type=node_type.lower() configuration = kubernetes.client.Configuration() token = '%s' % (service_account_secret) configuration.api_key={"authorization":"Bearer "+ token} configuration.host = cluster_url configuration.verify_ssl=False configuration.debug = False client.Configuration.set_default(configuration) if node_type in ["pod","service","serviceaccount"]: api_client = client.CoreV1Api() if node_type in ["deployment","replicaset"]: api_client = client.AppsV1Api() if node_type in ["networkpolicy"]: api_client = client.NetworkingV1Api() if node_type in ["podsecuritypolicy"]: api_client = client.PolicyV1beta1Api() if node_type in ["rolebinding","role","clusterrole","clusterrolebinding"]: api_client = client.RbacAuthorizationV1beta1Api() return api_client
def check_kube_connection(configuration): api_instance = kube_client.NetworkingV1Api(kube_client.ApiClient(configuration)) try: api_instance.get_api_resources() except Exception as e: # pylint: disable=broad-except logger.warning("Unable to verify connectivity to the Kubernetes cluster.") utils.kubernetes_exception_handler(e, consts.Kubernetes_Connectivity_FaultType, 'Unable to verify connectivity to the Kubernetes cluster', error_message="If you are using AAD Enabled cluster, verify that you are able to access the cluster. Learn more at https://aka.ms/arc/k8s/onboarding-aad-enabled-clusters")
def k8s_net_client(k8s_conf): """ Retrieves the kubernetes networking client :param k8s_conf: the k8s configuration used to deploy the cluster :return: a kubernetes.client.NetworkingV1Api instance """ logger.debug('Retrieving K8s networking API client') return client.NetworkingV1Api(get_client_conn(k8s_conf))
def delete_ingress(name, namespace): networkingv1 = client.NetworkingV1Api() networkingv1.delete_namespaced_ingress(name=name, namespace=namespace) logger.debug("Deleted ingress resource: %s/%s" % (namespace, name)) return
def check_kube_connection(configuration): api_instance = kube_client.NetworkingV1Api(kube_client.ApiClient(configuration)) try: api_instance.get_api_resources() except Exception as e: logger.warning("Unable to verify connectivity to the Kubernetes cluster: %s\n", e) raise CLIError("If you are using AAD Enabled cluster, " + "verify that you are able to access the cluster. Learn more at " + "https://aka.ms/arc/k8s/onboarding-aad-enabled-clusters")
def get_resource_api(api_client: client.ApiClient = None, **kwargs) -> "client.NetworkingV1Api": """ Returns an instance of the kubernetes API client associated with this object. """ if api_client: kwargs["apl_client"] = api_client return client.NetworkingV1Api(**kwargs)
def remove_network_policy(name: str, ns: str = "default", secrets: Secrets = None): """ Create a network policy in the given namespace eitehr from the definition as `spec` or from a file containing the definition at `spec_path`. """ api = create_k8s_api_client(secrets) v1 = client.NetworkingV1Api(api) v1.delete_namespaced_network_policy(name, ns)
def init_clients(self): api_client = client.ApiClient(self.cfg) self.res_v1_obj_h = client.CustomObjectsApi(api_client) self.v1_h = client.CoreV1Api(api_client) self.v1_h.read_namespace('default') self.v1_beta_h = client.ExtensionsV1beta1Api(api_client) self.v1_networking = client.NetworkingV1Api(api_client) self.apps_v1_beta1_h = client.AppsV1beta1Api(api_client) self.apps_v1_h = client.AppsV1Api(api_client)
def main(): # Fetching and loading local Kubernetes Information config.load_kube_config() apps_v1_api = client.AppsV1Api() networking_v1_api = client.NetworkingV1Api() create_deployment(apps_v1_api) create_service() create_ingress(networking_v1_api)
def __init__(self, config_file='/etc/kubernetes/admin.conf', logger=None): self.api_client = config.new_client_from_config(config_file) self.api_client.configuration.assert_hostname = False self.v1_h = client.CoreV1Api(self.api_client) self.v1_h.read_namespace('default') self.v1_beta_h = client.ExtensionsV1beta1Api(self.api_client) self.v1_networking = client.NetworkingV1Api(self.api_client) self.apps_v1_beta1_h = client.AppsV1beta1Api(self.api_client) self.logger = logger or contrail_logging.getLogger(__name__)
def main(svc): g.clear() try: if svc == "svc": config.load_incluster_config() else: config.load_kube_config() v1 = client.CoreV1Api() try: v1IngressApi = client.ExtensionsV1beta1Api() except: v1IngressApi = client.NetworkingV1Api() RbacAuthorizationV1Api = client.RbacAuthorizationV1Api() AppsV1Api = client.AppsV1Api() except Exception as e: print("Not able to read Kubernetes cluster check Kubeconfig") raise RuntimeError(e) print("Getting unused secret it may take couple of minute..") GetUsedResources(v1) Secrets = DefinedSecret(v1) ExtraSecret = Diffrance(Secrets, UsedSecret) PrintList(ExtraSecret, "Secrets") print("Getting unused ConfigMap it may take couple of minute..") ConfigMap = DefinedConfigMap(v1) ExtraConfigMap = Diffrance(ConfigMap, UsedConfigMap) PrintList(ExtraConfigMap, "ConfigMap") print("Getting unused PVC it may take couple of minute..") PVC = DefinedPersistentVolumeClaim(v1) ExtraPVC = Diffrance(PVC, UsedPVC) PrintList(ExtraPVC, "PV Claim") print("Getting unused services it may take couple of minute..") UsedEP = GetUsedServices(v1) EP = DefinedSvc(v1) ExtraSVC = Diffrance(EP, UsedEP) PrintList(ExtraSVC, "Services") print("Getting unused Ingress it may take couple of minute..") DefinedIngress(v1IngressApi) ExtraIng = GetUnusedIng(EP, ExtraSVC) PrintList(ExtraIng, "Ingress") print("Getting unused service account it may take couple of minute..") SA = DefinedServiceAccount(v1) ExtraSA = Diffrance(SA, UsedSA) PrintList(ExtraSA, "Service Account") print("Getting unused Roles Binding it may take couple of minute..") _ = DefinedRoleBinding(RbacAuthorizationV1Api) ExtraRB = GetUnusedRB(SA, ExtraSA) PrintList(ExtraRB, "Role Binding") ExtraDep = GetUnusedDeployment(AppsV1Api) PrintList(ExtraDep, "Deployment") ExtraSTS = GetUnusedSTS(AppsV1Api) PrintList(ExtraSTS, "Stateful Sets") if svc == "svc": refresh_interval = (os.environ['REFRESH_INTERVAL']) time.sleep(int(refresh_interval))
def deleteNsNetPol(ns, npName): nv1 = client.NetworkingV1Api() nv1.delete_namespaced_network_policy(npName, ns, client.V1DeleteOptions()) def delChecker(): npList = nv1.list_namespaced_network_policy(ns) for np in npList.items: if np.metadata.name is npName: return "exists" return "" tutils.assertEventually(delChecker, 1, 30)
def create_network_policy(policy_name, **kwargs): networkingv1 = client.NetworkingV1Api() policy_namespace = kwargs[ 'namespace'] if 'namespace' in kwargs else 'default' policy_labels = kwargs['labels'] if 'labels' in kwargs else {} policy_annotations = kwargs[ 'annotations'] if 'annotations' in kwargs else {} match_labels = kwargs['match_labels'] if 'match_labels' in kwargs else {} match_expressions = kwargs[ 'match_expressions'] if 'match_expressions' in kwargs else [] egress = kwargs['egress'] if 'egress' in kwargs else [] ingress = kwargs['ingress'] if 'ingress' in kwargs else [] egress_len = len(egress) ingress_len = len(ingress) policy_types = \ ["Ingress", "Egress"] if ingress_len > 0 and egress_len > 0 else \ ["Ingress"] if ingress_len > 0 and egress_len == 0 else \ ["Egress"] if egress_len > 0 and ingress_len == 0 else \ [] if not policy_types: logger.warning( "Warning: Creating NetworkPolicy with empty policy_types") if not match_labels and not match_expressions: logger.warning( "Warning: Creating NetworkPolicy that would operate on all resources" ) policy = networkingv1.create_namespaced_network_policy( namespace=policy_namespace, body=client.V1NetworkPolicy( api_version='v1', kind='NetworkPolicy', metadata=client.V1ObjectMeta(name=policy_name, namespace=policy_namespace, annotations=policy_annotations, labels=policy_labels), spec=client.V1NetworkPolicySpec( egress=egress, ingress=ingress, policy_types=policy_types, pod_selector=client.V1LabelSelector( match_expressions=match_expressions, match_labels=match_labels)))) return policy
def create_ingress(ingress_name, ingress_hosts, **kwargs): networkingv1 = client.NetworkingV1Api() print("Creating ingress resource:") # TODO: Validation ingress_namespace = kwargs[ 'namespace'] if 'namespace' in kwargs else 'default' ingress_labels = kwargs['labels'] if 'labels' in kwargs else {} ingress_annotations = kwargs[ 'annotations'] if 'annotations' in kwargs else {} try: ingress = networkingv1.create_namespaced_ingress_with_http_info( ingress_namespace, client.V1Ingress( api_version='networking.k8s.io/v1', kind='Ingress', metadata=client.V1ObjectMeta( name=ingress_name, namespace=ingress_namespace, annotations=ingress_annotations, labels=ingress_labels, ), spec=client.V1IngressSpec(rules=[ client.V1IngressRule( host='%s.%s' % (stack_service_id, config.DOMAIN), http=client.V1HTTPIngressRuleValue(paths=[ client.V1HTTPIngressPath( path_type='ImplementationSpecific', path='/', # Since we use host-based routing backend=client.V1IngressBackend( service=client.V1IngressServiceBackend( name=stack_service_id, port=client.V1ServiceBackendPort( number=ingress_hosts[ stack_service_id])))) ])) for stack_service_id in ingress_hosts.keys() ]))) logger.debug("Created ingress resource: " + str(ingress)) #for i in ret.items: # logger.debug("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name)) return ingress except (ApiException, HTTPError) as exc: if isinstance(exc, ApiException) and exc.status == 409: return None else: logger.error("Error creating ingress resource: %s" % str(exc)) raise exc
def get_pods_associated_with_ingress(): log.debug("get pods associated with ingress") pods = list() v1 = client.CoreV1Api() net = client.NetworkingV1Api() ingresses = net.list_ingress_for_all_namespaces() # Poderia ser um list comprehension? Sim, mas ficaria tão dificil de ler... for ingress in ingresses.items: for rule in ingress.spec.rules: if rule.http is None: log.warning("Ingress: {} Rule: is None".format(rule.host)) continue for path in rule.http.paths: try: service = v1.read_namespaced_service(name=path.backend.service.name, namespace=ingress.metadata.namespace) except ApiException as err: log.error("Ingress: {}, error getting service: {}".format(rule.host, err)) continue try: endpoint = v1.list_namespaced_endpoints(namespace=ingress.metadata.namespace, label_selector=convert_label_selector( service.spec.selector)) except ApiException as err: log.error("Ingress: {}, error getting endpoints. ".format(rule.host, err)) continue for ep in endpoint.items: if ep.subsets is None: log.warning("The endpoint of service {} comes empty. Skipping verification".format( path.backend.service.name)) continue for subset in ep.subsets: if subset.addresses is None: log.error("The endpoint subset of service {} has no address. Skipping verification".format( path.backend.service.name )) continue for address in subset.addresses: if address.target_ref is None: log.error( "The target ref of address {} is none. Skipping verification".format( subset.addresses )) continue if address.target_ref.name not in pods: pods.append(address.target_ref.name) log.debug("Pods associated with ingress: {}".format(pods)) return pods
def fake_k8s_client_dict(): k8s_client_dict = { 'v1': client.CoreV1Api(), 'apiregistration.k8s.io/v1': client.ApiregistrationV1Api(), 'apps/v1': client.AppsV1Api(), 'authentication.k8s.io/v1': client.AuthenticationV1Api(), 'authorization.k8s.io/v1': client.AuthorizationV1Api(), 'autoscaling/v1': client.AutoscalingV1Api(), 'batch/v1': client.BatchV1Api(), 'coordination.k8s.io/v1': client.CoordinationV1Api(), 'networking.k8s.io/v1': client.NetworkingV1Api(), 'rbac.authorization.k8s.io/v1': client.RbacAuthorizationV1Api(), 'scheduling.k8s.io/v1': client.SchedulingV1Api(), 'storage.k8s.io/v1': client.StorageV1Api() } return k8s_client_dict
def delete_network_policy(): data = json.loads(request.get_data().decode("utf-8")) current_app.logger.debug("接收到的数据:{}".format(data)) name = handle_input(data.get('name')) namespace = handle_input(data.get("namespace")) if namespace == '' or namespace == 'all': return simple_error_handle("namespace不能为空,并且不能选择all") myclient = client.NetworkingV1Api() try: # body=client.V1DeleteOptions(propagation_policy='Foreground',grace_period_seconds=5) result = myclient.delete_namespaced_network_policy(namespace=namespace, name=name) except ApiException as e: body = json.loads(e.body) msg = {"status": e.status, "reason": e.reason, "message": body['message']} return jsonify({'error': 'network_policy', "msg": msg}) return jsonify({"ok": "删除成功"})
def get_network_policy_list(): data = json.loads(request.get_data().decode("utf-8")) current_app.logger.debug("policy接收的数据:{}".format(data)) namespace = handle_input(data.get("namespace")) myclient = client.NetworkingV1Api() if namespace == "" or namespace == "all": policys = myclient.list_network_policy_for_all_namespaces() else: policys =myclient.list_namespaced_network_policy(namespace=namespace) i = 0 policy_list = [] for policy in policys.items: if (i >= 0): # print(policy) meta = policy.metadata create_time = time_to_string(meta.creation_timestamp) name = meta.name namespace = meta.namespace labels = meta.labels spec = policy.spec pod_selector = spec.pod_selector policy_types = spec.policy_types egress = spec.egress ingress = spec.ingress combine_policy = {} if ingress != None: combine_policy["ingress"] = ingress if egress != None: combine_policy["egress"] = egress my_policy = {} my_policy["name"] = name my_policy["namespace"] =namespace my_policy["labels"] = labels # my_policy["egress"] = egress # my_policy["ingress"] =ingress my_policy["policy_types"] = policy_types # 源(egress) / 目标(ingress)Pod my_policy["pod_selector"] =pod_selector my_policy["combine_policy"] = combine_policy my_policy["create_time"] =create_time policy_list.append(my_policy) # print(policy_list) i= i+1 return json.dumps(policy_list,indent=4,cls=MyEncoder)
def create_network_policy(cls, name=None, namespace='default', match_labels=None, match_expressions=None, ingress_port=None, ingress_port_protocol='TCP', ingress_ipblock_cidr=None, ingress_ipblock_except=[], egress_port=None, egress_port_protocol='TCP', egress_ipblock_cidr=None, egress_ipblock_except=[]): if not name: name = data_utils.rand_name(prefix='kuryr-network-policy') np = k8s_client.V1NetworkPolicy() np.kind = 'NetworkPolicy' np.api_version = 'networking.k8s.io/v1' np.metadata = k8s_client.V1ObjectMeta(name=name, namespace=namespace) to, _from = None, None if egress_ipblock_cidr: to = [k8s_client.V1NetworkPolicyPeer( ip_block=k8s_client.V1IPBlock(cidr=egress_ipblock_cidr, _except=egress_ipblock_except))] if ingress_ipblock_cidr: _from = [k8s_client.V1NetworkPolicyPeer( ip_block=k8s_client.V1IPBlock(cidr=ingress_ipblock_cidr, _except=ingress_ipblock_except))] if ingress_port: ingress_port = [k8s_client.V1NetworkPolicyPort( port=ingress_port, protocol=ingress_port_protocol)] if egress_port: egress_port = [k8s_client.V1NetworkPolicyPort( port=egress_port, protocol=egress_port_protocol)] np.spec = k8s_client.V1NetworkPolicySpec( egress=[k8s_client.V1NetworkPolicyEgressRule( ports=egress_port, to=to)], ingress=[k8s_client.V1NetworkPolicyIngressRule( ports=ingress_port, _from=_from)], pod_selector=k8s_client.V1LabelSelector( match_expressions=match_expressions, match_labels=match_labels), policy_types=['Ingress', 'Egress']) return k8s_client.NetworkingV1Api( ).create_namespaced_network_policy(namespace=namespace, body=np)
def __init__(self, config): """ Initialize connection to Kubernetes. Connects to Kubernetes configuration using an environment appropriate method. """ super(KubernetesCompute, self).__init__() self.config = config if os.getenv('KUBERNETES_SERVICE_HOST'): """ We're running inside K8S. Load the config appropriately. """ k8s_config.load_incluster_config() else: """ We're running outside of K8S. Load the config. """ k8s_config.load_kube_config() api_client = k8s_client.ApiClient() self.api = k8s_client.CoreV1Api(api_client) self.rbac_api = k8s_client.RbacAuthorizationV1Api(api_client) self.extensions_api = k8s_client.ExtensionsV1beta1Api(api_client) self.networking_api = k8s_client.NetworkingV1Api(api_client)
def __init__(self, logger, namespace, prefix, priority, labels=None): # Try loading a kubernetes connection from either the fact that we are running # inside of a cluster, or have a config file that tells us how try: config.load_incluster_config() except config.config_exception.ConfigException: # Load the configuration once to initialize the defaults config.load_kube_config() # Now we can actually apply any changes we want to make cfg = client.configuration.Configuration(client.configuration.Configuration) if 'HTTPS_PROXY' in os.environ: cfg.proxy = os.environ['HTTPS_PROXY'] if not cfg.proxy.startswith("http"): cfg.proxy = "https://" + cfg.proxy client.Configuration.set_default(cfg) # Load again with our settings set config.load_kube_config(client_configuration=cfg) self.prefix = prefix.lower() self.priority = priority self.logger = logger self._labels = labels self.apps_api = client.AppsV1Api() self.api = client.CoreV1Api() self.net_api = client.NetworkingV1Api() self.auto_cloud = False # TODO draw from config self.namespace = namespace self.config_volumes: Dict[str, V1Volume] = {} self.config_mounts: Dict[str, V1VolumeMount] = {} # A record of previously reported events so that we don't report the same message repeatedly, fill it with # existing messages so we don't have a huge dump of duplicates on restart self.events_window = {} response = self.api.list_namespaced_event(namespace='al', pretty='false', field_selector='type=Warning', watch=False, _request_timeout=API_TIMEOUT) for event in response.items: # Keep the scaler related events in case it helps us know why scaler was restarting if 'scaler' not in event.involved_object.name: self.events_window[event.metadata.uid] = event.count
def create_namespace(self, body, message): """ Listen to the `exchange` namespace, | and create the namespace accordly to the messages. | Idempotent. :param body: The message's content. :type body: dict :param message: The namespace to create. :type message: kombu.message.Message :returns: The creation state :rtype: bool """ payload = client.V1Namespace() payload.metadata = client.V1ObjectMeta(name=body['namespace']) core_v1 = client.CoreV1Api() network_v1 = client.NetworkingV1Api() policy = client.V1NetworkPolicy(api_version='networking.k8s.io/v1', kind='NetworkPolicy') policy.metadata = client.V1ObjectMeta(name='deny-namespaces-traffic', namespace=body['namespace']) policy.spec = client.V1NetworkPolicySpec( pod_selector=client.V1LabelSelector(match_labels={}), ingress=[ client.V1NetworkPolicyIngressRule(_from=[ client.V1NetworkPolicyPeer( pod_selector=client.V1LabelSelector()) ]) ]) #Idempotent try: core_v1.create_namespace(payload) core_v1.patch_namespaced_service_account( 'default', body['namespace'], {'automount_service_account_token': False}) network_v1.create_namespaced_network_policy( body['namespace'], policy) except ApiException as e: LOGGER.error(e) if e.status != 409: # 409 == Conclict => Already exist raise message.ack() return True
def test_network_policy_hairpin_traffic(self): namespace_name, namespace = self.create_namespace() self.addCleanup(self.delete_namespace, namespace_name) svc_name, svc_pods = self.create_setup_for_service_test( namespace=namespace_name, cleanup=False, save=False, pod_num=1) self.check_service_internal_connectivity(namespace=namespace_name, pod_num=1, service_name=svc_name, pod_name=svc_pods[0]) policy_name = data_utils.rand_name(prefix='kuryr-policy') np = k8s_client.V1NetworkPolicy( kind='NetworkPolicy', api_version='networking.k8s.io/v1', metadata=k8s_client.V1ObjectMeta(name=policy_name, namespace=namespace_name), spec=k8s_client.V1NetworkPolicySpec( pod_selector=k8s_client.V1LabelSelector(), policy_types=['Egress', 'Ingress'], ingress=[ k8s_client.V1NetworkPolicyIngressRule(_from=[ k8s_client.V1NetworkPolicyPeer( pod_selector=k8s_client.V1LabelSelector(), ), ], ), ], egress=[ k8s_client.V1NetworkPolicyEgressRule(to=[ k8s_client.V1NetworkPolicyPeer( pod_selector=k8s_client.V1LabelSelector(), ), ], ), ], ), ) k8s_client.NetworkingV1Api().create_namespaced_network_policy( namespace=namespace_name, body=np) # Just to wait for SGs. self.get_sg_rules_for_np(namespace_name, policy_name) self.check_service_internal_connectivity(namespace=namespace_name, pod_num=1, service_name=svc_name, pod_name=svc_pods[0])
def kube_apis(cli_arguments) -> KubeApis: """ Set up kubernets-client to operate in cluster. :param cli_arguments: a set of command-line arguments :return: KubeApis """ context_name = cli_arguments["context"] kubeconfig = cli_arguments["kubeconfig"] config.load_kube_config(config_file=kubeconfig, context=context_name, persist_config=False) v1 = client.CoreV1Api() networking_v1 = client.NetworkingV1Api() apps_v1_api = client.AppsV1Api() rbac_v1 = client.RbacAuthorizationV1Api() api_extensions_v1 = client.ApiextensionsV1Api() custom_objects = client.CustomObjectsApi() return KubeApis(v1, networking_v1, apps_v1_api, rbac_v1, api_extensions_v1, custom_objects)
def __init__(self): check_microk8s_kube_config_file() load_kubernetes_config() self.api_client = client.ApiClient() self.custom_def_cli = client.CustomObjectsApi() self.core_cli = client.CoreV1Api() self.apps_cli = client.AppsV1Api() self.jobs_cli = client.BatchV1Api() self.cronjobs_cli = client.BatchV1beta1Api() self.rbac_cli = client.RbacAuthorizationV1Api() self.network_cli = client.NetworkingV1beta1Api() self.network_policy_cli = client.NetworkingV1Api() self.extenstion_cli = client.ExtensionsV1beta1Api() self.crd_cli = client.ApiextensionsV1beta1Api() self.storage_cli = client.StorageV1Api() self.admission_cli = client.AdmissionregistrationV1beta1Api() self.delete_options = client.V1DeleteOptions() self.delete_options.grace_period_seconds = 2 self.delete_options.propagation_policy = 'Foreground' self.core_cli.api_client.configuration.assert_hostname = False self.apps_cli.api_client.configuration.assert_hostname = False
def create_network_policy(spec: Dict[str, Any] = None, spec_path: str = None, ns: str = "default", secrets: Secrets = None): """ Create a network policy in the given namespace eitehr from the definition as `spec` or from a file containing the definition at `spec_path`. """ api = create_k8s_api_client(secrets) if spec_path and os.path.isfile(spec_path): with open(spec_path) as f: p, ext = os.path.splitext(spec_path) if ext == '.json': spec = json.loads(f.read()) elif ext in ['.yml', '.yaml']: spec = yaml.safe_load(f.read()) else: raise ActivityFailed( "cannot process {path}".format(path=spec_path)) v1 = client.NetworkingV1Api(api) v1.create_namespaced_network_policy(ns, body=spec)