zaki work log

作業ログやら生活ログやらなんやら

[Terraform / AWS] 勘と雰囲気と勢いでEC2インスタンス作成してsshアクセスまで入門

クラウドのリソースで似たものをたくさん作る機会があってその時は温かみのある手作業で対応したんだけど、どう考えてもコード化した方が良かったので、Terraformの使い方についてAWSVPCからEC2作成までお試し入門してみた。

お題

2年前に演習的に作成したリンク先の環境をそっくりTerraformで作ってみる。

qiita.com

2021.04.17追記: 本記事はv0.12の内容。v0.15での確認は以下参照。

zaki-hmkc.hatenablog.com

Terraform CLIツールのインストール

こちらから。

プラットフォームにあったバイナリをダウンロードする。
今回はローカルのCentOS7で実行したいので、Linux 64bitをダウンロード。

なんでzipなんだ。

[zaki@manager-dev terraform]$ curl -LO https://releases.hashicorp.com/terraform/0.12.26/terraform_0.12.26_linux_amd64.zip
[zaki@manager-dev terraform]$ ls -l
合計 16444
-rw-rw-r--. 1 zaki zaki 16838433  6月 18 20:04 terraform_0.12.26_linux_amd64.zip
[zaki@manager-dev terraform]$ 
[zaki@manager-dev terraform]$ sudo unzip terraform_0.12.26_linux_amd64.zip -d /usr/local/bin/
Archive:  terraform_0.12.26_linux_amd64.zip
  inflating: /usr/local/bin/terraform  
[zaki@manager-dev terraform]$ which terraform 
/usr/local/bin/terraform
[zaki@manager-dev terraform]$ terraform --version
Terraform v0.12.26

作業用ディレクトリ作成

今回は~/terraform/aws/practice/を作業場所とした。

アカウント設定

Provider: AWS - Terraform by HashiCorp

AWSの場合はTerraform用にIAMユーザを作成し、そのアクセスキー・シークレットキーを設定する。

ドキュメントをざっと見た感じだと、環境変数に設定するのが楽そう。

$ export AWS_ACCESS_KEY_ID=<アクセスキー>
$ export AWS_SECRET_ACCESS_KEY=<シークレットキー>

IAMユーザーについてはこの辺参照

qiita.com

provider設定

環境変数の認証情報と、awsプロバイダを作成する。(ファイル名:provider.tf)

provider "aws" {
  version = "~> 2.8"
  region  = "ap-northeast-1"
}

ちなみにversion~> 3.0だとエラーになった。

terraform init

初期化する。

[zaki@manager-dev practice]$ terraform init

Initializing the backend...

Initializing provider plugins...
- Checking for available provider plugins...
- Downloading plugin for provider "aws" (hashicorp/aws) 2.66.0...

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.
[zaki@manager-dev practice]$ 

実行するとワークディレクトリに.terraform/というディレクトリが作成される。

VPCの確認と、お試しの作成/削除

AWS: aws_vpc - Terraform by HashiCorp

aws_vpcのリソースを作成する。(ファイル名:vpc.tf)

resource "aws_vpc" "practice" {
  cidr_block = "172.26.0.0/16"

  tags = {
    Name = "vpc-aws-study-example"
  }
}

まずはこれだけ。

現在のファイルリスト

[zaki@manager-dev practice]$ ls
env.source  provider.tf  vpc.tf

現在の状態でdry runしてみる

dry runするにはterraform planを実行する。

[zaki@manager-dev practice]$ ls
env.source  provider.tf  vpc.tf
[zaki@manager-dev practice]$ terraform plan
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.


------------------------------------------------------------------------

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

Terraform will perform the following actions:

  # aws_vpc.practice will be created
  + resource "aws_vpc" "practice" {
      + arn                              = (known after apply)
      + assign_generated_ipv6_cidr_block = false
      + cidr_block                       = "172.26.0.0/16"
      + default_network_acl_id           = (known after apply)
      + default_route_table_id           = (known after apply)
      + default_security_group_id        = (known after apply)
      + dhcp_options_id                  = (known after apply)
      + enable_classiclink               = (known after apply)
      + enable_classiclink_dns_support   = (known after apply)
      + enable_dns_hostnames             = (known after apply)
      + enable_dns_support               = true
      + id                               = (known after apply)
      + instance_tenancy                 = "default"
      + ipv6_association_id              = (known after apply)
      + ipv6_cidr_block                  = (known after apply)
      + main_route_table_id              = (known after apply)
      + owner_id                         = (known after apply)
      + tags                             = {
          + "Name" = "vpc-aws-study-example"
        }
    }

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

