1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

terraform moved blockでファクタリングする

Posted at

下記のように配列で作成したリソースはvariableを変更した際、配列を再作成してしまいます。
これをfor_eachでリファクタリングする際、手作業やterraform state mvで1つづつterraform.tfstateを更新するのですが、moved blockを使用すれば考えることを減らしてリファクタリングできます。

  • befor
route53_record.tf
data "aws_elb_hosted_zone_id" "main" {}

resource "aws_route53_record" "test_record" {
  count   = length(var.test_recors)
  zone_id = data.aws_route53_zone.selected.zone_id
  name    = element(var.test_recors, count.index)
  type    = "A"
  alias {
    name                   = var.test_elb_dns_names
    zone_id                = data.aws_elb_hosted_zone_id.main.id
    evaluate_target_health = true
  }
}
variables.tf
variable "test_recors" {
  type = list(any)

  default = [
    "test1.xxxx.jp",
    "test2.xxxx.jp",
    "test3.xxxx.jp"
  ]
}
variable "test_elb_dns_names" {
  type = list(any)

  default = [
    "awseb-AWSEB-xxxxxxx-xxxxxxx.ap-northeast-1.elb.amazonaws.com"
  ]
}
  • after
route53_record.tf
data "aws_elb_hosted_zone_id" "main" {}

moved {
  from = aws_route53_record.test_record[0]
  to   = aws_route53_record.test_newrecord["test1.xxxx.jp"]
}
moved {
  from = aws_route53_record.test_record[1]
  to   = aws_route53_record.test_newrecord["test2.xxxx.jp"]
}
moved {
  from = aws_route53_record.test_record[2]
  to   = aws_route53_record.test_newrecord["test3.xxxx.jp"]
}

resource "aws_route53_record" "test_newrecord" {
  zone_id = data.aws_route53_zone.selected.zone_id

  for_each = var.test_newrecords

  name = each.value.fqdn
  type = "A"

  alias {
    name                   = var.test_elb_dns_names
    zone_id                = data.aws_elb_hosted_zone_id.main.id
    evaluate_target_health = true
  }
}
variables.tf
variable "test_newrecords" {
  type = map(any)

  default = {
    test1 = {
      fqdn = "test1.xxxx.jp"
    }
    test2 = {
      fqdn = "test2.xxxx.jp"
    }
    test3 = {
      fqdn = "test3.xxxx.jp"
    }
  }
}

variable "test_elb_dns_names" {
  type = list(any)

  default = [
    "awseb-AWSEB-xxxxxxx-xxxxxxx.ap-northeast-1.elb.amazonaws.com"
  ]
}
  • planで変更がされていることを確認し、applyで適用する。
$ terraform plan
  # aws_route53_record.test_record[0] has moved to aws_route53_record.test_newrecord["test1.xxxx.jp"]
.
.
.
  • terraform.tfstate更新後はmoved blockは不要なので削除します。
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?