3. 主なコマンドのご利用方法

3.1. 作業ディレクトリの作成

Terraformでは、基本的にカレントディレクトリのtfファイルを基にクラウドサービス等の環境を操作します。

そのため、Terraformを利用いただく際は、まず作業用のディレクトリを作成しそこにtfファイルを配置いただくこととなります。

% mkdir work
% cd work
% cat sample.tf
provider "ecl" {
  auth_url          = "https://keystone-[Region]-ecl.api.ntt.com/v3/"
  user_name         = "[API Key]"
  password          = "[API Secret Key]"
  tenant_id         = "[Tenant ID]"
  user_domain_id    = "default"
  project_domain_id = "default"
}

resource "ecl_compute_volume_v2" "volume_1" {
  name = "volume-1"
  size = 15
}

3.2. 主なコマンド

Terraform を使用する上での主要コマンドを以下に記載します。

3.2.1. terraform init

作業用ディレクトリを初期化します。

% terraform init

Initializing provider plugins...
- Reusing previous version of nttcom/ecl from the dependency lock file
- Installing nttcom/ecl v1.11.2...
- Installed nttcom/ecl v1.11.2 (signed by a HashiCorp partner, key ID ****************)

Partner and community providers are signed by their developers.
If you'd like to know more about provider signing, you can read about it here:
https://www.terraform.io/docs/plugins/signing.html

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.

3.2.2. terraform apply

作業用ディレクトリのtfファイルを利用し、Smart Data Platform をはじめとした各種クラウドサービス等にリソースの作成を行います。

% 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:

  # ecl_compute_keypair_v2.kp_1 will be created
  + resource "ecl_compute_keypair_v2" "kp_1" {
      + fingerprint = (known after apply)
      + id          = (known after apply)
      + name:       = "keypair-1"
      + private_key = (known after apply)
      + public_key  = (known after apply)
      + region      = (known after apply)
    }

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

ecl_compute_keypair_v2.kp_1: Creating...
ecl_compute_keypair_v2.kp_1: Creation complete after *s [id=keypair-1]

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

本コマンドの実行により、作業用ディレクトリに terraform.tfstate というファイルが作成されています。

作成されたリソースの情報はこのファイルに保存されています。

なお、 terraform apply コマンドは同時に編集/削除のコマンドとしても動作します。

3.2.2.1. terraform applyによる作成済みリソースの編集

一度 terraform apply を実行後、作業用ディレクトリのresourceセクションを一部編集し、再度 terraform apply を実行した場合、 作成済みリソースに対する編集として動作します。

例えば以下の例では2回 terraform apply コマンドを実行していますが、

  1. 1回目の実行で、Smart Data Platform サーバーインスタンスサービスのボリュームを作成
  2. 2回目の実行で、作成済みボリュームのnameを変更

という操作が行われます。

% cat sample.tf

provider "ecl" {
  auth_url          = "https://keystone-[region]-ecl.api.ntt.com/v3/"
  user_name         = "[API鍵]"
  password          = "[API秘密鍵]"
  tenant_id         = "[テナントID]"
  user_domain_id    = "default"
}

resource "ecl_compute_volume_v2" "volume_1" {
  name = "volume-1"
  size = 15
}

% terraform apply

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create <-- 初回のterraform applyなので作成扱いとなる

Terraform will perform the following actions:

  + ecl_compute_volume_v2.volume_1
      id:                <computed>
      attachment.#:      <computed>
      availability_zone: <computed>
      metadata.%:        <computed>
      name:              "volume-1"
      region:            <computed>
      size:              "15"
      volume_type:       <computed>


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

ecl_compute_volume_v2.volume_1: Creating...
  attachment.#:      "" => "<computed>"
  availability_zone: "" => "<computed>"
  metadata.%:        "" => "<computed>"
  name:              "" => "volume-1"
  region:            "" => "<computed>"
  size:              "" => "15"
  volume_type:       "" => "<computed>"
