LoginSignup
19
6

More than 3 years have passed since last update.

terraformで入れ子の値を無視(ignore_change)する方法

Posted at

ignore_changes 基本的な使い方

terraformで、特定の項目をterraformで管理したくない場合、lifecycleignore_changesが使えます。

The lifecycle Meta-Argument - Configuration Language - Terraform by HashiCorp

ドキュメントからの引用ですが、これが基本的な設定の仕方になります。

resource "aws_instance" "example" {
  # ...

  lifecycle {
    ignore_changes = [
      # Ignore changes to tags, e.g. because a management agent
      # updates these based on some ruleset managed elsewhere.
      tags,
    ]
  }
}

入れ子の場合

では、入れ子の(nested)な値の場合はどうすれば良いのでしょうか?

例えば、


resource "aws_eip" "test" {
  tags = {
    test = "testValue"
  }
}

tags.test をignoreしたい場合です。

これはドキュメントに記載がありまして、

The arguments are the relative address of the attributes in the resource. Map and list elements can be referenced using index notation, like tags["Name"] and list[0] respectively.


resource "aws_eip" "test" {
  tags = {
    test = "testValue"
  }

  lifecycle {
    ignore_changes = [
      tags["test"],
    ]
  }
}

で、ignoreされるようになります。

入れ子の場合の落とし穴

で、ここからが本題なのですが、ignore_changeしたい場面で考えられるのが、先にコンソールから手動で値を設定した場合です。

具体例を挙げると、画面から↓の様にtagを新たに追加して、

image.png

terraformではこうなっている時です。


resource "aws_eip" "test" {
  tags = {
    Name = "名前"
  }
}

この状態で、terraform planをすると、まだignore設定をしていないので、差分が表示されます。

      ~ tags                 = {
            "Name"                           = "名前"
          - "test"                           = "testValue" -> null
        }
    }

なので、ignore_changeを追加します。


resource "aws_eip" "test" {
  tags = {
    Name = "名前"
  }
  lifecycle {
    ignore_changes = [
      tags["test"], // 追加
    ]
  }
}

ぱっと見よさそうですが、実はこれでは ignore_changes がうまく扱われずに、まだ差分があると認識されてしまいます。

正解はこうです。


resource "aws_eip" "test" {
  tags = {
    Name = "名前"
    test = "" // これが必要
  }
  lifecycle {
    ignore_changes = [
      tags["test"],
    ]
  }
}

ignore_changes で指定している値を、resourcesに実際に書いてあげる必要があります。値自体は無視されるので、内容はなんでも良いです。keyが(例だとtest)が設定されている必要があります。

補足

Terraform v0.13.5 で動作確認しました。

19
6
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
19
6