LoginSignup
2
1

More than 3 years have passed since last update.

TerraformでJSONを扱う方法

Last updated at Posted at 2019-09-27

Terraformでjsonを利用する際の方法をまとめました。
AWSはIPアドレスのレンジをjsonで公開していたりするので、Terraformでアクセス許可設定するときなど便利そうです。(例として利用します)

v0.12 から使えるようになった For Expression (jsondecodeもだけど) がとても便利で、下の例のようにregionやserviceで絞り込むことも出来るのでかなり使いやすいと思います。

AWS IP range: https://ip-ranges.amazonaws.com/ip-ranges.json

ローカルのjsonを利用

output "local_aws_ip_range" {
  value = [ for prefix in jsondecode(file("./ip-range.json"))["prefixes"] : prefix.ip_prefix if prefix.region == "ap-northeast-1" && prefix.service == "EC2" ]
}

# 出力結果
local_aws_ip_range = [
  "52.194.0.0/15",
  "54.168.0.0/16",
  "54.238.0.0/16",
  "54.250.0.0/16",
  "54.92.0.0/17",
  "18.183.0.0/16",
  "176.32.64.0/19",
  "52.196.0.0/14",
  "175.41.192.0/18",
  "54.150.0.0/16",
  "99.77.139.0/24",
  "54.199.0.0/16",
  "176.34.32.0/19",
  "54.248.0.0/15",
  "18.182.0.0/16",
  "13.112.0.0/14",
  "52.68.0.0/15",
  "52.94.248.80/28",
  "54.95.0.0/16",
  "52.95.243.0/24",
  "3.112.0.0/14",
  "18.178.0.0/16",
  "52.192.0.0/15",
  "13.230.0.0/15",
  "54.178.0.0/16",
  "18.180.0.0/15",
  "52.95.255.48/28",
  "103.4.8.0/21",
  "18.179.0.0/16",
  "46.51.224.0/19",
  "54.64.0.0/15",
  "176.34.0.0/19",
  "18.176.0.0/15",
  "15.193.1.0/24",
]

HTTPで取得したjsonを利用

data "http" "aws_ip_range" {
  url = "https://ip-ranges.amazonaws.com/ip-ranges.json"
}

output "aws_ip_range" {
  value = [ for prefix in jsondecode(data.http.aws_ip_range.body)["prefixes"] : prefix.ip_prefix if prefix.region == "ap-northeast-1" && prefix.service == "EC2" ]
}

# 出力結果
aws_ip_range = [
  "52.194.0.0/15",
  "54.168.0.0/16",
  "54.238.0.0/16",
  "54.250.0.0/16",
  "54.92.0.0/17",
  "18.183.0.0/16",
  "176.32.64.0/19",
  "52.196.0.0/14",
  "175.41.192.0/18",
  "54.150.0.0/16",
  "99.77.139.0/24",
  "54.199.0.0/16",
  "176.34.32.0/19",
  "54.248.0.0/15",
  "18.182.0.0/16",
  "13.112.0.0/14",
  "52.68.0.0/15",
  "52.94.248.80/28",
  "54.95.0.0/16",
  "52.95.243.0/24",
  "3.112.0.0/14",
  "18.178.0.0/16",
  "52.192.0.0/15",
  "13.230.0.0/15",
  "54.178.0.0/16",
  "18.180.0.0/15",
  "52.95.255.48/28",
  "103.4.8.0/21",
  "18.179.0.0/16",
  "46.51.224.0/19",
  "54.64.0.0/15",
  "176.34.0.0/19",
  "18.176.0.0/15",
  "15.193.1.0/24",
]
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1