def _createKubeSecret(args,CorV1Client=None): print("create Secret for current environment") # Create Certificate print("Create Certificate") metadata = {'name': args.tenant+args.env+args.envtype+'-certificate', 'namespace': args.namespace} #data= {'tls.crt': '###BASE64 encoded crt###', 'tls.key': '###BASE64 encoded Key###'} tls_crt_encrypt=base64EncryptCerts(CURDIR+CA_CERT) print('tls_crt_encrypt is %s' %(tls_crt_encrypt)) tls_key_encrypt=base64EncryptCerts(CURDIR+CA_KEY) print('tls_key_encrypt is %s' % (tls_key_encrypt)) data = {'tls.crt': tls_crt_encrypt, 'tls.key': tls_key_encrypt} api_version = "v1" kind = 'Secret' body = client.V1Secret(api_version, data, kind, metadata,type='kubernetes.io/tls') api_response = CorV1Client.create_namespaced_secret(args.namespace, body) print(api_response) # Create Certificate Public Key print("Create Certificate Public Key") metadata = {'name': args.tenant + args.env + args.envtype + '-dhparam', 'namespace': args.namespace} # data= {'tls.crt': '###BASE64 encoded crt###', 'tls.key': '###BASE64 encoded Key###'} publickey_encrypt = base64EncryptCerts(CURDIR + CA_PUBLISH_KEY) print('publickey_encrypt is %s' %(publickey_encrypt)) data = {'tls_public_key.pem': publickey_encrypt} api_version = "v1" kind = 'Secret' body = client.V1Secret(api_version, data, kind, metadata, type='Opaque') api_response = CorV1Client.create_namespaced_secret(args.namespace, body) print(api_response)
def main(): pod_namespace = os.getenv('MY_POD_NAMESPACE') if pod_namespace is None: _err_write('MY_POD_NAMESPACE is not set, see example/deploy.yaml') exit(1) htpasswd_secret_name = os.getenv('HTPASSWD_SECRET_NAME') if htpasswd_secret_name is None: _err_write('HTPASSWD_SECRET_NAME is not set, see example/deploy.yaml') exit(1) password_secret_name = os.getenv('PASSWORD_SECRET_NAME') if password_secret_name is None: _err_write('PASSWORD_SECRET_NAME is not set, see example/deploy.yaml') exit(1) registry_username = os.getenv('REGISTRY_USERNAME') if registry_username is None: _err_write('REGISTRY_USERNAME is not set, see example/deploy.yaml') exit(1) config.load_incluster_config() alphabet = string.ascii_letters + string.digits password = ''.join(secrets.choice(alphabet) for i in range(20)) out = subprocess.check_output( ['htpasswd', '-bn', registry_username, password]).decode('utf-8') v1 = client.CoreV1Api() try: v1.create_namespaced_secret(namespace=pod_namespace, body=client.V1Secret( string_data={'auth': out}, metadata={ 'name': htpasswd_secret_name, })) v1.create_namespaced_secret( namespace=pod_namespace, body=client.V1Secret(string_data={'password': password}, metadata={'name': password_secret_name})) print('Successfully created {} and {} secrets.'.format( htpasswd_secret_name, password_secret_name)) except ApiException as e: if e.reason == 'Conflict': print('Secret(s) already exist. Will not do anything.') else: raise while True: time.sleep(1000000)
def create_secret(self): ''' Create secret: https://docs.opsmanager.mongodb.com/current/tutorial/install-k8s-operator/index.html#create-credentials Equivalent to execute: kubectl -n mongodb create secret generic \ my-credentials --from-literal="user=<*****@*****.**>" \ --from-literal="publicApiKey=<my-public-api-key>" ''' print("Creating secret for user named %s with the provided API key" % self.om_api_user) metadata = client.V1ObjectMeta(name="my-credentials", namespace=self.namespace) # Encode credentials encoded_user = base64encode(self.om_api_user) encoded_key = base64encode(self.om_api_key) # Transform binary into string encoded_user = encoded_user.decode("utf-8").rstrip("\n") encoded_key = encoded_key.decode("utf-8").rstrip("\n") body = client.V1Secret(api_version="v1", kind="Secret", metadata=metadata, type="from-literal", data={"user": encoded_user, "publicApiKey": encoded_key}) try: api_response = self.v1.create_namespaced_secret(self.namespace, body) pprint(api_response) except ApiException as e: print("Exception when creating secret: %s\n" % e)
def create_or_update_secret(self, data, metadata, secret_type, name, namespace='default'): """Create secret. If existed, then replace""" request = client.V1Secret(api_version='v1', data=data, kind='Secret', metadata=metadata, type=secret_type) try: self._core.read_namespaced_secret(name, namespace) # If the secret already exists, then we use patch to replace it. # We don't use replace method because it requires `resourceVersion`. self._core.patch_namespaced_secret(name, namespace, request) return except ApiException as e: # 404 is expected if the secret does not exist if e.status != HTTPStatus.NOT_FOUND: self._raise_runtime_error(e) try: self._core.create_namespaced_secret(namespace, request) except ApiException as e: self._raise_runtime_error(e)
def create_certs_secret(namespace, secret_name, cert_dir): clear_secret(namespace, secret_name) passphrase = getpass.getpass("Enter passphrase for certs: ") data = { 'passphrase': base64.b64encode(passphrase.encode()).decode("ascii") } with open(os.path.expanduser(os.path.join(cert_dir, 'usercert.pem')), 'rb') as usercert_file: data['usercert.pem'] = base64.b64encode( usercert_file.read()).decode("ascii") with open(os.path.expanduser(os.path.join(cert_dir, 'userkey.pem')), 'rb') as userkey_file: data['userkey.pem'] = base64.b64encode( userkey_file.read()).decode("ascii") secret = client.V1Secret(data=data, kind='Secret', type='Opaque', metadata=client.V1ObjectMeta(name=secret_name)) client.CoreV1Api().create_namespaced_secret(namespace=namespace, body=secret) print(f"Successfully created {secret_name}.")
def _create_kubernetes_secret_objects(self, key, value): key = key.lower() api_instance = self._get_kubernetes_api_instance() secret = client.V1Secret() encoded_secret = base64.b64encode(bytes(value)) secret.metadata = client.V1ObjectMeta(name=key) secretTypeEnvKey = key.upper() + "_SECRET_TYPE" secret.type = os.getenv(secretTypeEnvKey, 'Opaque') secretDataKey = key.upper() + "_SECRETS_DATA_KEY" secret_data_key = os.getenv(secretDataKey, 'secret') secret.data = {secret_data_key: encoded_secret} secrets_list = self._get_kubernetes_secrets_list() _logger.info('Creating or updating Kubernetes Secret object: %s', key) try: if key in secrets_list: api_instance.patch_namespaced_secret( name=key, namespace=self._secrets_namespace, body=secret) else: api_instance.create_namespaced_secret( namespace=self._secrets_namespace, body=secret) except: _logger.exception("Failed to create or update Kubernetes Secret")
def create_secret(name, key, value, namespace="default"): api = kube_client.CoreV1Api() return api.create_namespaced_secret( body=kube_client.V1Secret( metadata=kube_client.V1ObjectMeta(name=name), string_data={key: value}), namespace=namespace)
def create_secret(secret_data_passed, secret_name): """ Create secret secet_name Args: param1: secret_data_passed - data for secret body param2: secret_name - name of secret to be created Returns: None Raises: Raises an exception on kubernetes client api failure and asserts """ secret_api_instance = client.CoreV1Api() secret_data = copy.deepcopy(secret_data_passed) secret_data["username"] = base64encoder(secret_data["username"]) secret_data["password"] = base64encoder(secret_data["password"]) secret_metadata = client.V1ObjectMeta( name=secret_name, labels={"product": "ibm-spectrum-scale-csi"}) secret_body = client.V1Secret(api_version="v1", kind="Secret", metadata=secret_metadata, data=secret_data) try: LOGGER.info(f'Creating secret {secret_name}') secret_api_response = secret_api_instance.create_namespaced_secret( namespace=namespace_value, body=secret_body, pretty=True) LOGGER.debug(str(secret_api_response)) except ApiException as e: LOGGER.error( f"Exception when calling CoreV1Api->create_namespaced_secret: {e}") assert False
def create_secret(name, data): core_v1 = client.CoreV1Api(client.api_client.ApiClient()) ignore_404( lambda: core_v1.delete_namespaced_secret(name, current_namespace())) if not data: return context().logger.info('Creating secret %s for account %s' % (name, context().account_id)) encoded_data = {} for k, v in data.items(): encoded_data[k] = encode(v) print("show me encoded data") print(encoded_data) metadata = {'name': name, 'namespace': current_namespace()} print("come here for create_secret ") # {'name': 'TNT_HMIYKXUFCW56WCEH2H9D38-cp4s-car-tan1-secrets', 'namespace': 'staging'} print(metadata) body = client.V1Secret(api_version='v1', data=encoded_data, kind='Secret', metadata=metadata, type='Opaque') handle_409( lambda: core_v1.create_namespaced_secret(current_namespace(), body))
def create(self): if IS_CE: data = { "name": base64.b64encode(self.secret_name.encode('utf-8')).decode("utf-8"), "metaurl": base64.b64encode(self.meta_url.encode('utf-8')).decode("utf-8"), "access-key": base64.b64encode(self.access_key.encode('utf-8')).decode("utf-8"), "secret-key": base64.b64encode(self.secret_key.encode('utf-8')).decode("utf-8"), "storage": base64.b64encode(self.storage_name.encode('utf-8')).decode("utf-8"), "bucket": base64.b64encode(self.bucket.encode('utf-8')).decode("utf-8"), } else: data = { "name": base64.b64encode(self.secret_name.encode('utf-8')).decode("utf-8"), "token": base64.b64encode(self.token.encode('utf-8')).decode("utf-8"), "accesskey": base64.b64encode(self.access_key.encode('utf-8')).decode("utf-8"), "secretkey": base64.b64encode(self.secret_key.encode('utf-8')).decode("utf-8"), "storage": base64.b64encode(self.storage_name.encode('utf-8')).decode("utf-8"), "bucket": base64.b64encode(self.bucket.encode('utf-8')).decode("utf-8"), } sec = client.V1Secret( api_version="v1", kind="Secret", metadata=client.V1ObjectMeta(name=self.secret_name), data=data ) client.CoreV1Api().create_namespaced_secret(namespace=self.namespace, body=sec) SECRETs.append(self)
def _create_namespaced_secret(self) -> None: from kubernetes import client docker_creds = Secret("DOCKER_REGISTRY_CREDENTIALS").get() assert isinstance(docker_creds, dict) v1 = client.CoreV1Api() cred_payload = { "auths": { docker_creds["docker-server"]: { "Username": docker_creds["docker-username"], "Password": docker_creds["docker-password"], "Email": docker_creds["docker-email"], } } } data = { ".dockerconfigjson": base64.b64encode(json.dumps(cred_payload).encode()).decode() } namespace = prefect.context.get("namespace", "unknown") name = namespace + "-docker" secret = client.V1Secret( api_version="v1", data=data, kind="Secret", metadata=dict(name=name, namespace=namespace), type="kubernetes.io/dockerconfigjson", ) v1.create_namespaced_secret(namespace, body=secret)
def install_aws_secret(api_client, namespace, secret_name, aws_access_key_id, aws_secret_access_key): """Install AWS secret on the cluster. Return: secret: Secret for AWS credentials """ logging.info("Install AWS secret %s", secret_name) corev1_api = k8s_client.CoreV1Api(api_client) try: secret = k8s_client.V1Secret() secret.metadata = k8s_client.V1ObjectMeta(name=secret_name) secret.type = "Opaque" secret.data = { "AWS_ACCESS_KEY_ID": aws_access_key_id, "AWS_SECRET_ACCESS_KEY": aws_secret_access_key } corev1_api.create_namespaced_secret(namespace, secret) except rest.ApiException as e: # Status appears to be a string. if e.status == 409: logging.info("Github token has already been installed") else: raise
def create_secret(secret_name='jupyter-awscreds', access_key=None, secret_key=None, token=None, namespace=None): # KFP k8s helper applies incluster config setup if needed api = kube_client.CoreV1Api(K8sHelper()._api_client) namespace = namespace or current_namespace() new_data = { 'access_key': _encode_b64(access_key), 'secret_key': _encode_b64(secret_key), } if token: new_data['token'] = _encode_b64(token) try: secret = api.read_namespaced_secret(secret_name, namespace) secret.data.update(new_data) api.replace_namespaced_secret(secret_name, namespace, secret) except ApiException: secret = kube_client.V1Secret( metadata=kube_client.V1ObjectMeta(name=secret_name), data=new_data, type='Opaque') api.create_namespaced_secret(namespace=namespace, body=secret)
def add_ecr_config(kube_manager, pod_spec, namespace): if not kube_manager.secret_exists('ecr-config', namespace): secret = client.V1Secret( metadata = client.V1ObjectMeta(name='ecr-config'), string_data={ 'config.json': '{"credsStore": "ecr-login"}' }) kube_manager.create_secret(namespace, secret) volume_mount=client.V1VolumeMount( name='ecr-config', mount_path='/kaniko/.docker/', read_only=True) if pod_spec.containers[0].volume_mounts: pod_spec.containers[0].volume_mounts.append(volume_mount) else: pod_spec.containers[0].volume_mounts = [volume_mount] volume=client.V1Volume( name='ecr-config', secret=client.V1SecretVolumeSource(secret_name='ecr-config')) if pod_spec.volumes: pod_spec.volumes.append(volume) else: pod_spec.volumes = [volume]
def create_or_update_secret(self, appname, secrets, replace=True): """ create or update secret for specified app :param appname: :param secrets: new secret data dict :param replace: replace the existing secret data or just merge new data to the existing secret data :param namespace: :return: """ base64_secrets = {} for k, v in secrets.items(): b = v if isinstance(b, str): b = v.encode("utf8") if not isinstance(b, bytes): raise ValueError("secret value should be string or dict") base64_secrets[k] = base64.b64encode(b).decode('utf8') try: sec = self.core_api.read_namespaced_secret(name=appname, namespace=self.namespace) if replace: sec.data = base64_secrets else: sec.data.update(base64_secrets) self.core_api.replace_namespaced_secret(name=appname, namespace=self.namespace, body=sec) except ApiException as e: if e.status == 404: sec = client.V1Secret() sec.metadata = client.V1ObjectMeta(name=appname) sec.type = "Opaque" sec.data = base64_secrets self.core_api.create_namespaced_secret(namespace=self.namespace, body=sec) else: raise e
def main(): argument_spec = dict(fields=dict(required=True, type='dict')) ansible_module = AnsibleModule(argument_spec=argument_spec) try: fields_json = json.dumps(ansible_module.params['fields']) encoded_fields = base64.b64encode(fields_json) except Exception as error: ansible_module.fail_json( msg="Error attempting to encode binding: {}".format(error)) try: name = os.environ[ENV_NAME] namespace = os.environ[ENV_NAMESPACE] except Exception as error: ansible_module.fail_json( msg="Error attempting to get name/namespace from environment: {}". format(error)) try: api.create_namespaced_secret( namespace=namespace, body=client.V1Secret(metadata=client.V1ObjectMeta(name=name), data={"fields": encoded_fields})) except Exception as error: ansible_module.fail_json( msg="Error attempting to create binding secret: {}".format(error)) ansible_module.exit_json(changed=True, encoded_fields=encoded_fields)
def createSecretPython(payload): config.load_kube_config() client.configuration.assert_hostname = False api_instance = client.CoreV1Api() sec = client.V1Secret() UUID = str(uuid.uuid4()) sec.metadata = client.V1ObjectMeta( name="mysecret" + str(UUID), labels={ "heritage": "brigade", "project": "brigade-kafka", #****** "build": "mysecret" + str(UUID), "component": "build" }) sec.type = "brigade.sh/build" encoded_payload = base64.b64encode(json.dumps(payload).encode()) decoded_payload = encoded_payload.decode('utf-8') json_data = {"payload": decoded_payload} sec.data = json_data sec.string_data = { "event_type": "exec", "build_id": "mysecret" + str(UUID), "commit_ref": "master", #******* "project": "brigade-kafka", #****** "project_id": "brigade-kafka", #****** "build_name": "mysecret" + str(UUID), "event_provider": "brigade_cli" } api_instance.create_namespaced_secret(namespace="default", body=sec)
def deploy_secret(secret_name, secret_data, namespace="default"): """Creates or updates a secret with the values specified in the secret_data param. This param must be a dict where the key is the entry name and the value is the secret value (e.g. `{"username": "******"}'). If the secret already exists then it will be patched instead. Returns the secret object that has been created/updated. """ secret_metadata = {"name": secret_name, "namespace": "default"} api_version = "v1" kind = "Secret" config.load_kube_config() k8 = client.CoreV1Api() body = client.V1Secret(api_version=api_version, kind=kind, metadata=secret_metadata, string_data=secret_data) # Try the post request. If it fails, handle the 409 response by trying a patch request instead try: resp = k8.create_namespaced_secret(namespace, body) except ApiException as e: if e.status == 409: print("Secret already exists! Updating...") resp = k8.patch_namespaced_secret(name=secret_name, namespace=namespace, body=body) return resp
def _create_secret(secret: Dict[Text, Text]): api_instance = client.CoreV1Api() try: api_instance.read_namespaced_secret( name=secret["secret_name"], namespace="default", ) except rest.ApiException as e: if e.status != 404: raise RuntimeError(f"Unknown error: {e}.") api_instance.create_namespaced_secret( body=client.V1Secret( api_version="v1", kind="Secret", metadata={ "name": secret["secret_name"], "type": "Opaque" }, data=gamla.valmap( lambda s: base64.b64encode(os.getenv(s, s).encode()). decode(), secret["data"], ), ), namespace="default", ) logging.info(f"Secret '{secret['secret_name']}' created.")
def patch_secret(name, data_dict, namespace): confirm_namespace(namespace) config.load_kube_config() api_instance = client.CoreV1Api() meta_data = client.V1ObjectMeta() meta_data.namespace = namespace meta_data.name = name body = client.V1Secret(metadata = meta_data, data = data_dict) try: api_response = api_instance.patch_namespaced_secret(name, namespace, body) logger.info("Secret named {0} is updated.".format(name)) except ApiException as e: logger.info(e) if e.status == 404: try: logger.info("Couldn't find secret named {0}. Create a new secret".format(name)) api_response = api_instance.create_namespaced_secret(namespace, body) logger.info("Secret named {0} is created".format(name)) except ApiException as ie: logger.error("Exception when calling CoreV1Api->create_namespaced_secret: {0}".format(str(ie))) sys.exit(1) else: logger.error("Exception when calling CoreV1Api->patch_namespaced_secret: {0}".format(str(e))) sys.exit(1)
def _create_storage_account_secret(cluster_details: dict) -> None: """Setup storage_account_secret for the MARO Cluster. The secret is used in Azure File Service. Returns: None. """ # Build params storage_account_name = f"{cluster_details['id']}st" # Get storage account key storage_account_keys = AzureController.get_storage_account_keys( resource_group=cluster_details["cloud"]["resource_group"], storage_account_name=storage_account_name) storage_key = storage_account_keys[0]["value"] # Create k8s secret client.CoreV1Api().create_namespaced_secret(body=client.V1Secret( metadata=client.V1ObjectMeta(name="azure-storage-account-secret"), data={ "azurestorageaccountname": base64.b64encode(storage_account_name.encode()).decode(), "azurestorageaccountkey": base64.b64encode(bytes(storage_key.encode())).decode() }), namespace="default")
def add_ecr_config(kube_manager, pod_spec, namespace): """add secret :param kube_manager: kube manager for handles communication with Kubernetes' client :param pod_spec: pod spec like volumes and security context :param namespace: The custom resource """ if not kube_manager.secret_exists('ecr-config', namespace): secret = client.V1Secret(metadata=client.V1ObjectMeta(name='ecr-config'), string_data={ 'config.json': '{"credsStore": "ecr-login"}' }) kube_manager.create_secret(namespace, secret) volume_mount = client.V1VolumeMount(name='ecr-config', mount_path='/kaniko/.docker/', read_only=True) if pod_spec.containers[0].volume_mounts: pod_spec.containers[0].volume_mounts.append(volume_mount) else: pod_spec.containers[0].volume_mounts = [volume_mount] volume = client.V1Volume(name='ecr-config', secret=client.V1SecretVolumeSource(secret_name='ecr-config')) if pod_spec.volumes: pod_spec.volumes.append(volume) else: pod_spec.volumes = [volume]
def create_secret_for_app(app): ''' 将client secret以k8s secret形式存储 deprecated TODO: - 目前job缺少对完成状况的判断 ''' k8s_config.load_kube_config() client = k8s_client.CoreV1Api() oauth_app = OAuthAPP.objects.filter(app=app).first() ark_app_uid = app.uid # "arker-{arkerPK}" if oauth_app: secret = k8s_client.V1Secret( api_version="v1", data={ "OAUTH_CLIENT_ID": (base64.b64encode( str.encode(oauth_app.client_id))).decode("utf-8"), "OAUTH_CLIENT_SECRET": (base64.b64encode( str.encode(oauth_app.client_secret))).decode("utf-8"), }, kind="Secret", metadata={ "name": ark_app_uid, "namespace": ark_app_uid, }, ) thread = client.create_namespaced_secret(namespace=ark_app_uid, body=secret, async_req=True) res = thread.get() print(res)
def create_or_patch_secret(self, file_list, secret_name): # api_version = 'v1' # kind = 'Secret' # type='kubernetes.io/tls' rsp = None tmp_log = core_utils.make_logger(base_logger, method_name='create_or_patch_secret') metadata = {'name': secret_name, 'namespace': self.namespace} data = {} for file_name in file_list: filename = os.path.basename(file_name) with open(file_name, 'rb') as f: content = f.read() data[filename] = base64.b64encode(content).decode() body = client.V1Secret(data=data, metadata=metadata) try: try: rsp = self.corev1.patch_namespaced_secret( name=secret_name, body=body, namespace=self.namespace) tmp_log.debug('Patched secret') except ApiException as e: tmp_log.debug( 'Exception when patching secret: {0} . Try to create secret instead...' .format(e)) rsp = self.corev1.create_namespaced_secret( body=body, namespace=self.namespace) tmp_log.debug('Created secret') except Exception as e: tmp_log.error( 'Exception when patching or creating secret: {0}.'.format(e)) return rsp
def update_secret(namespace, secret_name, labels, key, value): """ Update a secret object's key with the value """ try: config.load_kube_config() except: config.load_incluster_config() v1 = client.CoreV1Api() try: secret = v1.read_namespaced_secret(namespace=namespace, name=secret_name) except client.rest.ApiException as e: if e.status == 404: secret = client.V1Secret( metadata=client.V1ObjectMeta(name=secret_name, labels=labels), data={} ) resp = v1.create_namespaced_secret(namespace=namespace, body=secret) logging.info(f"Created secret {secret_name} since it does not exist") else: raise # Value should be base64'd string new_value = base64.standard_b64encode(value).decode() if secret.data is None: secret.data = {} if new_value != secret.data.get(key): secret.data[key] = base64.standard_b64encode(value).decode() v1.patch_namespaced_secret(namespace=namespace, name=secret_name, body=secret) logging.info(f"Updated secret {secret_name} with new value for key {key}")
def on_field_data(old, new, body, name, logger=None, **_): logger.debug(f'Data changed: {old} -> {new}') if old is not None: syncedns = body['status']['create_fn']['syncedns'] v1 = client.CoreV1Api() secret_type = 'Opaque' if 'type' in body: secret_type = body['type'] for ns in syncedns: logger.info(f'Re Syncing secret {name} in ns {ns}') metadata = {'name': name, 'namespace': ns} api_version = 'v1' kind = 'Secret' data = new body = client.V1Secret(api_version, data, kind, metadata, type=secret_type) # response = v1.patch_namespaced_secret(name,ns,body) response = v1.replace_namespaced_secret(name, ns, body) logger.debug(response) else: logger.debug('This is a new object')
def create_image_pull_secret(self, namespace="default"): secret_metadata = client.V1ObjectMeta(name="image-pull-secret") auth_string = str.encode(f"{self.registry['user']}:{self.registry['pwd']}") secret_data = { "auths": { self.registry["url"]: { "auth": base64.b64encode(auth_string).decode("utf-8") } } } secret_data = json.dumps(secret_data).encode() secret_body = client.V1Secret( api_version="v1", kind="Secret", metadata=secret_metadata, type="kubernetes.io/dockerconfigjson", data={".dockerconfigjson": base64.b64encode(secret_data).decode("utf-8")}, ) core_v1 = client.CoreV1Api() try: core_v1.create_namespaced_secret(namespace, secret_body) except client.rest.ApiException as exc: if exc.status == 409 and exc.reason == "Conflict": warnings.warn( "Kubernetes Cluster not empty. Image pull secret already exists." ) else: raise exc
def store_project_secrets(self, project, secrets, namespace=""): secret_name = self.get_project_secret_name(project) namespace = self.resolve_namespace(namespace) try: k8s_secret = self.v1api.read_namespaced_secret( secret_name, namespace) except ApiException as exc: # If secret doesn't exist, we'll simply create it if exc.status != 404: logger.error(f"failed to retrieve k8s secret: {exc}") raise exc k8s_secret = client.V1Secret(type="Opaque") k8s_secret.metadata = client.V1ObjectMeta(name=secret_name, namespace=namespace) k8s_secret.string_data = secrets self.v1api.create_namespaced_secret(namespace, k8s_secret) return secret_data = k8s_secret.data.copy() for key, value in secrets.items(): secret_data[key] = base64.b64encode(value.encode()).decode("utf-8") k8s_secret.data = secret_data self.v1api.replace_namespaced_secret(secret_name, namespace, k8s_secret)
def create_secret(self, namespace='default', name=None, metadata=None, data=None): ''' Returns V1Secret object Ex : metadata = {'name': 'xyz', 'namespace' : 'abc' } "secret": { "data": { 'tls.crt' : <>, 'tls.key' : <>, }, ''' kind = 'Secret' obj_type = 'kubernetes.io/tls' if metadata is None: metadata = {} if data is None: data = {} metadata_obj = self._get_metadata(metadata) if name: metadata_obj.name = name body = client.V1Secret(metadata=metadata_obj, data=data, kind=kind, type=obj_type) self.logger.info('Creating secret %s' % (metadata_obj.name)) resp = self.v1_h.create_namespaced_secret(namespace, body) return resp
def create_secret_as_env(self, secret_name, namespace): config.load_kube_config() v1 = client.CoreV1Api() tmp_content = open("/tmp/{}.yaml".format(secret_name), "r") tmp_yaml = yaml.safe_load(tmp_content) tmp_arr = {} for item, doc in tmp_yaml.items(): tmp_encode = base64.b64encode(str.encode(doc)) tmp_arr[item] = tmp_encode.decode() secret = client.V1Secret( api_version="v1", data=tmp_arr, kind="Secret", metadata=dict(name=secret_name, namespace=namespace), type="Opaque", ) response = v1.create_namespaced_secret(namespace, body=secret) tmp_content.close() tmp_arr = {} return response