简体   繁体   English

k8s/python:如何使用 Kubernetes Python 客户端读取机密?

[英]k8s/python: How do I read a secret using the Kubernetes Python client?

I want to do the opposite of this question:我想做与这个问题相反的事情:

How to create secrets using Kubernetes Python client? 如何使用 Kubernetes Python 客户端创建秘密?

ie: IE:

How do I read an existing secret from a kubernetes cluster via the kubernetes-python API?如何通过 kubernetes-python API 从 kubernetes 集群读取现有机密?

The use case is: I want to authenticate to mongodb (running in my cluster) from a jupyter notebook (also running in my cluster) without, for obvious reasons, saving the mongodb auth password inside the jupyter notebook.用例是:我想从 jupyter 笔记本(也在我的集群中运行)向 mongodb(在我的集群中运行)进行身份验证,出于明显的原因,没有将 mongodb 身份验证密码保存在 jupyter 笔记本中。

Thanks!谢谢!

  1. Install Kubernetes client for python为 python 安装Kubernetes 客户端
  2. Now you can pull the secret.现在你可以揭开秘密了。 For example secret name - mysql-pass , namespace - default例如秘密名称 - mysql-pass ,命名空间 - default
from kubernetes import client, config
config.load_kube_config()
v1 = client.CoreV1Api()
secret = v1.read_namespaced_secret("mysql-pass", "default")
print(secret)
  1. If you need to extract decoded password from the secret如果您需要从秘密中提取解码后的密码
from kubernetes import client, config
import base64
import sys    
config.load_kube_config()
v1 = client.CoreV1Api()
sec = str(v1.read_namespaced_secret("mysql-pass", "default").data)
pas = base64.b64decode(sec.strip().split()[1].translate(None, '}\''))
print(pas)

Hope this will help.希望这会有所帮助。

If you use kubernetes client api it will give you response as a dict datatype and you might not need to do spiting etc, You can say something like this,如果您使用 kubernetes 客户端 api,它将为您提供 dict 数据类型的响应,您可能不需要进行吐痰等,您可以这样说,

from kubernetes import client, config
import base64
config.load_kube_config()
v1 = client.CoreV1Api()
sec = v1.read_namespaced_secret("default-token-rsbq7", "default").data
cert = base64.b64decode(sec["ca.crt"])
print(cert)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM