terraformでVPCを作成する

以下ができていることが前提となります。

準備

まずは作業ディレクトリを作成します。wsl2のubuntuでやっているので以下のようなディレクトリになりました。

/mnt/c/root/work/learn/AWS/learn/vpc_sample

これ以降、このディレクトリ配下でファイルを作ってきます。


main.tfを作成します。
vpcを作って、その中にsubnetを作るというシンプルな作りです。

provider "aws" {
  region     = var.aws_region
  access_key = var.aws_access_key
  secret_key = var.aws_secret_key
}

resource "aws_vpc" "main_vpc" {
  cidr_block = var.aws_vpc_cidr
  tags = {
    name = "vpc-sample"
  }
}

# Subnetを作成する
resource "aws_subnet" "subnet" {
  vpc_id     = aws_vpc.main_vpc.id
  cidr_block = "10.0.1.0/24"
}

terraform.tfvarsを作成します。
シークレット関係はここに記載しておきます。

aws_access_key = "hogehoge"
aws_secret_key = "keyhogehoge"
aws_region     = "ap-northeast-1"
aws_vpc_cidr   = "10.0.1.0/24"

variables.tfを作成します。
この内容を main.tfに書いてもいいんですが、別ファイルにしています。
これを記述することで、terraform.tfvarsの値をmain.tfで使えるようになります。

variable "aws_access_key" {}
variable "aws_secret_key" {}
variable "aws_region" {}
variable "aws_vpc_cidr" {}

terraformしていく

terraform init

terraformを実行するために最初にやる必要があるコマンド。

terraform plan

このように構成されますよというのを一度見せてくれます。
これをしても、aws上では何も変化が起こりません。

terraform apply

処理が終わったら入力を促されます。

Plan: 2 to add, 0 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と入力します。

terraform destroy

applyで作ったリソースを消します。
こちらも処理が終わったら入力を促されます。

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

Do you really want to destroy all resources?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value: yes


YESで.

AWS

Posted by takumioda