![見出し画像](https://assets.st-note.com/production/uploads/images/111915568/rectangle_large_type_2_89208467a343eef14f3915a86cd25060.png?width=1200)
Photo by
shino_angle
Terraform Cloud 事始め#3|修正と変数化
↑これの続き
前のディレクトリに移動し、initコマンド実行
terraform init
terraform apply
エラーになった…
│ Error: configuring Terraform AWS Provider: no valid credential sources for Terraform AWS Provider found.
│
│ Please see https://registry.terraform.io/providers/hashicorp/aws
│ for more information about providing credentials.
│
│ AWS Error: failed to refresh cached credentials, no EC2 IMDS role found, operation error ec2imds: GetMetadata, request canceled, context deadline exceeded
│
│
│ with provider["registry.terraform.io/hashicorp/aws"],
│ on main.tf line 12, in provider "aws":
│ 12: provider "aws" {
│
terraform initを実行したせいか?
AWSクレデンシャル情報を環境変数にセットし直し
export AWS_ACCESS_KEY_ID=<*****>
export AWS_SECRET_ACCESS_KEY=<*****>
![](https://assets.st-note.com/img/1690518766403-geJpxByuBN.png?width=1200)
設定変更する(Configuration)
main.tf内のamiを変更してみる
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.16"
}
}
required_version = ">= 1.2.0"
}
provider "aws" {
region = "ap-northeast-1"
}
resource "aws_instance" "app_server" {
instance_type = "t2.micro"
古|ami = "ami-06a89154ee4d34706"
新|ami = "ami-03508a27a8e31bbe5"
tags = {
Name = "ExampleAppServerInstance"
}
}
Apply Changes
terraform apply
![](https://assets.st-note.com/img/1690519104057-yYyonLALYX.png?width=1200)
![](https://assets.st-note.com/img/1690519174338-Xt4hT9BHYe.png?width=1200)
Destroy Infrastructure
terraform destroy
Define Input Variables
ここまではtfファイルの記述内容はすべてハードコード。
変数化する方法をここでは行う。
Set the instance name with a variable
1) 変数化したいものに対するtfファイルを作成する
*defaultの値が反映される
variable "instance_name" {
description = "Value of the Name tag for the EC2 instance"
type = string
default = "NewAppServerInstance"
}
Note:
Terraform loads all files in the current directory ending in .tf, so you can name your configuration files however you choose.
2) main.tfの編集
aws_instanceブロック内のNameタグを今回変数化したい。
tags内にあるNameの値をvar.instance_nameと変更する。
main.tf(抜粋)
resource "aws_instance" "app_server" {
instance_type = "t2.micro"
ami = "ami-03508a27a8e31bbe5"
tags = {
Name = var.instance_name
}
}
3) terraform apply (実行)
反映されない。
terraform initを実行し, terraform applyを実行するも反映されず…
variables.tfのdefaultの値が反映されるが正しかった。
description値が反映されると思っていたため。