2017-07-26 51 views
8

這裏是我的s3_policy.json如何使用Terraform從GitHub Enterprise下載文件?

{ 
    "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地址。

回答

2

您可以使用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列表,而不是毫無意義的此數據源中硬編碼。