🎃
variable変数に関して
main.tfの内容を以下にしてみました。
variable "pet_name" {
type = string
default = "dogs"
}
variable "pet_count" {
type = number
default = 5
}
結果
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Outputs:
message = "There are 5 dogs in the room."
次は-var引数で値を変更してみます。
% terraform apply -var="pet_name=fishes"
Changes to Outputs:
~ message = "There are 5 dogs in the room." -> "There are 5 fishes in the room."
You can apply this plan to save these new output values to the Terraform state, without changing any real infrastructure.
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
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Outputs:
message = "There are 5 fishes in the room."
犬が魚🐟になりましたね
このように-var参照をすることで、main.tfに記述を上書きすることができます。
が、terraform.tfvarsでやる方が早いので
main.tfの同階にterraform.tfvarsを作ります。

内容は以下のように記載します。
#terraform.tfvars
pet_name = "fishes"
pet_count = 7
すると以下のようになります。
% terraform apply
Changes to Outputs:
~ message = "There are 5 cats in the room." -> "There are 7 fishes in the room."
You can apply this plan to save these new output values to the Terraform state, without changing any real infrastructure.
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
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Outputs:
message = "There are 7 fishes in the room."
main.tfの記載からterraform.tfvarsを参照し、値を変えることができました。
これを応用してAWSのアカウントIDとリージョン情報を取得します。
#main.tf
variable "aws_profile_name" {
type = string
default = "develop"
}
provider "aws" {
profile = var.aws_profile_name
}
#AWSアカウント情報を取得
data "aws_caller_identity" "current" {}
#リージョンを取得
data "aws_region" "current" {}
output "account_id" {
value = data.aws_caller_identity.current.account_id
}
output "current_region" {
value = data.aws_region.current.name
}
実行結果
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Outputs:
account_id = "アカウント名"
current_region = "ap-northeast-1"
上記のように表示されれrばOKです。
Discussion