網頁

2021/11/27

Terraform 使用data source設定EC2 AMI ID

Terraform 使用data source設定EC2 instance的AMI ID。


在「Terraform 建立EC2範例」中resource aws_instance.app_serverami是把Amazon Linux 2的AMI ID寫死,本範例將改從data source取得。

main.tf中新增aws_ssm_parameter data source如下,其意思為從Systems Manager Parameter Store取得name/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2的data instance。

data "aws_ssm_parameter" "ami_id" {
  name = "/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2"
}

接著把resource aws_instance.app_serverami參數的值改為data.aws_ssm_parameter.ami_id.value,意思為參照aws_ssm_parameter.ami_idvalue

修改後main.tf的內容如下。

main.tf

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.27"
    }
  }

  required_version = ">= 0.14.9"
}

provider "aws" {
  profile = "default"
  region  = "ap-northeast-1" // Tokyo
}

data "aws_ssm_parameter" "ami_id" {
  name = "/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2"
}

resource "aws_instance" "app_server" {
  ami           = data.aws_ssm_parameter.ami_id.value
  instance_type = "t2.micro"

  tags = {
    Name = "TerraformProvisionDemo"
  }
}

輸入terraform apply執行。

$ terraform apply
aws_instance.app_server: Refreshing state... [id=i-09f43428032994849]
...
Terraform used the selected providers to generate the following execution plan. Resource actions are
indicated with the following symbols:
  ~ update in-place

Terraform will perform the following actions:

  # aws_instance.app_server will be updated in-place
  ~ resource "aws_instance" "app_server" {
      # Warning: this attribute value will be marked as sensitive and will not
      # display in UI output after applying this change. The value is unchanged.
      ~ ami                                  = (sensitive)
      + iam_instance_profile                 = ""
        id                                   = "i-09f43428032994849"
      + key_name                             = ""
      + outpost_arn                          = ""
      + password_data                        = ""
      + placement_group                      = ""
        tags                                 = {
            "Name" = "TerraformProvisionDemo"
        }
        # (27 unchanged attributes hidden)





        # (5 unchanged blocks hidden)
    }

Plan: 0 to add, 1 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

aws_instance.app_server: Modifying... [id=i-09f43428032994849]
aws_instance.app_server: Modifications complete after 0s [id=i-09f43428032994849]

Apply complete! Resources: 0 added, 1 changed, 0 destroyed.

上次建立時與這次更新的AMI ID相同。



github

沒有留言:

張貼留言