------------------------------------------------------------------------

Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.

[zaki@manager-dev practice]$ 

ここで1項目がaddされることが分かる。
内訳は、+で始まってる行の内容でリソースが作成される。

問題無ければ実際に実行する。

ちなみに作成前のwebコンソールで確認したVPCの状態

f:id:zaki-hmkc:20200618214510p:plain

作成する

planで問題無ければ、applyで実際に実行する。
途中、本当に続けてよいか確認されるので、Enter a value:のプロンプトにyesと入力する。

[zaki@manager-dev practice]$ terraform apply

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

Terraform will perform the following actions:

  # aws_vpc.practice will be created
  + resource "aws_vpc" "practice" {
      + arn                              = (known after apply)
      + assign_generated_ipv6_cidr_block = false
      + cidr_block                       = "172.26.0.0/16"
      + default_network_acl_id           = (known after apply)
      + default_route_table_id           = (known after apply)
      + default_security_group_id        = (known after apply)
      + dhcp_options_id                  = (known after apply)
      + enable_classiclink               = (known after apply)
      + enable_classiclink_dns_support   = (known after apply)
      + enable_dns_hostnames             = (known after apply)
      + enable_dns_support               = true
      + id                               = (known after apply)
      + instance_tenancy                 = "default"
      + ipv6_association_id              = (known after apply)
      + ipv6_cidr_block                  = (known after apply)
      + main_route_table_id              = (known after apply)
      + owner_id                         = (known after apply)
      + tags                             = {
          + "Name" = "vpc-aws-study-example"
        }
    }

Plan: 1 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

aws_vpc.practice: Creating...
aws_vpc.practice: Creation complete after 2s [id=vpc-0e20495abd5b061ab]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
[zaki@manager-dev practice]$ 

無事にリソースが作成されました。

webコンソールで確認しても、新しくリソースが増えているのがわかる。

f:id:zaki-hmkc:20200618214437p:plain

削除する

applyで作成されるのに対して、destroyで削除できる。
Ansibleのpresentabsentみたいな感じ。(想像)

destroyapplyと同様に、実行確認があるのでyesを入力する。

[zaki@manager-dev practice]$ terraform destroy
aws_vpc.practice: Refreshing state... [id=vpc-0e20495abd5b061ab]

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

Terraform will perform the following actions:

  # aws_vpc.practice will be destroyed
  - resource "aws_vpc" "practice" {
      - arn                              = "arn:aws:ec2:ap-northeast-1:598843273716:vpc/vpc-0e20495abd5b061ab" -> null
      - assign_generated_ipv6_cidr_block = false -> null
      - cidr_block                       = "172.26.0.0/16" -> null
      - default_network_acl_id           = "acl-00bc2105ce335b96f" -> null
      - default_route_table_id           = "rtb-0a3364506150a424a" -> null
      - default_security_group_id        = "sg-064e86a502ab17dd0" -> null
      - dhcp_options_id                  = "dopt-102d5e77" -> null
      - enable_classiclink               = false -> null
      - enable_classiclink_dns_support   = false -> null
      - enable_dns_hostnames             = false -> null
      - enable_dns_support               = true -> null
      - id                               = "vpc-0e20495abd5b061ab" -> null
      - instance_tenancy                 = "default" -> null
      - main_route_table_id              = "rtb-0a3364506150a424a" -> null
      - owner_id                         = "598843273716" -> null
      - tags                             = {
          - "Name" = "vpc-aws-study-example"
        } -> null
    }

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

aws_vpc.practice: Destroying... [id=vpc-0e20495abd5b061ab]
aws_vpc.practice: Destruction complete after 0s

Destroy complete! Resources: 1 destroyed.
[zaki@manager-dev practice]$ 

消えました。
webコンソールでもこの通り。

f:id:zaki-hmkc:20200618214848p:plain

サブネット

AWS: aws_subnet - Terraform by HashiCorp

VPCの作成がわかったのでサブネットを作る。(ファイル名:subnet.tf)

resource "aws_subnet" "prac_public" {
  vpc_id            = "${aws_vpc.practice.id}"
  cidr_block        = "172.26.10.0/24"
  availability_zone = "ap-northeast-1a"

  tags = {
    Name = "public-subnet-aws-study"
  }
}

