首页 > 解决方案 > GCP VM 部署:如何在创建 VM 时动态更新 yaml 配置属性

问题描述

我们有一个 nodejs 应用程序,它使用配置文件 (.yaml) 和模板在 GCP 上创建 VM。现在我想在创建 VM 时根据来自 UI 的用户输入更新 yaml/模板中的一些属性。我们如何动态更新配置属性?在此先感谢您的任何建议。

标签: google-apigoogle-cloud-platformgcloudgoogle-api-nodejs-clientgoogle-deployment-manager

解决方案


似乎您有两个选择:

1)神社模板方式

您可以定义一个 jinja 模板,而不是配置文件:资源:

# my-template.jinja
resources:
- name: my-resource
  type: some-type
  properties:
    prop1: {{ properties['foo'] }}
    prop2: {{ properties['bar'] }}

然后,您可以像这样调用它,变量 foo 和 bar 将映射到提供的属性:

gcloud deployment-manager deployments create <my-deployment> \
  --template my-template.jinja \
  --properties foo:user-custom-value,bar:another-value

2) 老式的模板方式

我们正在替换文本本身中的自定义值,而不是使用渲染引擎(就像 jinja2 一样)

# my-template.yaml
resources:
- name: my-resource
  type: some-type
  properties:
    prop1: REPLACE-PROP-1
    prop2: REPLACE-PROP-2

sed尽可能替换文本,如果您正在运行 shell 脚本,或者从 node/javascript 本身,则可以使用

const replaces = [
  {name: 'REPLACE-PROP-1', value: 'user-custom-value'},
  {name: 'REPLACE-PROP-2', value: 'another-custom-value'},
];
const templateYaml = fs.readFileSync('my-template.yaml','utf-8');
const customYaml = replaces
  .map(r => templateYaml.replace(RegExp(r.name,'g'), r.value);

或者使用 sed

sed -ie 's/REPLACE-PROP-1/user-custom-value/g' my-template.yaml
sed -ie 's/REPLACE-PROP-2/another-cst-value/g' my-template.yaml

最后部署配置

gcloud deployment-manager deployments create <my-deployment> \
  --config my-template.yaml

推荐阅读