ecl_compute_volume_v2.volume_1: Still creating... (10s elapsed)
ecl_compute_volume_v2.volume_1: Creation complete after 11s (ID: b1f3517b-e585-4e56-b56f-c6f3bcda0a21)

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

一旦tfファイルを以下のように編集する

provider "ecl" {
  auth_url          = "https://keystone-[region]-ecl.api.ntt.com/v3/"
  user_name         = "[API鍵]"
  password          = "[API秘密鍵]"
  tenant_id         = "[テナントID]"
  user_domain_id    = "default"
}

resource "ecl_compute_volume_v2" "volume_1" {
  name = "volume-1-update" <-- nameを変更
  size = 15
}

% terraform apply
ecl_compute_volume_v2.volume_1: Refreshing state... (ID: b1f3517b-e585-4e56-b56f-c6f3bcda0a21)

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

Terraform will perform the following actions:

  ~ ecl_compute_volume_v2.volume_1
      name: "volume-1" => "volume-1-update" <-- 同じ terraform applyコマンドだが、差分が検出されnameの変更が行われる


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

ecl_compute_volume_v2.volume_1: Modifying... (ID: b1f3517b-e585-4e56-b56f-c6f3bcda0a21)
  name: "volume-1" => "volume-1-update"
ecl_compute_volume_v2.volume_1: Modifications complete after 1s (ID: b1f3517b-e585-4e56-b56f-c6f3bcda0a21)

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

3.2.2.2. terraform applyによる作成済みリソースの削除

一度 terraform apply を実行後、作業用ディレクトリのtfファイル内から、特定のresourceをセクションを削除し、再度 terraform apply を実行すると、 これは作成済みリソースに対する削除として動作します。

例えば以下の例では2回 terraform apply コマンドを実行していますが、

  1. 1回目の実行で、Smart Data Platform サーバーインスタンスサービスのボリュームを作成
  2. 2回目の実行で、作成済みのボリュームを削除

という操作が行われます。

% cat sample.tf

provider "ecl" {
  auth_url          = "https://keystone-[region]-ecl.api.ntt.com/v3/"
  user_name         = "[API鍵]"
  password          = "[API秘密鍵]"
  tenant_id         = "[テナントID]"
  user_domain_id    = "default"
}

resource "ecl_compute_volume_v2" "volume_1" {
  name = "volume-1"
  size = 15
}

% terraform apply

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create <-- 初回のterraform applyなので作成扱いとなる

Terraform will perform the following actions:

  + ecl_compute_volume_v2.volume_1
      id:                <computed>
      attachment.#:      <computed>
      availability_zone: <computed>
      metadata.%:        <computed>
      name:              "volume-1"
      region:            <computed>
      size:              "15"
      volume_type:       <computed>


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

ecl_compute_volume_v2.volume_1: Creating...
  attachment.#:      "" => "<computed>"
  availability_zone: "" => "<computed>"
  metadata.%:        "" => "<computed>"
  name:              "" => "volume-1"
  region:            "" => "<computed>"
  size:              "" => "15"
  volume_type:       "" => "<computed>"
ecl_compute_volume_v2.volume_1: Still creating... (10s elapsed)
ecl_compute_volume_v2.volume_1: Creation complete after 11s (ID: b1f3517b-e585-4e56-b56f-c6f3bcda0a21)

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

一旦tfファイルから、resourceブロック "ecl_compute_volume_v2" をすべて削除する。

provider "ecl" {
  auth_url          = "https://keystone-[region]-ecl.api.ntt.com/v3/"
  user_name         = "[API鍵]"
  password          = "[API秘密鍵]"
  tenant_id         = "[テナントID]"
  user_domain_id    = "default"
}

% terraform apply
ecl_compute_volume_v2.volume_1: Refreshing state... (ID: 4446aebf-1382-4bcc-a013-3d55e68e376e)

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:

  - ecl_compute_volume_v2.volume_1


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

