如何使用Terraform从GitHub Enterprise下载文件?

时间:2017-07-26 05:08:56

标签: amazon-s3 terraform

这是我的s3_policy.json

{
  "Version":"2012-10-17",
  "Statement":[
    {
      "Sid":"mybucket",
      "Effect":"Allow",
      "Principal": "*",
      "Action":["s3:GetObject"],
      "Resource":[
        "arn:aws:s3:::${bucket_name}/*"
      ],
      "Condition": {
          "IpAddress": {
              "aws:SourceIp": [
              "10.xx.xxx.x",
              "172.168.xx.x",
              ........,
              .........,
              ..........,
              ...........,
              ]
          }
      }
    }
  ]
}

我有一个共同的回购,我将它用于不同的项目。这个通用仓库有一个yaml格式的CIDR IP列表。

我想把它拉进我的Terraform项目,以便我可以重新使用相同的文件而不是硬编码IP地址。

我无法找到一种自动化方法,而不是在此仓库中硬编码IP地址。

1 个答案:

答案 0 :(得分:3)

您可以将IP地址用作数据源并使用它。

您的政策文件将如下所示:

resource "aws_iam_policy" "whitelist_ips" {
  name        = "whitelist_ips"
  description = "${var.policy_description}"

  policy = <<EOF
{
  "Version":"2012-10-17",
  "Statement":[
    {
      "Sid":"mybucket",
      "Effect":"Allow",
      "Principal": "*",
      "Action":["s3:GetObject"],
      "Resource":[
        "arn:aws:s3:::${bucket_name}/*"
      ],
      "Condition": {
          "IpAddress": {
              "aws:SourceIp": ["${data.external.ip_addresses.result}"]
          }
      }
    }
  ]
}
EOF
}

您需要创建一个可以运行的external data source,它可以从某个位置获取IP地址,并以逗号分隔的字符串形式返回IP。

data "external" "ip_addresses" {
  program = ["python", "${path.module}/get_ips.py"]
}

其中get_ips.py可能如下所示:

#!/usr/bin/env python
from __future__ import print_function
import json
import re

yaml_string = """ - 1.2.3.4/32
 - 1.2.3.5/32
 - 1.3.0.0/16
"""

result = []
lines = yaml_string.split("\n")

for line in lines:
    # Remove empty lines
    if line != "":
        result.append(re.sub('\s*-\s*', '', line))

print(json.dumps(','.join(result)))

但显然你需要从Github获取YAML列表,而不是在这个数据源中无意义地硬编码。

相关问题