Learn Terraform - GET STARTED - AWS 練習メモ
- Introduction to Infrastructure as Code with Terraform
- Install Terraform
- Build Infrastructure
- Change Infrastructure
- Destroy Infrastructure
- Resource Dependencies
- Provision
- Input Variables
- Output Variables
- Remote State Storage
- Next Steps
- 宿題
Introduction to Infrastructure as Code with Terraform
- HashiCorp Configuration Language (HCL)
Install Terraform
anyenv経由の tfenv` でインストールしたtfenvはrbenvなどと結構違う
terraform -install-autocomplete
Build Infrastructure
- AMI で
terraformというアカウントを作った VPCResourceNotSpecified- Troubleshooting に解決策あり
- VPC を手動で作って .tf にセキュリティグループとサブネットを記入する
- 原因: t2 インスタンスは VPC 内にしか作れないが、古い AWS アカウントはデフォルト VPC を持っていない
- https://github.com/hashicorp/terraform/issues/4367
- 自分の AWS アカウントをデフォルト VPC を持つように変更してもらうこともできる https://github.com/hashicorp/terraform/issues/4367#issuecomment-513480968
- Troubleshooting に解決策あり
Change Infrastructure
-/+destroy and recreate the resource~some attributes can be updated in-place
Destroy Infrastructure
- Destroying your infrastructure is a rare event in production environments. But if you're using Terraform to spin up multiple environments such as development, test, QA environments, then destroying is a useful action.
Resource Dependencies
- Implicit dependencies interpolation
resource.name.attributeaws_instance.example.id
- Explicit dependencies
depends_ondepends_on = [aws_s3_bucket.example]
Provision
- Terraform でインスタンスのプロビジョニングもできる、が...
local-execprovisioner はローカルマシン上でコマンドを実行するterraform init && terraform applyでlocal-execprovisioner が実行されるかのように書いてあるが、実行されないterraform destroy && terraform applyが必要- チュートリアルの下の方に書いてあるが...
command = "echo ${aws_instance.example.public_ip} > ip_address.txt"でファイルはつくられたけど中身が空...- provisioning でエラーが発生したリソースは
tainted- When you generate your next execution plan, Terraform will not attempt to restart provisioning on the same resource because it isn't guaranteed to be safe. Instead, Terraform will remove any tainted resources and create new resources, attempting to provision them again after creation.
taintedなリソースをうっかり実運用にのせてしまうと後で意図せず消されてしまう、みたいな落とし穴がありそう
terraform tainttaint前後でterraform showの diff-# aws_instance.example:+# aws_instance.example: (tainted)
Input Variables
-var 'key=value'terraform.tfvars- 自動で読み込まれる
*.auto.tfvars- 自動で読み込まれる
*.tfvars- 自動で読み込まれない
-var-fileオプションで指定して読み込む
-var-file='secrets.tfvars'-var-fileは複数回指定可能-var-file='production.tfvars'- Tip: This is one way to provision infrastructure in a staging environment or a production environment using the same Terraform configuration.
export TF_VAR_name- Note: Environment variables can only populate string-type variables. List and map type variables must be populated via one of the other mechanisms.
- var が未指定かつデフォルト値も未定義の場合、プロンプトで入力を促される
- Terraform version <= 0.11
- UI input は string type のみ
- Terraform version >= 0.12
- UI input は List, Map type もいける
- Terraform version <= 0.11
- List type
variable "cidrs" { default = [] }variable "cidrs" { type = list }cidrs = [ "10.0.0.0/16", "10.1.0.0/16" ]
- Map type
variable "amis" {
type = "map"
type = "map"
default = {
"us-east-1" = "ami-b374d5a5"
"us-west-2" = "ami-4b32be2b"
}
}
- lookup
ami = var.amis[var.region]var.amis["us-east-1"]
-varで map 指定terraform apply -var 'amis={ us-east-1 = "foo", us-west-2 = "bar" }'- Note: Even if a map's data is set in a tfvar file, the variable must be declared separately with either type="map" or default={}.
- これハマりそう
- 最後の
outputの例が出力されない- 存在しない ami ID 指定して実行時エラーになってるから?
Output Variables
terraform apply後にterraform outputでoutputで指定した値を取得できるterraform outputで全部terraform output varnameで一個指定
Remote State Storage
- Terraform の実行自体をリモートでやるのがおすすめ
- Terraform Cloud のアカウント作成済みだったが、いつ作った?記憶にない
- 1Password にも入ってない
- .tfstate を remote に migration し終わった後に
terraform applyしたらローカルの .tfstate ファイルは消せというエラー- チュートリアルと違う...
- .tfstate を作業ディレクトリから消して
terraform applyするとError: No value for required variable- https://github.com/hashicorp/terraform/issues/21659
- 少し古いイシューで解決済みとのことだけど、いろいろ入り組んでる
*terraform.tfvarsをterraform.auto.tfvarsにリネームすると No value for required variable エラーは解消するが...- 次は
Error: No valid credential sources found for AWS Provider.エラーが出る - どうやら remote backend に Terraform Cloud を使う場合、 TFC workspace をいつ作ったかによってデフォルトの Execution Mode が Remote か Local か変わったらしい
- 2020/06/10 時点でデフォルトは Remote
- Local に変更したら上記エラーは出なくなった
- UPDATE So I changed my execution mode in TF Cloud for this scope to run locally instead of remote, and 🎉🎉🎉! Fixed all my problems. These changes caught me off guard, so hopefully more people are paying better attention than I am to the HC2019 announcements. とのこと
- EDIT for those with AWS CLI installed and configured: TFC workspaces' "remote plan execution" prevented the automatic scan of ~/.aws/config file that Terraform used to perform. So, you have to explicitly define them inside .auto.tfvars file or switch to "local plan execution" とのこと
- If you want to move back to local state, you can remove the backend configuration block from your configuration and run terraform init again. Terraform will once again ask if you want to migrate your state back to local.
- 設定で remote から local に変更してから init し直したら remote 側にある state をどうやって local に反映するのだ?と思ったが
.terraform/terraform.tfstateというファイルがあったのでそのへんを参照して remote から state の実体を取得するのかな?
- 設定で remote から local に変更してから init し直したら remote 側にある state をどうやって local に反映するのだ?と思ったが
- Terraform Cloud
- A VCS-driven workflow
- GitHub 連携とかそれ系
- An API-driven workflow
- Circle CI から API 叩くとかそれ系
- A VCS-driven workflow
Next Steps
- ついにラスト!
- ただのリンク集
- 別のチュートリアル
- ここまでやってたのが Get Started
- 次のステップが Operations and Development Tracks
宿題
local-execでip_address.txtの中身が空だった件terraform init再実行時に.tfstate.backupファイルができたがそのあたりの挙動の確認