从文件中读取terraform变量

Dan*_*ats 5 amazon-web-services terraform

在terraform中,长按键可以指定如下:

resource "aws_iam_role_policy" "foo-policy" {
    role = "${aws_iam_role.foo-role.name}"
    name = "foo-policy"

    policy = <<EOF
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents",
                "logs:DescribeLogStreams"
            ],
            "Resource": [
                "arn:aws:logs:*:*:*"
            ]
        }
    ]
}
EOF
}
Run Code Online (Sandbox Code Playgroud)

这是IAM策略文档的常见模式.此处记录该方法,并且是在terraform上AWS IAM角色策略页面中给出的示例.有没有办法从外部文件中读取文档?

这有很多好处:

  • 您可以使用工具生成策略
  • 您可以使用linting工具来验证策略JSON.此外,编辑器语法突出显示将起作用,显示JSON错误,如尾随逗号.
  • 您可以使用更高级的工具来验证策略文档语法

Ant*_*ace 11

您可以使用terraform的template_file数据源.只需将策略写入您的terraform脚本可以访问的路径中的文件,然后创建引用它的template_file数据源.例如:

data "template_file" "policy" {
  template = "${file("somepath/my-policy.json")}"
}
Run Code Online (Sandbox Code Playgroud)

然后,在foo-policy中,你会像这样呈现它:

policy = "${data.template_file.policy.rendered}"
Run Code Online (Sandbox Code Playgroud)

template_file的另一个好处是可以在引用的文件中插入变量.例如,您可以在策略中包含${IAMUser}或使用变量${AWSAccountNumber},并通过template_file vars选项传入,这将允许您重用策略文件.

进一步阅读

  • 此外,如果单独的文件是文字 IAM 策略文档(无 Terraform 模板插值),您可以直接在“aws_iam_role_policy”的“policy”参数中使用“file”函数。 (2认同)