ecl_compute_volume_v2.volume_1: Destroying... (ID: 4446aebf-1382-4bcc-a013-3d55e68e376e) <-- 同じ terraform applyコマンドだが、tfファイルから削除されたリソースがサービス上からも削除される
ecl_compute_volume_v2.volume_1: Still destroying... (ID: 4446aebf-1382-4bcc-a013-3d55e68e376e, 10s elapsed)
ecl_compute_volume_v2.volume_1: Destruction complete after 12s

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

3.2.3. terraform plan

実際のリソースは作成することなく、Terraformの実行計画だけを表示するコマンドとなります。

以下の例では、実行計画上1つのリソースが新規作成される旨が表示されますが、実際のリソース作成は行われません。

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:

  + ecl_compute_volume_v2.volume_1
      id:                <computed>
      attachment.#:      <computed>
      availability_zone: <computed>
      metadata.%:        <computed>
      name:              "volume-1"
      region:            <computed>
      size:              "15"
      volume_type:       <computed>


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.

3.2.4. terraform destroy

現在の作業ディレクトリにおいて情報を保有しているリソースをすべて削除します。 terraform apply コマンドによるリソース削除とは、以下の点が異なります。

  • terraform apply によりリソースを削除する場合、当該リソースに関するresourceセクションをtfファイルから削除しなくてはいけません
  • terraform destroy の場合、tfファイル上のresourceセクションを削除せずとも、現在の作業ディレクトリにおいてTerraform管轄下にあるリソースがすべて削除されます

以下の例では、Terraformにより作成したサーバーインスタンスサービスのボリュームが削除されています。

% terraform destroy

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:

  # ecl_compute_keypair_v2.kp_1 will be destroyed
  - resource "ecl_compute_keypair_v2" "kp_1" {
      - fingerprint = "*********" -> null
      - id          = "keypair-1" -> null
      - name        = "keypair-1" -> null
      - private_key = <<-EOT
            -----BEGIN RSA PRIVATE KEY-----
            *********************************************************************
            *********************************************************************
            *********************************************************************
            -----END RSA PRIVATE KEY-----
        EOT -> null
      - public_key  = "**************************" -> 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

ecl_compute_keypair_v2.kp_1: Destroying... [id=keypair-1]
ecl_compute_keypair_v2.kp_1: Destruction complete after *s

Destroy complete! Resources: 1 destroyed.

3.3. 作業用ディレクトリ、各種コマンドの関係性

以上の内容を図にしたのが以下となります。

  • terraform init で作業用ディレクトリを初期化します
  • terraform apply コマンドで作業用ディレクトリのtfファイルに従い、リソースの作成/編集/削除を行います
  • terraform destroy コマンドで作成されたリソースの削除が行われます
作業用ディレクトリ、各種コマンドの関係性

注釈

上記にてご紹介した以外にも、さまざまなコマンドがあります。
詳細は terraform コマンド(オプション無し)を実行いただくことで確認ができます。
% terraform
Usage: terraform [-version] [-help] <command> [args]

The available commands for execution are listed below.
The most common, useful commands are shown first, followed by
less common or more advanced commands. If you're just getting
started with Terraform, stick with the common commands. For the
other commands, please read the help and docs before usage.

Common commands:
    apply              Builds or changes infrastructure
    console            Interactive console for Terraform interpolations
    destroy            Destroy Terraform-managed infrastructure
    env                Workspace management
    fmt                Rewrites config files to canonical format
    get                Download and install modules for the configuration
    graph              Create a visual graph of Terraform resources
    import             Import existing infrastructure into Terraform
    init               Initialize a Terraform working directory
    output             Read an output from a state file
    plan               Generate and show an execution plan
    providers          Prints a tree of the providers used in the configuration
    push               Upload this Terraform module to Atlas to run
    refresh            Update local state file against real resources
    show               Inspect Terraform state or plan
    taint              Manually mark a resource for recreation
    untaint            Manually unmark a resource as tainted
    validate           Validates the Terraform files
    version            Prints the Terraform version
    workspace          Workspace management

All other commands:
    debug              Debug output management (experimental)
    force-unlock       Manually unlock the terraform state
    state              Advanced state management