def clusterrolebindings_from_marker(item, namespace): """Create ClusterRoleBindings for the test case if the test case is marked with the `pytest.mark.clusterrolebinding` marker. Args: item (pytest.Item): The pytest test item. namespace (str): The namespace of the test case. Return: list[objects.ClusterRoleBinding]: The ClusterRoleBindings that were generated from the test case markers. """ clusterrolebindings = [] for mark in item.iter_markers(name='clusterrolebinding'): name = mark.args[0] subj_kind = mark.kwargs.get('subject_kind') subj_name = mark.kwargs.get('subject_name') subj = get_custom_rbac_subject(namespace, subj_kind, subj_name) if not subj: subj = get_default_rbac_subjects(namespace) clusterrolebindings.append(ClusterRoleBinding(client.V1ClusterRoleBinding( metadata=client.V1ObjectMeta( name='kubetest:{}'.format(item.name), ), role_ref=client.V1RoleRef( api_group='rbac.authorization.k8s.io', kind='ClusterRole', name=name, ), subjects=subj, ))) return clusterrolebindings
def create_namespace_rolebinding(self, namespace: str, metadata: client.V1ObjectMeta, role_ref: client.V1RoleRef, subjects: List[client.V1Subject]): """ Create a role binding in a namespace Args: namespace: namespace name metadata: metadata for role binding role_ref: Role reference for the binding subjects: list of subjects for the binding Returns: V1ClusterRoleBinding object Raises: ApiException if something wrong with binding creation Examples: create_rolebinding( metadata = client.V1ObjectMeta( name="role-bind-name", namespace='namespace-name' ), role_ref = client.V1RoleRef( api_group='rbac.authorization.k8s.io', kind='ClusterRole', name='cluster-admin' ), subjects = [ client.V1Subject( kind='ServiceAccount', name='default', namespace='namespace-name' ) ] """ body = client.V1ClusterRoleBinding(metadata=metadata, role_ref=role_ref, subjects=subjects) exception_count = 3 while True: try: api_response = self.rbac_v1. \ create_namespaced_role_binding(namespace, body) except ApiException as e_obj: utilprocs.log( ("Exception when calling RbacAuthorizationV1Api->" "create_cluster_role_binding: {}".format(e_obj))) exception_count -= 1 if exception_count <= 0: raise continue return api_response
def create_cluster_role_binding(): """ Create IBM Spectrum Scale CSI Operator ClusterRoleBinding object in Operator namepsace Args: None Returns: None Raises: Raises an exception on kubernetes client api failure and asserts """ cluster_role_binding_api_instance = client.RbacAuthorizationV1Api() pretty = True cluster_role_binding_labels = { "app.kubernetes.io/instance": "ibm-spectrum-scale-csi-operator", "app.kubernetes.io/managed-by": "ibm-spectrum-scale-csi-operator", "app.kubernetes.io/name": "ibm-spectrum-scale-csi-operator", "product": "ibm-spectrum-scale-csi", "release": "ibm-spectrum-scale-csi-operator" } cluster_role_binding_metadata = client.V1ObjectMeta( name="ibm-spectrum-scale-csi-operator", labels=cluster_role_binding_labels, namespace=namespace_value) cluster_role_binding_role_ref = client.V1RoleRef( api_group="rbac.authorization.k8s.io", kind="ClusterRole", name="ibm-spectrum-scale-csi-operator") cluster_role_binding_subjects = client.V1Subject( kind="ServiceAccount", name="ibm-spectrum-scale-csi-operator", namespace=namespace_value) cluster_role_binding_body = client.V1ClusterRoleBinding( kind='ClusterRoleBinding', api_version='rbac.authorization.k8s.io/v1', metadata=cluster_role_binding_metadata, role_ref=cluster_role_binding_role_ref, subjects=[cluster_role_binding_subjects]) try: LOGGER.info("creating cluster role binding") cluster_role_binding_api_response = cluster_role_binding_api_instance.create_cluster_role_binding( cluster_role_binding_body, pretty=pretty) LOGGER.debug(cluster_role_binding_api_response) except ApiException as e: LOGGER.error( f"Exception when calling RbacAuthorizationV1Api->create_cluster_role_binding: {e}" ) assert False
def _cluster_role_binding(self): return client.V1ClusterRoleBinding( api_version='rbac.authorization.k8s.io/v1', kind='ClusterRoleBinding', metadata=metadata( name=self.name, labels=self.labels, ), role_ref=client.V1RoleRef(api_group='rbac.authorization.k8s.io', kind='ClusterRole', name=self.name), subjects=[ client.V1Subject(kind='ServiceAccount', name=self.name, namespace=self.namespace) ])
def create_quick_clusterrolebinding_definition(clusterRoleBindingName, clusterRoleName, serviceAccountName, saNamespace, annotationsDict={}): clusterrole = client.V1RoleRef(api_group="rbac.authorization.k8s.io", kind="ClusterRole", name=clusterRoleName) subjectsList = client.V1Subject(kind="ServiceAccount", name=serviceAccountName, namespace=saNamespace) clusterRoleBinding = client.V1ClusterRoleBinding( api_version="rbac.authorization.k8s.io/v1", kind="ClusterRoleBinding", metadata=client.V1ObjectMeta(name=clusterRoleBindingName, annotations=annotationsDict), role_ref=clusterrole, subjects=[subjectsList]) return clusterRoleBinding
def get_token(): config.load_kube_config() v1 = client.CoreV1Api() rbac_v1 = client.RbacAuthorizationV1Api() try: v1.read_namespace(name="auto-istio", pretty=True) except client.rest.ApiException: metadata = {"name": "auto-istio"} namespace = client.V1Namespace(api_version="v1", kind="Namespace", metadata=metadata) v1.create_namespace(namespace) try: rbac_v1.read_cluster_role_binding(name="auto_istio_binding", pretty=True) except client.rest.ApiException: metadata = {"name": "auto_istio_binding"} subjects = [{ "kind": "ServiceAccount", "name": "default", "namespace": "auto-istio" }] role_ref = { "kind": "ClusterRole", "name": "cluster-admin", "apiGroup": "rbac.authorization.k8s.io" } cluster_role_binding = client.V1ClusterRoleBinding( api_version="rbac.authorization.k8s.io/v1", kind="ClusterRoleBinding", metadata=metadata, subjects=subjects, role_ref=role_ref) rbac_v1.create_cluster_role_binding(cluster_role_binding) service_account = v1.read_namespaced_service_account( namespace="auto-istio", name="default") secret = v1.read_namespaced_secret(namespace='auto-istio', name=service_account.secrets[0].name) return base64.b64decode(secret.data['token']).decode("utf-8")
def create_cluster_role_binding(self, cluster_role_binding_name, user_name, cluster_role_name): """Create role binding using name=role_binding_name in namespace connecting role_name using service_account_name""" metadata = client.V1ObjectMeta(name=cluster_role_binding_name) role = client.V1RoleRef(kind="ClusterRole", name=cluster_role_name, api_group="rbac.authorization.k8s.io") subject = client.V1Subject(kind="User", name=user_name) body = client.V1ClusterRoleBinding(subjects=[subject], metadata=metadata, role_ref=role) try: self.rbac_cli.create_cluster_role_binding(body=body) logger.info('Created cluster role binding {}'.format( cluster_role_binding_name)) return True except client.rest.ApiException as e: self.check_create_error_and_response(e, "ClusterRoleBinding", cluster_role_binding_name) return False
def clusterrolebindings_from_marker( item: pytest.Item, namespace: str) -> List[ClusterRoleBinding]: """Create ClusterRoleBindings for the test case if the test case is marked with the `pytest.mark.clusterrolebinding` marker. Args: item: The pytest test item. namespace: The namespace of the test case. Return: The ClusterRoleBindings which were generated from the test case markers. """ clusterrolebindings = [] for mark in item.iter_markers(name="clusterrolebinding"): name = mark.args[0] subj_kind = mark.kwargs.get("subject_kind") subj_name = mark.kwargs.get("subject_name") subj = get_custom_rbac_subject(namespace, subj_kind, subj_name) if not subj: subj = get_default_rbac_subjects(namespace) clusterrolebindings.append( ClusterRoleBinding( client.V1ClusterRoleBinding( metadata=client.V1ObjectMeta( name=f"kubetest:{item.name}", ), role_ref=client.V1RoleRef( api_group="rbac.authorization.k8s.io", kind="ClusterRole", name=name, ), subjects=subj, ))) return clusterrolebindings
def setup_workflow_service_account(namespace: str) -> None: """Setup a workflow controller 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_WORKFLOW_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_WORKFLOW_SERVICE_ACCOUNT), rules=[ k8s.V1PolicyRule(api_groups=[''], resources=['*'], verbs=['*']), k8s.V1PolicyRule(api_groups=['apps', 'batch'], resources=['*'], verbs=['*']) ]) k8s.RbacAuthorizationV1Api().create_namespaced_role(namespace=namespace, body=role_object) role_binding_object = k8s.V1RoleBinding( metadata=k8s.V1ObjectMeta(namespace=namespace, name=BODYWORK_WORKFLOW_SERVICE_ACCOUNT), role_ref=k8s.V1RoleRef(kind='Role', name=BODYWORK_WORKFLOW_SERVICE_ACCOUNT, api_group='rbac.authorization.k8s.io'), subjects=[ k8s.V1Subject(kind='ServiceAccount', name=BODYWORK_WORKFLOW_SERVICE_ACCOUNT, namespace=namespace) ]) k8s.RbacAuthorizationV1Api().create_namespaced_role_binding( namespace=namespace, body=role_binding_object) if not cluster_role_exists(BODYWORK_WORKFLOW_CLUSTER_ROLE): cluster_role_object = k8s.V1ClusterRole( metadata=k8s.V1ObjectMeta(name=BODYWORK_WORKFLOW_CLUSTER_ROLE), rules=[ k8s.V1PolicyRule(api_groups=[''], resources=['namespaces'], verbs=['get', 'list']), k8s.V1PolicyRule(api_groups=['rbac.authorization.k8s.io'], resources=['clusterrolebindings'], verbs=['get', 'list']) ]) k8s.RbacAuthorizationV1Api().create_cluster_role( body=cluster_role_object) if not cluster_role_binding_exists( workflow_cluster_role_binding_name(namespace)): cluster_role_binding_object = k8s.V1ClusterRoleBinding( metadata=k8s.V1ObjectMeta( name=workflow_cluster_role_binding_name(namespace), namespace=namespace), role_ref=k8s.V1RoleRef(kind='ClusterRole', name=BODYWORK_WORKFLOW_CLUSTER_ROLE, api_group='rbac.authorization.k8s.io'), subjects=[ k8s.V1Subject(kind='ServiceAccount', name=BODYWORK_WORKFLOW_SERVICE_ACCOUNT, namespace=namespace) ]) k8s.RbacAuthorizationV1Api().create_cluster_role_binding( body=cluster_role_binding_object)
def setup_workflow_service_account(namespace: str) -> None: """Setup a workflow controller 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_WORKFLOW_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_WORKFLOW_SERVICE_ACCOUNT ), rules=[ k8s.V1PolicyRule(api_groups=[""], resources=["*"], verbs=["*"]), k8s.V1PolicyRule( api_groups=["apps", "batch"], resources=["*"], verbs=["*"] ), k8s.V1PolicyRule( api_groups=["extensions"], resources=["ingresses"], verbs=["*"] ), ], ) k8s.RbacAuthorizationV1Api().create_namespaced_role( namespace=namespace, body=role_object ) role_binding_object = k8s.V1RoleBinding( metadata=k8s.V1ObjectMeta( namespace=namespace, name=BODYWORK_WORKFLOW_SERVICE_ACCOUNT ), role_ref=k8s.V1RoleRef( kind="Role", name=BODYWORK_WORKFLOW_SERVICE_ACCOUNT, api_group="rbac.authorization.k8s.io", ), subjects=[ k8s.V1Subject( kind="ServiceAccount", name=BODYWORK_WORKFLOW_SERVICE_ACCOUNT, namespace=namespace, ) ], ) k8s.RbacAuthorizationV1Api().create_namespaced_role_binding( namespace=namespace, body=role_binding_object ) if not cluster_role_exists(BODYWORK_WORKFLOW_CLUSTER_ROLE): cluster_role_object = k8s.V1ClusterRole( metadata=k8s.V1ObjectMeta(name=BODYWORK_WORKFLOW_CLUSTER_ROLE), rules=[ k8s.V1PolicyRule( api_groups=[""], resources=["namespaces"], verbs=["get", "list"] ), k8s.V1PolicyRule( api_groups=["rbac.authorization.k8s.io"], resources=["clusterrolebindings"], verbs=["get", "list"], ), ], ) k8s.RbacAuthorizationV1Api().create_cluster_role(body=cluster_role_object) if not cluster_role_binding_exists(workflow_cluster_role_binding_name(namespace)): cluster_role_binding_object = k8s.V1ClusterRoleBinding( metadata=k8s.V1ObjectMeta( name=workflow_cluster_role_binding_name(namespace), namespace=namespace ), role_ref=k8s.V1RoleRef( kind="ClusterRole", name=BODYWORK_WORKFLOW_CLUSTER_ROLE, api_group="rbac.authorization.k8s.io", ), subjects=[ k8s.V1Subject( kind="ServiceAccount", name=BODYWORK_WORKFLOW_SERVICE_ACCOUNT, namespace=namespace, ) ], ) k8s.RbacAuthorizationV1Api().create_cluster_role_binding( body=cluster_role_binding_object )
def process_admin_rbac(self, username: str) -> None: # Let admins read anything try: _ = self.rbac.create_cluster_role_binding( body=client.V1ClusterRoleBinding( api_version="rbac.authorization.k8s.io/v1", kind="ClusterRoleBinding", metadata=client.V1ObjectMeta( name=f"{username}-view-binding"), role_ref=client.V1RoleRef( kind="ClusterRole", name="view", api_group="rbac.authorization.k8s.io", ), subjects=[ client.V1Subject( kind="User", name=username, api_group="rbac.authorization.k8s.io", ) ], )) except ApiException as api_ex: if api_ex.status == 409 and "AlreadyExists" in api_ex.body: logging.info( "ClusterRoleBinding %s-view-binding already exists", username, ) return logging.error("Could not create view clusterrolebinding for %s", username) raise # Also let admins impersonate anything, allowing full sudo access try: _ = self.rbac.create_cluster_role_binding( body=client.V1ClusterRoleBinding( api_version="rbac.authorization.k8s.io/v1", kind="ClusterRoleBinding", metadata=client.V1ObjectMeta(name=f"{username}-binding"), role_ref=client.V1RoleRef( kind="ClusterRole", name="k8s-admin", api_group="rbac.authorization.k8s.io", ), subjects=[ client.V1Subject( kind="User", name=username, api_group="rbac.authorization.k8s.io", ) ], )) except ApiException as api_ex: if api_ex.status == 409 and "AlreadyExists" in api_ex.body: logging.info("ClusterRoleBinding %s-binding already exists", username) return logging.error("Could not create admin clusterrolebinding for %s", username) raise
def run(namespace, tmpVolumeSize, outputVolumeSize, volumeName, storage_class_name=None, imagepullsecrets=None, ades_namespace=None, state=None): print( f"Preparing {namespace} tmpVolumeSize: {tmpVolumeSize} outputVolumeSize: {outputVolumeSize} volumeName: {volumeName}" ) apiclient = helpers.get_api_client() api_instance = client.RbacAuthorizationV1Api(apiclient) v1 = client.CoreV1Api(api_client=apiclient) print("####################################") print("######### Checking if namespace already exists") try: v1.read_namespace(namespace, pretty=True) print("Namespace already exists") return {"status": "success"} except ApiException as e: if e.status == 404: print("Namespace does not exists and will be created") else: print("Exception when creating namespace: %s\n" % e, file=sys.stderr) raise e ### Creating namespace print("####################################") print("######### Creating namespace") try: body = client.V1Namespace(metadata=client.V1ObjectMeta(name=namespace)) namespace_json = v1.create_namespace(body=body, async_req=False) print(str(namespace_json)) except ApiException as e: print("Exception when creating namespace: %s\n" % e, file=sys.stderr) raise e #### Creating pod manager role print("####################################") print("######### Creating pod_manager_role") metadata = client.V1ObjectMeta(name='pod-manager-role', namespace=namespace) rule = client.V1PolicyRule( api_groups=['*'], resources=['pods', 'pods/log'], verbs=['create', 'patch', 'delete', 'list', 'watch']) rules = [] rules.append(rule) body = client.V1Role(metadata=metadata, rules=rules) pretty = True try: api_response = api_instance.create_namespaced_role(namespace, body, pretty=pretty) pprint(api_response) except ApiException as e: print("Exception when creating pod-manager-role: %s\n" % e, file=sys.stderr) raise e #### Creating log-reader-role print("####################################") print("######### Creating log-reader-role") metadata = client.V1ObjectMeta(name='log-reader-role', namespace=namespace) rule = client.V1PolicyRule( api_groups=['*'], resources=['pods', 'pods/log'], verbs=['create', 'patch', 'delete', 'list', 'watch']) # verbs=['get', 'list']) rules = [] rules.append(rule) body = client.V1Role(metadata=metadata, rules=rules) pretty = True try: api_response = api_instance.create_namespaced_role(namespace, body, pretty=pretty) pprint(api_response) except ApiException as e: print("Exception when creating pod-manager-role: %s\n" % e, file=sys.stderr) raise e print("####################################") print("######### Creating pod-manager-default-binding") metadata = client.V1ObjectMeta(name='pod-manager-default-binding', namespace=namespace) role_ref = client.V1RoleRef(api_group='', kind='Role', name='pod-manager-role') subject = client.models.V1Subject(api_group='', kind='ServiceAccount', name='default', namespace=namespace) subjects = [] subjects.append(subject) body = client.V1RoleBinding(metadata=metadata, role_ref=role_ref, subjects=subjects) pretty = True try: api_response = api_instance.create_namespaced_role_binding( namespace, body, pretty=pretty) pprint(api_response) except ApiException as e: print("Exception when creating pod-manager-default-binding: %s\n" % e, file=sys.stderr) raise e print("####################################") print("######### Creating log-reader-default-binding") metadata = client.V1ObjectMeta(name='log-reader-default-binding', namespace=namespace) role_ref = client.V1RoleRef(api_group='', kind='Role', name='log-reader-role') subject = client.models.V1Subject(api_group='', kind='ServiceAccount', name='default', namespace=namespace) subjects = [] subjects.append(subject) body = client.V1RoleBinding(metadata=metadata, role_ref=role_ref, subjects=subjects) pretty = True try: api_response = api_instance.create_namespaced_role_binding( namespace, body, pretty=pretty) pprint(api_response) except ApiException as e: print("Exception when creating log-reader-default-binding: %s\n" % e, file=sys.stderr) raise e print("####################################") print("######### Creating cluster-role-binding") metadata = client.V1ObjectMeta(name=f"{namespace}-rbac", namespace=namespace) role_ref = client.V1RoleRef(api_group='rbac.authorization.k8s.io', kind='ClusterRole', name='cluster-admin') subject = client.models.V1Subject(api_group='', kind='ServiceAccount', name='default', namespace=namespace) subjects = [] subjects.append(subject) body = client.V1ClusterRoleBinding(metadata=metadata, role_ref=role_ref, subjects=subjects) pretty = True try: api_response = api_instance.create_cluster_role_binding(body=body, pretty=pretty) pprint(api_response) except ApiException as e: if e.status == 409: print( f"cluster-role-binding {namespace}-rbac has already been installed" ) else: print("Exception when creating cluster-role-binding: %s\n" % e, file=sys.stderr) raise e print("####################################") print("######### Creating Persistent Volume Claims") # metadata1 = client.V1ObjectMeta(name=f"{volumeName}-input-data", namespace=namespace) # spec1 = client.V1PersistentVolumeClaimSpec( # # must be ReadWriteOnce for EBS # # access_modes=["ReadWriteOnce", "ReadOnlyMany"], # access_modes=["ReadWriteMany"], # resources=client.V1ResourceRequirements( # requests={"storage": inputVolumeSize} # ) # ) # # if storage_class_name: # spec1.storage_class_name = storage_class_name # # body1 = client.V1PersistentVolumeClaim(metadata=metadata1, spec=spec1) metadata2 = client.V1ObjectMeta(name=f"{volumeName}-tmpout", namespace=namespace) spec2 = client.V1PersistentVolumeClaimSpec( access_modes=["ReadWriteMany"], resources=client.V1ResourceRequirements( requests={"storage": tmpVolumeSize})) if storage_class_name: spec2.storage_class_name = storage_class_name body2 = client.V1PersistentVolumeClaim(metadata=metadata2, spec=spec2) metadata3 = client.V1ObjectMeta(name=f"{volumeName}-output-data", namespace=namespace) spec3 = client.V1PersistentVolumeClaimSpec( access_modes=["ReadWriteMany"], resources=client.V1ResourceRequirements( requests={"storage": outputVolumeSize})) if storage_class_name: spec3.storage_class_name = storage_class_name body3 = client.V1PersistentVolumeClaim(metadata=metadata3, spec=spec3) pretty = True try: # api_response1 = v1.create_namespaced_persistent_volume_claim(namespace, body1, pretty=pretty) api_response2 = v1.create_namespaced_persistent_volume_claim( namespace, body2, pretty=pretty) api_response3 = v1.create_namespaced_persistent_volume_claim( namespace, body3, pretty=pretty) # pprint(api_response1) pprint(api_response2) pprint(api_response3) except ApiException as e: print("Exception when creating persistent_volume_claim: %s\n" % e, file=sys.stderr) raise e # we copy the secret from ades namespace to the new job namespace if imagepullsecrets is not None and ades_namespace is not None: for imagepullsecret in imagepullsecrets: # Create an instance of the API class secretname = imagepullsecret["name"] pretty = True # str | If 'true', then the output is pretty printed. (optional) exact = False # bool | Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'. Deprecated. Planned for removal in 1.18. (optional) export = True # bool | Should this value be exported. Export strips fields that a user can not specify. Deprecated. Planned for removal in 1.18. (optional) secret_export = None try: secret_export = v1.read_namespaced_secret(secretname, ades_namespace, pretty=pretty, exact=exact, export=export) except ApiException as e: print( "Exception when retrieving image pull secret from eoepca: %s\n" % e) time.sleep(5) try: api_response = v1.create_namespaced_secret(namespace, secret_export, pretty=pretty) except ApiException as e: print("Exception when creating image pull secret: %s\n" % e) time.sleep(5) name = 'default' try: service_account_body = v1.read_namespaced_service_account( name, namespace, pretty=True) pprint(service_account_body) time.sleep(5) if service_account_body.secrets is None: service_account_body.secrets = [] if service_account_body.image_pull_secrets is None: service_account_body.image_pull_secrets = [] service_account_body.secrets.append({"name": secretname}) service_account_body.image_pull_secrets.append( {"name": secretname}) api_response = v1.patch_namespaced_service_account( name, namespace, service_account_body, pretty=True) pprint(api_response) except ApiException as e: print( "Exception when calling CoreV1Api->patch_namespaced_service_account: %s\n" % e) return {"status": "success"}