This page looks best with JavaScript enabled

Terraformに入門したのでざっくりメモ

 ·  ☕ 6 分で読めます
✏️

実際にいろいろやってみたログを記録する。

1
2
3
$ terraform -v
Terraform v1.1.7
on darwin_arm64

現ローカル環境にAWS Cliは入れていない。

公式チュートリアル: Get Started - AWS | Terraform - HashiCorp Learn

完全初心者向けTerraform入門(AWS)をやってみた

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$ terraform init

Initializing the backend...

Initializing provider plugins...
- Finding latest version of hashicorp/aws...
- Installing hashicorp/aws v4.8.0...
- Installed hashicorp/aws v4.8.0 (signed by HashiCorp)

Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.

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.
1
2
$ terraform validate
Success! The configuration is valid.
1
2
$ terraform fmt
aws_ec2.tf # これが整形されたファイル

このコマンドで、.terraformディレクトリと.terraform.lock.hclファイルが生成された。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
$ terraform apply
╷
│ Error: error configuring Terraform AWS Provider: no valid credential sources for Terraform AWS Provider found.
│
│ Please see https://registry.terraform.io/providers/hashicorp/aws
│ for more information about providing credentials.
│
│ Error: failed to refresh cached credentials, no EC2 IMDS role found, operation error ec2imds: GetMetadata, request send failed, Get "http://169.254.169.254/latest/meta-data/iam/security-credentials/": dial tcp 169.254.169.254:80: i/o timeout
│
│
│   with provider["registry.terraform.io/hashicorp/aws"],
│   on provider.tf line 1, in provider "aws":
│    1: provider "aws" {
│
╵

【Terraform】AWS事始め - Qiitaを参考にAWSのIAMを作成した。
image

【Terraform】awsのprofileの認証情報で403エラーが出る | ハックノートを参考にして環境変数を定義した。

ちなみに、このとき途中でエラーが出たが、途中までの段階でVPCなどは作成されていた。
image

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
$ terraform apply

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # aws_instance.sample_web_server will be created
  + resource "aws_instance" "sample_web_server" {
      + ami                                  = "ami-0fc6e8f1041d0a223"
      + arn                                  = (known after apply)
      + associate_public_ip_address          = (known after apply)
      + availability_zone                    = (known after apply)
      + cpu_core_count                       = (known after apply)
      + cpu_threads_per_core                 = (known after apply)
      + disable_api_termination              = (known after apply)
      + ebs_optimized                        = (known after apply)
      + get_password_data                    = false
      + host_id                              = (known after apply)
      + id                                   = (known after apply)
      + instance_initiated_shutdown_behavior = (known after apply)
      + instance_state                       = (known after apply)
      + instance_type                        = "t2.micro"
      + ipv6_address_count                   = (known after apply)
      + ipv6_addresses                       = (known after apply)
      + key_name                             = (known after apply)
      + monitoring                           = (known after apply)
      + outpost_arn                          = (known after apply)
      + password_data                        = (known after apply)
      + placement_group                      = (known after apply)
      + placement_partition_number           = (known after apply)
      + primary_network_interface_id         = (known after apply)
      + private_dns                          = (known after apply)
      + private_ip                           = (known after apply)
      + public_dns                           = (known after apply)
      + public_ip                            = (known after apply)
      + secondary_private_ips                = (known after apply)
      + security_groups                      = (known after apply)
      + source_dest_check                    = true
      + subnet_id                            = (known after apply)
      + tags_all                             = (known after apply)
      + tenancy                              = (known after apply)
      + user_data                            = "f3a477061291a9f4185c8a7832baefc49a3edd6a"
      + user_data_base64                     = (known after apply)
      + user_data_replace_on_change          = false
      + vpc_security_group_ids               = (known after apply)

      + capacity_reservation_specification {
          + capacity_reservation_preference = (known after apply)

          + capacity_reservation_target {
              + capacity_reservation_id = (known after apply)
            }
        }

      + ebs_block_device {
          + delete_on_termination = (known after apply)
          + device_name           = (known after apply)
          + encrypted             = (known after apply)
          + iops                  = (known after apply)
          + kms_key_id            = (known after apply)
          + snapshot_id           = (known after apply)
          + tags                  = (known after apply)
          + throughput            = (known after apply)
          + volume_id             = (known after apply)
          + volume_size           = (known after apply)
          + volume_type           = (known after apply)
        }

      + enclave_options {
          + enabled = (known after apply)
        }

      + ephemeral_block_device {
          + device_name  = (known after apply)
          + no_device    = (known after apply)
          + virtual_name = (known after apply)
        }

      + metadata_options {
          + http_endpoint               = (known after apply)
          + http_put_response_hop_limit = (known after apply)
          + http_tokens                 = (known after apply)
          + instance_metadata_tags      = (known after apply)
        }

      + network_interface {
          + delete_on_termination = (known after apply)
          + device_index          = (known after apply)
          + network_interface_id  = (known after apply)
        }

      + root_block_device {
          + delete_on_termination = (known after apply)
          + device_name           = (known after apply)
          + encrypted             = (known after apply)
          + iops                  = (known after apply)
          + kms_key_id            = (known after apply)
          + tags                  = (known after apply)
          + throughput            = (known after apply)
          + volume_id             = (known after apply)
          + volume_size           = (known after apply)
          + volume_type           = (known after apply)
        }
    }

  # aws_internet_gateway.sample_igw will be created
  + resource "aws_internet_gateway" "sample_igw" {
      + arn      = (known after apply)
      + id       = (known after apply)
      + owner_id = (known after apply)
      + tags_all = (known after apply)
      + vpc_id   = (known after apply)
    }

  # aws_route_table.sample_rtb will be created
  + resource "aws_route_table" "sample_rtb" {
      + arn              = (known after apply)
      + id               = (known after apply)
      + owner_id         = (known after apply)
      + propagating_vgws = (known after apply)
      + route            = [
          + {
              + carrier_gateway_id         = ""
              + cidr_block                 = "0.0.0.0/0"
              + destination_prefix_list_id = ""
              + egress_only_gateway_id     = ""
              + gateway_id                 = (known after apply)
              + instance_id                = ""
              + ipv6_cidr_block            = ""
              + local_gateway_id           = ""
              + nat_gateway_id             = ""
              + network_interface_id       = ""
              + transit_gateway_id         = ""
              + vpc_endpoint_id            = ""
              + vpc_peering_connection_id  = ""
            },
        ]
      + tags_all         = (known after apply)
      + vpc_id           = (known after apply)
    }

  # aws_route_table_association.sample_rt_assoc will be created
  + resource "aws_route_table_association" "sample_rt_assoc" {
      + id             = (known after apply)
      + route_table_id = (known after apply)
      + subnet_id      = (known after apply)
    }

  # aws_security_group.sample_sg will be created
  + resource "aws_security_group" "sample_sg" {
      + arn                    = (known after apply)
      + description            = "Managed by Terraform"
      + egress                 = [
          + {
              + cidr_blocks      = [
                  + "0.0.0.0/0",
                ]
              + description      = ""
              + from_port        = 0
              + ipv6_cidr_blocks = []
              + prefix_list_ids  = []
              + protocol         = "-1"
              + security_groups  = []
              + self             = false
              + to_port          = 0
            },
        ]
      + id                     = (known after apply)
      + ingress                = [
          + {
              + cidr_blocks      = [
                  + "0.0.0.0/0",
                ]
              + description      = ""
              + from_port        = 80
              + ipv6_cidr_blocks = []
              + prefix_list_ids  = []
              + protocol         = "tcp"
              + security_groups  = []
              + self             = false
              + to_port          = 80
            },
        ]
      + name                   = "sample-sg"
      + name_prefix            = (known after apply)
      + owner_id               = (known after apply)
      + revoke_rules_on_delete = false
      + tags_all               = (known after apply)
      + vpc_id                 = (known after apply)
    }

  # aws_subnet.sample_subnet will be created
  + resource "aws_subnet" "sample_subnet" {
      + arn                                            = (known after apply)
      + assign_ipv6_address_on_creation                = false
      + availability_zone                              = "ap-northeast-1a"
      + availability_zone_id                           = (known after apply)
      + cidr_block                                     = "10.0.1.0/24"
      + enable_dns64                                   = false
      + enable_resource_name_dns_a_record_on_launch    = false
      + enable_resource_name_dns_aaaa_record_on_launch = false
      + id                                             = (known after apply)
      + ipv6_cidr_block_association_id                 = (known after apply)
      + ipv6_native                                    = false
      + map_public_ip_on_launch                        = true
      + owner_id                                       = (known after apply)
      + private_dns_hostname_type_on_launch            = (known after apply)
      + tags_all                                       = (known after apply)
      + vpc_id                                         = (known after apply)
    }

  # aws_vpc.sample_vpc will be created
  + resource "aws_vpc" "sample_vpc" {
      + arn                                  = (known after apply)
      + cidr_block                           = "10.0.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                 = true
      + enable_dns_support                   = true
      + id                                   = (known after apply)
      + instance_tenancy                     = "default"
      + ipv6_association_id                  = (known after apply)
      + ipv6_cidr_block                      = (known after apply)
      + ipv6_cidr_block_network_border_group = (known after apply)
      + main_route_table_id                  = (known after apply)
      + owner_id                             = (known after apply)
      + tags_all                             = (known after apply)
    }

Plan: 7 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.sample_vpc: Creating...
aws_vpc.sample_vpc: Still creating... [10s elapsed]
aws_vpc.sample_vpc: Creation complete after 12s [id=vpc-0f3ab7be56c0f3375]
aws_internet_gateway.sample_igw: Creating...
aws_subnet.sample_subnet: Creating...
aws_security_group.sample_sg: Creating...
aws_internet_gateway.sample_igw: Creation complete after 0s [id=igw-09ac5cd48b6038f53]
aws_route_table.sample_rtb: Creating...
aws_route_table.sample_rtb: Creation complete after 1s [id=rtb-02fb72b61515f9787]
aws_security_group.sample_sg: Creation complete after 3s [id=sg-02bc40a7196016ce4]
aws_subnet.sample_subnet: Still creating... [10s elapsed]
aws_subnet.sample_subnet: Creation complete after 11s [id=subnet-01976a2bc5bd39876]
aws_route_table_association.sample_rt_assoc: Creating...
aws_instance.sample_web_server: Creating...
aws_route_table_association.sample_rt_assoc: Creation complete after 0s [id=rtbassoc-041ebdbca22795470]
╷
│ Error: Error launching source instance: InvalidParameterValue: The architecture 'i386,x86_64' of the specified instance type does not match the architecture 'arm64' of the specified AMI. Specify an instance type and an AMI that have matching architectures, and try again. You can use 'describe-instance-types' or 'describe-images' to discover the architecture of the instance type or AMI.
│       status code: 400, request id: a33a74a9-f764-453f-9363-19f574f9bb50
│
│   with aws_instance.sample_web_server,
│   on aws_ec2.tf line 4, in resource "aws_instance" "sample_web_server":
│    4: resource "aws_instance" "sample_web_server" {
│
╵

Amazon Linux 2 AMI (HVM) - Kernel 5.10, SSD Volume Type
ami-0ab0bbbd329f565e6 (64 ビット (x86)) / ami-0fc6e8f1041d0a223 (64 ビット (Arm))

image

Armを選択していたので、AMIをx86の方に変更したら成功した。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
$ terraform apply
(略)
Plan: 7 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.sample_vpc: Creating...
aws_vpc.sample_vpc: Still creating... [10s elapsed]
aws_vpc.sample_vpc: Creation complete after 14s [id=vpc-0b958c856ef533c93]
aws_internet_gateway.sample_igw: Creating...
aws_subnet.sample_subnet: Creating...
aws_security_group.sample_sg: Creating...
aws_internet_gateway.sample_igw: Creation complete after 1s [id=igw-0bae810cd40dec166]
aws_route_table.sample_rtb: Creating...
aws_route_table.sample_rtb: Creation complete after 2s [id=rtb-0bb36b4e7a6aaca81]
aws_security_group.sample_sg: Creation complete after 4s [id=sg-090f6cc3a960ccdf1]
aws_subnet.sample_subnet: Still creating... [10s elapsed]
aws_subnet.sample_subnet: Creation complete after 12s [id=subnet-0e4c45dac4cd481af]
aws_route_table_association.sample_rt_assoc: Creating...
aws_instance.sample_web_server: Creating...
aws_route_table_association.sample_rt_assoc: Creation complete after 1s [id=rtbassoc-0bd7decb4d78ec862]
aws_instance.sample_web_server: Still creating... [10s elapsed]
aws_instance.sample_web_server: Still creating... [20s elapsed]
aws_instance.sample_web_server: Still creating... [30s elapsed]
aws_instance.sample_web_server: Creation complete after 34s [id=i-0da4b5254362e525a]

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

デプロイできたので、パブリックIPからアクセスできた!
image

terraform applyによって作成されたリソースは、terraform.tfstateに記録される。で、それとの差分がterraform plan時に出る。なので、terraform.tfstateを削除してしまうと制御を外れてしまう。
(今回、applyしたままtfstateを削除してしまったので、リソースはAWSコンソールで手動で削除した)

ちなみに、実際に既存のAWS構成をTerraformで管理するのは以下の手順らしい。なので、terraform.tfstateはその基準になる。
既存のAWS環境を後からTerraformでコード化する | DevelopersIO

Terraform Cloud に登録してみた

案内されるがままに、Getting Started | Terraform Cloudをやってみた。
前述のやり方だと、ローカルでしかコードを把握できないので、複数人で作業しているときはリアルタイムで状態を把握できない。
Terraform Cloudはapplyされたタイミングで反映されるので、実際の状態がわかる。
5人まで無料! Terraform Cloudを使ってみた | DevelopersIO

image

このときに作成されるのは、Terraform Cloudでのみ動作するモックのようなものなので、実際にAWSなどで作成されているわけではない。
hashicorp / terraform-provider-fakewebservices

Share on

END
END
@aiandrox

目次