まず1個分作成したplanしてみる。

[zaki@manager-dev practice]$ terraform plan
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.


------------------------------------------------------------------------

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

Terraform will perform the following actions:

  # aws_subnet.prac_public will be created
  + resource "aws_subnet" "prac_public" {
      + arn                             = (known after apply)
      + assign_ipv6_address_on_creation = false
      + availability_zone               = "ap-northeast-1a"
      + availability_zone_id            = (known after apply)
      + cidr_block                      = "172.26.10.0/24"
      + id                              = (known after apply)
      + ipv6_cidr_block                 = (known after apply)
      + ipv6_cidr_block_association_id  = (known after apply)
      + map_public_ip_on_launch         = false
      + owner_id                        = (known after apply)
      + tags                            = {
          + "Name" = "public-subnet-aws-study"
        }
      + vpc_id                          = (known after apply)
    }

  # aws_vpc.practice will be created
  + resource "aws_vpc" "practice" {
      + arn                              = (known after apply)
      + assign_generated_ipv6_cidr_block = false
      + cidr_block                       = "172.26.0.0/16"
      + default_network_acl_id           = (known after apply)
      + default_route_table_id           = (known after apply)
      + default_security_group_id        = (known after apply)
      + dhcp_options_id                  = (known after apply)
      + enable_classiclink               = (known after apply)
      + enable_classiclink_dns_support   = (known after apply)
      + enable_dns_hostnames             = (known after apply)
      + enable_dns_support               = true
      + id                               = (known after apply)
      + instance_tenancy                 = "default"
      + ipv6_association_id              = (known after apply)
      + ipv6_cidr_block                  = (known after apply)
      + main_route_table_id              = (known after apply)
      + owner_id                         = (known after apply)
      + tags                             = {
          + "Name" = "vpc-aws-study-example"
        }
    }

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

Warning: Interpolation-only expressions are deprecated

  on subnet.tf line 2, in resource "aws_subnet" "prac_public":
   2:   vpc_id            = "${aws_vpc.practice.id}"

Terraform 0.11 and earlier required all non-constant expressions to be
provided via interpolation syntax, but this pattern is now deprecated. To
silence this warning, remove the "${ sequence from the start and the }"
sequence from the end of this expression, leaving just the inner expression.

Template interpolation syntax is still used to construct strings from
expressions when the template includes multiple interpolation sequences or a
mixture of literal strings and interpolations. This deprecation applies only
to templates that consist entirely of a single interpolation sequence.


------------------------------------------------------------------------

Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.

[zaki@manager-dev practice]$ 

なんか警告がわらわら出てる。

ドキュメントの通りに記述はしてるんだけど、警告メッセージを見る限り、変数参照は${ ... }の書式は不要で、そのまま書けば良いっぽい。

resource "aws_subnet" "prac_public" {
  vpc_id            = aws_vpc.practice.id
  cidr_block        = "172.26.10.0/24"
  availability_zone = "ap-northeast-1a"

  tags = {
    Name = "public-subnet-aws-study"
  }
}

というわけで、こんな感じ。
planを実行してもwarningは出ない。

念のためapplyして確認。

[zaki@manager-dev practice]$ terraform apply

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

Terraform will perform the following actions:

  # aws_subnet.prac_public will be created
  + resource "aws_subnet" "prac_public" {
      + arn                             = (known after apply)
      + assign_ipv6_address_on_creation = false
      + availability_zone               = "ap-northeast-1a"
      + availability_zone_id            = (known after apply)
      + cidr_block                      = "172.26.10.0/24"
      + id                              = (known after apply)
      + ipv6_cidr_block                 = (known after apply)
      + ipv6_cidr_block_association_id  = (known after apply)
      + map_public_ip_on_launch         = false
      + owner_id                        = (known after apply)
      + tags                            = {
          + "Name" = "public-subnet-aws-study"
        }
      + vpc_id                          = (known after apply)
    }

  # aws_vpc.practice will be created
  + resource "aws_vpc" "practice" {
      + arn                              = (known after apply)
      + assign_generated_ipv6_cidr_block = false
      + cidr_block                       = "172.26.0.0/16"
      + default_network_acl_id           = (known after apply)
      + default_route_table_id           = (known after apply)
      + default_security_group_id        = (known after apply)
      + dhcp_options_id                  = (known after apply)
      + enable_classiclink               = (known after apply)
      + enable_classiclink_dns_support   = (known after apply)
      + enable_dns_hostnames             = (known after apply)
      + enable_dns_support               = true
      + id                               = (known after apply)
      + instance_tenancy                 = "default"
      + ipv6_association_id              = (known after apply)
      + ipv6_cidr_block                  = (known after apply)
      + main_route_table_id              = (known after apply)
      + owner_id                         = (known after apply)
      + tags                             = {
          + "Name" = "vpc-aws-study-example"
        }
    }

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

