LoginSignup
11
3

More than 1 year has passed since last update.

【Terraform】よく使用するコマンドについて書きます。

Last updated at Posted at 2022-05-05

はじめに

Terraformでよく使用する基本コマンドについてアウトプットをしたいと思います。

以下の記事にてMac環境でのTerraformセットアップ手順も記載しているため、併せてご覧頂ければと思います。

Terraformとは?

file_type_terraform_icon_130125.png

HashiCorp社が提供する構成管理ツールになります。
クラウド上のリソース作成・変更を自動化できるツール(Infrastructure as Code)になります。

よく使用するコマンド

  • 初期化
  • フォーマット
  • 実行計画の確認
  • 変更の適用
  • リソースの削除
  • リソースの状態確認

初期化

Terraformの作業ディレクトリを初期化するために使用するコマンドになります。
Terraformを実行する際に一番最初に実行します。

コマンド
terraform init
実行例
satsuton:EC2_Create ma-sato$ terraform init

Initializing the backend...

Initializing provider plugins...
- Finding hashicorp/aws versions matching "> 3.0.0"...
- Installing hashicorp/aws v4.12.1...
- Installed hashicorp/aws v4.12.1 (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.
satsuton:EC2_Create ma-sato$ 

フォーマット

terraformのコードのフォーマットを整えるコマンドになります。

コマンド
terraform fmt
実行例
satsuton:EC2_Create ma-sato$ terraform fmt
main.tf
satsuton:EC2_Create ma-sato$ 

実行計画の確認

現状のソースコードをもとに実行計画を確認するコマンドになります。
コードをterraform applyする前の事前確認で使用します。

コマンド
terraform plan
実行例
satsuton:EC2_Create ma-sato$ terraform plan

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.server will be created
  + resource "aws_instance" "server" {
      + ami                                  = "ami-02c3627b04781eada"
      + arn                                  = (known after apply)
      + associate_public_ip_address          = true
      + 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"
〜〜〜〜長いため省略〜〜〜〜
      + main_route_table_id                  = (known after apply)
      + owner_id                             = (known after apply)
      + tags                                 = {
          + "Env"     = "dev"
          + "Name"    = "Test-dev-vpc"
          + "Project" = "Test"
        }
      + tags_all                             = {
          + "Env"     = "dev"
          + "Name"    = "Test-dev-vpc"
          + "Project" = "Test"
        }
    }

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

Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform apply" now.
satsuton:EC2_Create ma-sato$ 

変更の適用

現状のソースコードに従って変更を適用するコマンドになります。

コマンド
terraform apply
実行例
satsuton:EC2_Create ma-sato$ 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.server will be created
  + resource "aws_instance" "server" {
      + ami                                  = "ami-02c3627b04781eada"
      + arn                                  = (known after apply)
      + associate_public_ip_address          = true
      + availability_zone                    = (known after apply)
      + cpu_core_count                       = (known after apply)
〜〜〜長いので省略〜〜〜
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_route.public_rt_igw_r: Creation complete after 0s [id=r-rtb-0b8e5cc75b96605211080289494]
aws_security_group.opmng_sg: Creation complete after 2s [id=sg-05977eae8905e2de6]
aws_security_group_rule.opmng_in_ssh: Creating...
aws_security_group_rule.opmng_in_ssh: Creation complete after 1s [id=sgrule-3046359132]
aws_subnet.public_subnet: Still creating... [10s elapsed]
aws_subnet.public_subnet: Creation complete after 11s [id=subnet-0fe22cf846150399d]
aws_route_table_association.public_rt_1a: Creating...
aws_instance.server: Creating...
aws_route_table_association.public_rt_1a: Creation complete after 1s [id=rtbassoc-06d4deb245e69daf9]
aws_instance.server: Still creating... [10s elapsed]
aws_instance.server: Still creating... [20s elapsed]
aws_instance.server: Still creating... [30s elapsed]
aws_instance.server: Creation complete after 32s [id=i-07aafe6f29ee808ca]

Apply complete! Resources: 10 added, 0 changed, 0 destroyed.
satsuton:EC2_Create ma-sato$ 

オプションに-auto-approveを付与した場合、強制的にYesで進めることが可能です。

コマンド
terraform apply -auto-approve

リソースの削除

terraformで管理しているリソースを削除する際に利用するコマンドになります。

コマンド
terraform destroy
実行例
satsuton:EC2_Create ma-sato$ terraform destroy
aws_vpc.vpc: Refreshing state... [id=vpc-046903fc5cd5883ff]
aws_key_pair.keypair: Refreshing state... [id=Test-dev-keypeir]
aws_internet_gateway.igw: Refreshing state... [id=igw-02d0932dea1636f58]
aws_subnet.public_subnet: Refreshing state... [id=subnet-0f68dc0d33de46ee2]
aws_security_group.opmng_sg: Refreshing state... [id=sg-0f6d6d027d317871d]
aws_route_table.public_rt: Refreshing state... [id=rtb-06f54a5eee901f156]
aws_route_table_association.public_rt_1a: Refreshing state... [id=rtbassoc-012b28476c8a667f6]
aws_route.public_rt_igw_r: Refreshing state... [id=r-rtb-06f54a5eee901f1561080289494]
aws_security_group_rule.opmng_in_ssh: Refreshing state... [id=sgrule-4054515482]
aws_instance.server: Refreshing state... [id=i-018d7d758c615b5f7]
〜〜〜長いので省略〜〜〜
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_key_pair.keypair: Destroying... [id=Test-dev-keypeir]
aws_subnet.public_subnet: Destroying... [id=subnet-0f68dc0d33de46ee2]
aws_security_group.opmng_sg: Destroying... [id=sg-0f6d6d027d317871d]
aws_key_pair.keypair: Destruction complete after 0s
aws_security_group.opmng_sg: Destruction complete after 0s
aws_subnet.public_subnet: Destruction complete after 0s
aws_vpc.vpc: Destroying... [id=vpc-046903fc5cd5883ff]
aws_vpc.vpc: Destruction complete after 1s

Destroy complete! Resources: 10 destroyed.
satsuton:EC2_Create ma-sato$ 

オプションに-auto-approveを付与した場合、強制的にYesで進めることが可能です。

コマンド
terraform destroy -auto-approve

リソースの状態確認

terraform.stateファイルを元に現在のリソースの状態を参照するコマンドになります。

コマンド
terraform show

terraform.stateとは、管理対象のリソースの構成に関する状態を記録したファイルになります。

実行例
satsuton:EC2_Create ma-sato$ terraform show
# aws_instance.server:
resource "aws_instance" "server" {
    ami                                  = "ami-02c3627b04781eada"
    arn                                  = "arn:aws:ec2:ap-northeast-1:555246305565:instance/i-006b8fa6653595f1f"
    associate_public_ip_address          = true
    availability_zone                    = "ap-northeast-1a"
    cpu_core_count                       = 1
    cpu_threads_per_core                 = 1
    disable_api_termination              = false
    ebs_optimized                        = false
    get_password_data                    = false
    hibernation                          = false
    id                                   = "i-006b8fa6653595f1f"
〜〜〜長いので省略〜〜〜
    tags                             = {
        "Env"     = "dev"
        "Name"    = "Test-dev-vpc"
        "Project" = "Test"
    }
    tags_all                         = {
        "Env"     = "dev"
        "Name"    = "Test-dev-vpc"
        "Project" = "Test"
    }
}
satsuton:EC2_Create ma-sato$ 

まとめ

今回紹介したコマンド一覧をまとめます。

コマンド 説明 備考
terraform init Terraformの作業ディレクトリの初期化 Terraformを実行する際に一番最初に実行
terraform fmt terraformのコードのフォーマットを整える -
terraform plan 現状のソースコードをもとに実行計画を確認する terraform applyの実行前に実行
terraform validate 構成ファイルの記述が全て正常であることを確認 terraform applyの実行前に実行
terraform apply 現状のソースコードに従って変更を適用 以下のコマンドにて強制的にYesで実行可能
terraform apply -auto-approve
terraform destroy terraformで管理されているリソースを削除 以下のコマンドにて強制的にYesで実行可能
terraform destroy -auto-approve
terraform show terraform.stateファイルを元に現在のリソースの状態を参照する リソースに変更を加えた際等に確認のために実行

さいごに

使用しているコードはこちらになります。
※README作成中。コードも変更予定(そのまま実行できるようにすることが目標)

参考記事

5分で分かるTerraform(Infrastructure as Code)
Terraform 初心者の超簡単まとめ

11
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
3