generated at
Terraform
>Terraform is an open-source infrastructure as code software tool that provides a consistent CLI workflow to manage hundreds of cloud services. Terraform codifies cloud APIs into declarative configuration files.

コードでインフラ構成を表現する
実行可能なコードで、インフラの初期プロビジョニング、更新、破棄を実行できる。
AWSだけに特化しているわけではない。AzureGCP向けにも使える。
Terraformファイルの用意
provider定義
例えばawsを使う場合
main.tf
# definition provider provider "aws" {   version = "~> 2.0"   region = "${var.provider_region}"   access_key = "${var.secret_access_key}"   secret_key = "${var.secret_key}" }
resource定義
resource "resource_name" "local_name" {} の構文で書いていく
DBの定義の例は以下
resource.tf
resource "aws_db_instance" "default" {   allocated_storage = "${var.db_allocated_storage}"   storage_type = "${var.db_storage_type}"   engine = "${var.db_engine}"   engine_version = "${var.db_engine_version}"   instance_class = "${var.db_instance_class}"   name = "${var.db_database_name}"   username = "${var.db_database_username}"   password = "${var.secret_db_database_password}"   final_snapshot_identifier = "${var.db_snapshot_identifier}" }
リソースで何を設定すべきかは、リソースの種類であらかじめ決まっている。上の例だと、aws_db_instance への設定項目は、公式の各リリース向けドキュメントを読む。
variables定義
上記の定義で必要な変数の定義
var.XXXで参照されている
variable "XXXX" {} の構文で書いていく
いくつかの例
variables.tf
# provider variables variable "provider_region" {  description = "Provider region"  default = "us-east-1" } variable "secret_access_key" {  description = "Provider access key"  default = "YOUR-ACCESS-KEY" } variable "secret_key" {  description = "Provider secret key"  default = "YOUR-SECRET-KEY" } # instance base de données RDS postgres variables variable "db_allocated_storage" {   description = "Allocated storage"   default = 20 } variable "db_storage_type" {   description = "Storage type"   default = "gp2" } ...
上記の定義ファイルを用意したら、実行していく
初期化
定義ファイルがあるフォルダで、 terraform init を実行
検証
ファイルの記述が正常であることを検証する。
terraform validate
Plan
インラフの作成の操作のみ実行する
terraform plan
この時点では、例えばAWS上にはまだ構築はされてない
Apply
Planの結果を実行する。ProviderのAWS上に構築される
Destory
上記で作った環境を破棄する


moduleを用いたディレクトリ構成が参考になる