aws_vpc.practice: Creating...
aws_vpc.practice: Creation complete after 3s [id=vpc-08b35b5c9c25f0101]
aws_subnet.prac_public: Creating...
aws_subnet.prac_public: Creation complete after 2s [id=subnet-09dc730a1cc4d10f6]
Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
[zaki@manager-dev practice]$ 

問題無い。

f:id:zaki-hmkc:20200618220429p:plain

(作成が確認できたので、また削除しておく) <- Ansibleと同じように冪等性があるので消さなくてもよかった。

同じ要領で、3つのサブネットの定義を記述する。

resource "aws_subnet" "prac_public" {
  vpc_id            = aws_vpc.practice.id
  cidr_block        = "172.26.10.0/24"
  availability_zone = "ap-northeast-1a"

  tags = {
    Name = "public-subnet-aws-study"
  }
}

resource "aws_subnet" "prac_priv1" {
  vpc_id            = aws_vpc.practice.id
  cidr_block        = "172.26.20.0/24"
  availability_zone = "ap-northeast-1a"

  tags = {
    Name = "private1-subnet-aws-study"
  }
}

resource "aws_subnet" "prac_priv2" {
  vpc_id            = aws_vpc.practice.id
  cidr_block        = "172.26.30.0/24"
  availability_zone = "ap-northeast-1c"

  tags = {
    Name = "private2-subnet-aws-study"
  }
}

インターネットゲートウェイ

AWS: aws_internet_gateway - Terraform by HashiCorp

どんどんいくよー。(ファイル名:igw.tf)

resource "aws_internet_gateway" "gw" {
  vpc_id = aws_vpc.practice.id

  tags = {
    Name = "igw-aws-study"
  }
}

あれ?アタッチの設定がないね。

正解がほんとわかんないんだけど、ここまでの状態で試しにapplyしてみると、勝手にアタッチされていた。

あああ、、もしかしてvpc_idで指定してるから大丈夫ってことかな?

f:id:zaki-hmkc:20200618221627p:plain

ルートテーブルの作成

AWS: aws_route_table - Terraform by HashiCorp

ちょっとややこしい。(ファイル名:route_table.tf)

「サブネットの関連付け」がArgumentを見る限り存在しない。
よくよく探すと、aws_route_table_assosicatoinがあり、これと連携して設定する模様。

AWS: aws_route_table_association - Terraform by HashiCorp

というわけで、パブリックネットワーク用のルートテーブルはこんな感じ。

resource "aws_route_table" "public_route" {
  vpc_id = aws_vpc.practice.id

  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = aws_internet_gateway.gw.id
  }

  tags = {
    Name = "public-route-table-aws-study"
  }
}

resource "aws_route_table_association" "public_subnet" {
  subnet_id      = aws_subnet.prac_public.id
  route_table_id = aws_route_table.public_route.id
}

ちなみに、「デフォルトで作成されるルートテーブルにNameタグだけ付ける」という操作はちょっとわからなかった。

DNSホスト名の有効化

ホスト名付与のためのVPCに設定追加が必要だった。
enable_dns_hostnames = trueを追加。

resource "aws_vpc" "practice" {
  cidr_block = "172.26.0.0/16"
  enable_dns_hostnames = true

  tags = {
    Name = "vpc-aws-study-example"
  }
}

セキュリティグループ

AWS: aws_security_group - Terraform by HashiCorp

まずはICMPを許可する設定

resource "aws_security_group" "allow_ssh_icmp" {
  name        = "ssh-icmp"
  description = "ssh-icmp"
  vpc_id      = aws_vpc.practice.id

  ingress {
    from_port   = -1
    to_port     = -1
    protocol    = "icmp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = {
    Name = "ssh-icmp-security-group"
  }
}

あれ、2つ目のルール(SSHを許可したい)はどうすれば…

ドキュメントのタイトル一覧が連続してなかったので見落としそうだったけど、aws_security_group_ruleというものがあった。

