Terraform:容器存储部分中的 YAML 文件呈现问题 linux flatcar OS 配置

Terraform: YAML file rendering issue in storage section of container linux config of flatcar OS

我正在尝试通过模板渲染生成文件以传递给ec2 实例的用户数据。我正在使用第三方 terraform 提供程序从 YAML 生成点火文件。

data "ct_config" "worker" {
  content      = data.template_file.file.rendered
  strict       = true
  pretty_print = true
}
data "template_file" "file" {
  ...
  ...
  template = file("${path.module}/example.yml")
  vars = {
    script = file("${path.module}/script.sh")
  }
}

example.yml

storage:
  files:
    - path: "/opt/bin/script"
      mode: 0755
      contents: 
        inline: |
          ${script}

错误:

Error: Error unmarshaling yaml: yaml: line 187: could not find expected ':'

  on ../../modules/launch_template/launch_template.tf line 22, in data "ct_config" "worker":
  22: data "ct_config" "worker" {

如果我将 ${script} 更改为样本数据,那么它就可以工作了。另外,无论我在 script.sh 中输入什么,我都会收到同样的错误。

你想要这个结果(伪代码):

storage:
  files:
    - path: "/opt/bin/script"
      mode: 0755
      contents: 
        inline: |
          {{content of script file}}

在您当前的实现中,从 script.sh 加载的第一行之后的所有行都不会缩进,也不会被 YAML 解码器按需要解释(整个 script.sh 内容)。

使用 indent you can correct the indentation and using the newer templatefile 函数,您可以对模板使用稍微简洁的设置:

data "ct_config" "worker" {
  content      = local.ct_config_content
  strict       = true
  pretty_print = true
}

locals {
  ct_config_content = templatefile("${path.module}/example.yml", {
    script = indent(10, file("${path.module}/script.sh"))
  })
}

为清楚起见,这里是 example.yml 模板文件(来自原始问题),用于上面的代码:

storage:
  files:
    - path: "/opt/bin/script"
      mode: 0755
      contents: 
        inline: |
          ${script}

我在 ct_config 中遇到了这个问题,今天解决了。您需要 base64encode 您的脚本以确保其编写正确 没有 换行符 - 否则,脚本中的换行符将进入 CT,它会尝试构建 Ignition 文件,这不能有换行符,导致你 运行 原来的错误。

编码后,您只需告诉 CT !!binary 文件以确保 Ignition 在部署时正确地对其进行 base64 解码:

data "template_file" "file" {
  ...
  ...
  template = file("${path.module}/example.yml")
  vars = {
    script = base64encode(file("${path.module}/script.sh"))
  }
}
storage:
  files:
    - path: "/opt/bin/script"
      mode: 0755
      contents: 
        inline: !!binary |
          ${script}