ksaitoの日記

日々試したことの覚え書き

terraformでデフォルトVPCを扱う

移転しました。

自動的にリダイレクトします。

ちょっとした、検証をする場合に、都度、VPCを作りたくないので、デフォルトVPCを使いたいことがよくあります。

terraformでデフォルトVPCのVPCIDを参照するには、dataを使うのが良さそうです。

コードの取得

下記のコマンドでサンプルコードを取得します。

git clone https://gitlab.com/softlab-pub/terraform/sample.git -b 20200515-0955 --depth 1
cd sample/vpc/default_vpc

簡単な説明

コードは、下記の通りで、dataを使ってデフォルトVPCの情報を取得して表示します。

terraformで、スコープがモジュール内の変数は、localsに集めて定義すると、tfファイルの保守性が向上します。

$ cat -n main.tf 
     1  provider "aws" {
     2    profile = "terraform"
     3    region  = "ap-northeast-1"
     4  }
     5
     6  data "aws_vpc" "target_vpc" {
     7    default = true
     8  }
     9
    10  locals {
    11    vpc_id = data.aws_vpc.target_vpc
    12  }
    13
    14  output "vpc_id" {
    15    value = local.vpc_id.id
    16  }

使い方

初期化して変更内容を確認します。

terraform init

terraform planで適用される変更を確認することができます。 No changesと出ているので何かを変更してしまうことはありません。

terraform plan

applyするとデフォルトVPCのVPCIDが表示されます。

$ terraform apply
data.aws_vpc.target_vpc: Refreshing state...

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

vpc_id = vpc-******
$

terraform outputで外部に公開する情報を確認できます。 取得できている情報は、terraform showで確認することができます。

使い終わったら削除します。

下記の通り、変更予定の内容を表示して確認を求められます。

$ terraform destroy
data.aws_vpc.target_vpc: Refreshing state...

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:

Terraform will perform the following actions:

Plan: 0 to add, 0 to change, 0 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


Destroy complete! Resources: 0 destroyed.
$