AWS: aws_security_group_rule - Terraform by HashiCorp

SSHであればこれで。

resource "aws_security_group_rule" "ssh" {
  type              = "ingress"
  from_port         = 22
  to_port           = 22
  protocol          = "tcp"
  cidr_blocks       = ["0.0.0.0/0"]
  security_group_id = aws_security_group.allow_ssh_icmp.id
}

というか、ルールは全部外に出せるってことだな。
全体でこんな感じ。

resource "aws_security_group" "allow_ssh_icmp" {
  name        = "ssh-icmp"
  description = "ssh-icmp"
  vpc_id      = aws_vpc.practice.id

  tags = {
    Name = "ssh-icmp-security-group"
  }
}

resource "aws_security_group_rule" "ssh" {
  type              = "ingress"
  from_port         = 22
  to_port           = 22
  protocol          = "tcp"
  cidr_blocks       = ["0.0.0.0/0"]
  security_group_id = aws_security_group.allow_ssh_icmp.id
}

resource "aws_security_group_rule" "icmp" {
  type              = "ingress"
  from_port         = -1
  to_port           = -1
  protocol          = "icmp"
  cidr_blocks       = ["0.0.0.0/0"]
  security_group_id = aws_security_group.allow_ssh_icmp.id
}

resource "aws_security_group_rule" "egress" {
  type              = "egress"
  from_port         = 0
  to_port           = 0
  protocol          = "-1"
  cidr_blocks       = ["0.0.0.0/0"]
  security_group_id = aws_security_group.allow_ssh_icmp.id
}

ネットワーク関連はこれでOK

EC2インスタンスの作成

いよいよVM作る。
そしてaws_ec2_***が異様にたくさんあってどうすればイインダー状態。

ここで中断したかったけど、調べたらaws_instanceを使えば良さげ。

AWS: aws_instance - Terraform by HashiCorp

aws_instanceの指定は見ればわかるんだけど、amiの方が何書いてあるか読めない。。

ので、検索してヒットした、クラスメソッドさんの定義から記述を拝借。

dev.classmethod.jp

それからネットワーク設定…public ipの設定はassociate_public_ip_addressで、VPCの指定は無く、あとはサブネットの指定くらいしか見当たらなかった。

あとはキーペア設定かな。

AWS: aws_key_pair - Terraform by HashiCorp

sshの鍵は、あらかじめ手元で作成しておき、公開鍵の内容を記載。

ということで、こんな感じでどうでしょうか。

data "aws_ssm_parameter" "amzn2_ami" {
  name = "/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2"
}

resource "aws_key_pair" "my_key" {
  key_name   = "deployer-key"
  public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDyK6HCvGQr84FgD+CDa7cCtt+D03bMb2O/surNv5pkSbPJ4T4d+E79tqjqjhxunse5lPnTCKeA22YzCQpjvnfXNci8OeFfHI6Amni8/Y3ANgjJ9W/5MYYXVTrDhohST62zURsZWTSpevK3LAHxzylyzKpKPTUuP204ff7s1G2PEg61w4DEOn19L7MaO0E0aKG6vr5SkvpKCZ9eGW+dhKK6bXW5scmmbmRUquIfO5SvdcCVAS/fbRtuXstIjSJYomhM8eExMVNwl97qC86Fq8jKQbnx1XK/+I/M62sMlJ3/DV0lZGYxAdeBGIP8U2lyH4lfQ2kNGCWaqxnDzKSEqcU8n+lJcmwNXLTj93/gyuqdm5gbAKaTcmftQ30R9LqosrdguNoFy0uN0Mhvo7jqE6a6p5ZRJYi7svAQFslE8OqHKr/ZevoPPFjmWKw8+hgDtJhtxHZO8Rvce0IJI1YILd2hJMDrJQBL0BRaFipGvGd594+DmtdSx2U58KfmaZ0rArLexWa8LjgooRaOdE+54z97wFqgMFgRJz7CgMJAm5dyux4nDFZFpXLWkW4YSyjylCEiEMQtPmi6H+7W4zDx/nrVXFlGxfexNE42ANertD60JzZprnKS9Y6nxqqjow3RqLmqbK8TdtN64/ls+Jsss3FhQDOXNK5WgFKCG1iCuYXCdw=="
}

