7
1

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 5 years have passed since last update.

terraformでaws_launch_configurationを作成する時は、name_prefixを使う

7
Posted at

概要

terraformでaws_launch_configurationを更新したい時に、再作成できなくて困ったのでメモ

以下のようなコードでaws_launch_configurationを作成した。

resource "aws_launch_configuration" "config" {
  name                               = "hogehoge-config"
  image_id                    = "ami-0e95c345XXXXXXXXXXX"
  instance_type               = "t2.micro"
  key_name                    = "adminkey"
  security_groups             = ["sg-1234567890"]
  associate_public_ip_address = 0

  lifecycle {
    create_before_destroy = true
  }
}

作成したあとにAMIを入れ替えたくなったので、修正して再作成。
terraform apply したところ以下のようなエラーを受け取った。

Error: Error applying plan:

1 error(s) occurred:

* module.autoscale.aws_launch_configuration.config: 1 error(s) occurred:

* aws_launch_configuration.config: Error creating launch configuration: AlreadyExists: Launch Configuration by this name already exists - A launch configuration already exists with the name <リソース名>
        status code: 400, request id: a2a7ac89-b0ca-11e8-8187-db9a15b5b0a9

どうやら一度作ったリソース名と同じ名前のリソースを再作成できないらしい。

解決策

resource "aws_launch_configuration" "config" {
  name_prefix                        = "hogehoge-config"  // name -> name_prefixに修正
  image_id                    = "ami-0e95c345XXXXXXXXXXX"
  instance_type               = "t2.micro"
  key_name                    = "adminkey"
  security_groups             = ["sg-1234567890"]
  associate_public_ip_address = 0

  lifecycle {
    create_before_destroy = true
  }
}

として再度applyすると今度は通った。

ドキュメント

公式ドキュメントには以下のように書かれている

Launch Configurations cannot be updated after creation with the Amazon Web Service API. In order to update a Launch Configuration, Terraform will destroy the existing resource and create a replacement.
In order to effectively use a Launch Configuration resource with an AutoScaling Group resource, it's recommended to specify create_before_destroy in a lifecycle block. 
Either omit the Launch Configuration name attribute, or specify a partial name with name_prefix. 

実行後

applyを実行すると、AutoScaling Groupは新しいaws_launch_configurationを元にしたものに変更されるが、すでに起動されているインスタンスが更新されるわけではない。よって新しいaws_launch_configurationでインスタンスを更新したい場合はAutoscaleさせる必要がある。

参考

https://github.com/hashicorp/terraform/issues/3665
https://www.terraform.io/docs/providers/aws/r/launch_configuration.html

7
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
7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?