LoginSignup
2
2

More than 3 years have passed since last update.

[terraform] 用意されてないresourceはnull_resourceで対応する

Last updated at Posted at 2020-10-14

簡易的な例

resource "null_resource" "hogehoge" {
  triggers = {
    fugafuga = "fugafuga" // ここが変わると直下に記載してあるlocal-execが実行される(whenが指定されてない方)
  }
  provisioner "local-exec" {
    interpreter = ["ruby", "-e"]
    command     = "puts 'hogefuga'"
  }
  provisioner "local-exec" {
    interpreter = ["ruby", "-e"]
    command     = "puts 'fugapiyo'"
    when        = destroy // こっちは削除時に実行される(whenで指定してあるため)
  }
}

具体例

resource "google_bigquery_dataset" "shared_udf" {
  dataset_id = "shared_udf"
  location   = local.japan_tokyo_region
}

locals {
  japan_tokyo_region = "asia-northeast1"
  udfs = {
    example : <<EOF
CREATE OR REPLACE FUNCTION ${google_bigquery_dataset.shared_udf.dataset_id}.example(x INT64)
RETURNS INT64
  LANGUAGE js AS """
  return x*2;
""";
EOF
  }

}

resource "null_resource" "udfs" {
  for_each = local.udfs
  triggers = {
    udf = each.value
    project_id = var.project_id
    location = local.japan_tokyo_region
    udf_dataset_id = google_bigquery_dataset.shared_udf.dataset_id // destroy時のwarningへの暫定対応 望ましくないがとりあえず https://github.com/hashicorp/terraform/issues/23679
  }
  provisioner "local-exec" {
    interpreter = ["bq", "query", "--use_legacy_sql=false", "--project_id=${self.triggers.project_id}", "--location=${self.triggers.location}"]
    command     = each.value
  }
  provisioner "local-exec" {
    interpreter = ["bq", "query", "--use_legacy_sql=false", "--project_id=${self.triggers.project_id}", "--location=${self.triggers.location}"]
    command     = "DROP FUNCTION IF EXISTS ${self.triggers.udf_dataset_id}.${each.key}"
    when        = destroy
  }
}

参考

2
2
1

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
2