resource "aws_instance" "bastion" {
  ami                         = data.aws_ssm_parameter.amzn2_ami.value
  instance_type               = "t3.nano"
  key_name                    = aws_key_pair.my_key.id
  subnet_id                   = aws_subnet.prac_public.id
  security_groups             = [aws_security_group.allow_ssh_icmp.id]
  associate_public_ip_address = true

  tags = {
    Name = "HelloWorld"
  }
}

いくぜ!

[zaki@manager-dev practice]$ terraform apply -auto-approve 
data.aws_ssm_parameter.amzn2_ami: Refreshing state...
aws_key_pair.my_key: Creating...
aws_vpc.practice: Creating...
aws_key_pair.my_key: Creation complete after 0s [id=deployer-key]
aws_vpc.practice: Creation complete after 3s [id=vpc-0a330c046eeb054fb]
aws_subnet.prac_priv2: Creating...
aws_security_group.allow_ssh_icmp: Creating...
aws_subnet.prac_priv1: Creating...
aws_internet_gateway.gw: Creating...
aws_subnet.prac_public: Creating...
aws_subnet.prac_priv2: Creation complete after 1s [id=subnet-0349dd67e95b1b6d0]
aws_subnet.prac_priv1: Creation complete after 1s [id=subnet-02bb47986e9f6dd16]
aws_internet_gateway.gw: Creation complete after 1s [id=igw-05223b63e6857ff0d]
aws_route_table.public_route: Creating...
aws_subnet.prac_public: Creation complete after 1s [id=subnet-0132b08244144b392]aws_security_group.allow_ssh_icmp: Creation complete after 1s [id=sg-0e292dba4ea77dbb4]
aws_security_group_rule.egress: Creating...
aws_security_group_rule.icmp: Creating...
aws_instance.bastion: Creating...
aws_security_group_rule.ssh: Creating...
aws_route_table.public_route: Creation complete after 1s [id=rtb-0426487311aa569cb]
aws_route_table_association.public_subnet: Creating...
aws_route_table_association.public_subnet: Creation complete after 0s [id=rtbassoc-044b755dfe11365dc]
aws_security_group_rule.egress: Creation complete after 1s [id=sgrule-130298719]aws_security_group_rule.icmp: Creation complete after 2s [id=sgrule-3390099364]
aws_security_group_rule.ssh: Creation complete after 2s [id=sgrule-1620952985]
aws_instance.bastion: Still creating... [10s elapsed]
aws_instance.bastion: Creation complete after 13s [id=i-0335ed46a3ddee70a]

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

f:id:zaki-hmkc:20200619001345p:plain

何度かうまくいかずに試行錯誤した残骸が残ってるけど、EC2が作成された。

[zaki@manager-dev practice]$ ssh ec2-user@ec2-********.ap-northeast-1.compute.amazonaws.com
The authenticity of host 'ec2-********.ap-northeast-1.compute.amazonaws.com (13.114.50.30)' can't be established.
ECDSA key fingerprint is SHA256:UrN5GhWTr7UU5wsx87UQFolSmv4rWXEjduwnrb4Olr0.
ECDSA key fingerprint is MD5:d6:97:06:aa:3f:66:9b:b5:bc:d9:70:2b:fe:ac:49:e9.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'ec2-********.ap-northeast-1.compute.amazonaws.com,13.114.50.30' (ECDSA) to the list of known hosts.

       __|  __|_  )
       _|  (     /   Amazon Linux 2 AMI
      ___|\___|___|

https://aws.amazon.com/amazon-linux-2/
4 package(s) needed for security, out of 10 available
Run "sudo yum update" to apply all updates.
[ec2-user@ip-172-26-10-12 ~]$
[ec2-user@ip-172-26-10-12 ~]$ uname -a
Linux ip-172-26-10-12.ap-northeast-1.compute.internal 4.14.177-139.254.amzn2.x86_64 #1 SMP Thu May 7 18:48:23 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

sshアクセスも確認。


2021.05.22追記: VPC内のEC2のセキュリティグループの指定は、security_group_idでなくvpc_security_group_idsを使って指定しないと、再実行時にEC2が強制再作成されてしまうので注意。

zaki-hmkc.hatenablog.com


applyで確認を行わないオプションは-auto-approve
destroyで確認を行わないオプションは-force


Terraformのリファレンス、リソースに設定するパラメタ(Attribute)の型(リストなのかどうか)がわからん。


Terraformの記述のMarkdown用ハイライトってないのかな。。