Terraform:将 JSON 文件作为环境变量值传递给 docker 容器内的系统单元文件

Terraform: Passing JSON file as environment variable value with a systemd unit file inside docker container

我正在尝试通过 terraform 在 systemd 单元文件的环境变量中传递 json。我正在使用名为 CT 的外部提供程序从 YAML 配置生成点火。

CT 配置:

data "ct_config" "ignition" {
  # Reference: https://github.com/poseidon/terraform-provider-ct/
  content      = data.template_file.bastion_user_data.rendered
  strict       = true
  pretty_print = false
}

错误:

Error: error converting to Ignition: error at line 61, column 17
invalid unit content: unexpected newline encountered while parsing option name

  on ../../modules/example/launch-template.tf line 91, in data "ct_config" "ignition":
  91: data "ct_config" "ignition" {

单元文件内容:

- name: cw-agent.service
  enabled: true
  contents: |
    [Unit]
    Description=Cloudwatch Agent Service
    Documentation=https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Agent-Configuration-File-Details.html
    Requires=docker.socket
    After=docker.socket
    [Service]
    TimeoutStartSec=0
    Restart=always
    RestartSec=10s
    Environment=CONFIG=${cw-agent-config}
    ExecStartPre=-/usr/bin/docker kill cloudwatch-agent
    ExecStartPre=-/usr/bin/docker rm cloudwatch-agent
    ExecStartPre=/usr/bin/docker pull amazon/cloudwatch-agent
    ExecStart=/usr/bin/docker run --name cloudwatch-agent \
                              --net host \
                              --env CW_CONFIG_CONTENT=$CONFIG \
                              amazon/cloudwatch-agent
    ExecStop=/usr/bin/docker stop cloudwatch-agent
    [Install]
    WantedBy=multi-user.target

渲染:

data "template_file" "cw_agent_config" {
  template = file("${path.module}/../cw-agent-config.json")
}

cw-agent-config = indent(10, data.template_file.cw_agent_config.rendered)

文件内容:

{
    "agent": {
        "metrics_collection_interval": 60,
"run_as_user": "cwagent"
    },
    "metrics": {
        "append_dimensions": {
            "AutoScalingGroupName": "$${aws:AutoScalingGroupName}",
            "ImageId": "$${aws:ImageId}",
            "InstanceId": "$${aws:InstanceId}",
            "InstanceType": "$${aws:InstanceType}"
        },
        "metrics_collected": {
            "disk": {
                "drop_device" : true,
                "measurement": [
                    "used_percent"
                ],
                "metrics_collection_interval": 120,
                "resources": [
                    "/"
                ]
            },
            "mem": {
                "measurement": [
                    "mem_used_percent"
                ],
                "metrics_collection_interval": 120
            }
        }
    }
}

我需要这个 json 文件作为 docker 容器中名为 CW_CONFIG_CONTENT 的环境变量的值。

这已通过使用 Terraform jsonencode 函数解决。

    cw-agent-config = jsonencode(data.template_file.cw_agent_config.rendered)