如何将某些文本文件(python)中的值传递到YAML文件

时间:2019-12-17 09:25:56

标签: python yaml

我需要将python文件中的值传递给yaml文件。

这是我的constants.py

NAMESPACE = "bitesize-troubleshooter"
DEPLOYMENT_NAME = "deployment-test"

这是我的yaml文件

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: deployment-test-ingress
  namespace: //here I want to pass the NAMESPACE value
  annotations:
    ingress.kubernetes.io/rewrite-target: / 
    nginx.org/ssl-services: deployment-test-clusterip
spec:
  rules:
  - host: # empty in this case, but you could fill in the host here (we use the minikube IP instead)
    http:
      paths:
      - path: /
        backend:
          serviceName: deployment-test-clusterip
          servicePort: 80

yaml中表示namespace的位置应在python文件中分配给NAMESPACE常量。

有没有办法在Yaml中做到这一点?

2 个答案:

答案 0 :(得分:0)

您将不得不将Yaml重写为模板。模板替换有很多方法。例如,与此:

kind: Ingress
metadata:
  name: deployment-test-ingress
  namespace: ${NAMESPACE} 
...

Also, I see you're working with Kubernetes yaml. Take a look at Helm, which adds this sort of configurability.

Python可以通过启动外部进程来调用envsubst,或者使用此Pypi Locator Strategies,或者简单地读取yaml并调用yaml_str.replace("${NAMESPACE}", namespace)

答案 1 :(得分:0)

如果尚未安装pyyaml软件包,请安装:pip install pyyaml

然后按如下所示更新yaml文件中的NAMESPACE和DEPLOYMENT_NAME参数:

import yaml

NAMESPACE, DEPLOYMENT_NAME = "bitesize-troubleshooter", "deployment-test"
yaml_file, params = "your.yaml", None

with open(yaml_file) as f:
    params = yaml.safe_load(f)

params['metadata']['namespace'] = NAMESPACE
params['metadata']['name']      = DEPLOYMENT_NAME

with open(yaml_file, 'w') as f:
    yaml.safe_dump(params, f)