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?

AWS学習記録(Terraformについて)

Posted at

使用教材

TerraformでEC2を起動する

  • VSCodeでtfファイルを作成して以下の記述をする
  • 作成したtfファイルと同じパスにtfstateファイルが生成されてAWS上のインスタンス情報などを記録する
  • インスタンス更新する場合は、tfsateとの差分を検知して更新する
  • そのため、マネジメントコンソールなどで手動で更新した場合は実際のインスタンの状態をインポートしないといけない(terrafomr import)

provider "aws" {
    profile = "terraform"
    region = "ap-northeast-1"  #東京リージョン
}

resource "aws_instance" "hello-world" {
  ami           = "ami-025bbcfb04b076789" # Amazon Linux 2023
  instance_type = "t2.micro"

  tags = { 
    Name = "HelloWorld" # タグの設定
  }
}

ユーザデータの追加

  • EC2インスタンス起動時にユーザが指定したスクリプトを実行する機能(ユーザデータ)を追記
  • ユーザデータはインスタンスの初回起動時に設定しないといけないため、すでにインスタンス起動している場合は再作成が必要になる
  • 以下のようにユーザデータの記述を追記したが、更新のみでインスタンスの再作成が行われない
provider "aws" {
    profile = "terraform"
    region = "ap-northeast-1" 
}

resource "aws_instance" "hello-world" {
  ami           = "ami-025bbcfb04b076789" # Amazon Linux 2023
  instance_type = "t2.micro"

    tags = { 
    Name = "HelloWorld" 
  }
    user_data = <<EOF #ユーザデータ追記
      #!/bin/bash
      dnf install -y nginx
      systemctl enable nginx
      systemctl start nginx
      EOF
}

原因

  • terraformはユーザデータの追記を検知してもデフォルトではインスタンス再作成しないためスクリプトが実行されない

解決策

  • 明示的にユーザデータの変更を検知した場合はインスタンスの再作成を実施するよう記述する
provider "aws" {
    profile = "terraform"
    region = "ap-northeast-1" 
}

resource "aws_instance" "hello-world" {
  ami           = "ami-025bbcfb04b076789" # Amazon Linux 2023
  instance_type = "t2.micro"

    tags = { 
    Name = "HelloWorld" 
  }
    user_data = <<EOF 
      #!/bin/bash
      dnf install -y nginx
      systemctl enable nginx
      systemctl start nginx
      echo = 'test' #変更を検知させるための変更点
      EOF
    user_data_replace_on_change = true #ユーザデータの変更後に再作成する記述
}
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?