Terraform で Azure 環境作成ことはじめ

Azure 環境で Terraform を始めたいと思い、検証しました。

基本的な動きはこちら

docs.microsoft.com

と同じです。
同じような内容をあえてブログに書く理由はただ一つ、自分への備忘録です。
ドキュメント最高、ありがとうございます。

Azure で使うには

https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs

ここに詳しく記載されていますが、Azure 使うよ!ということを明記する必要があります。

Features and Bug Requests

そうそう、ここにこうやって記載があるのは良いですね。 その features のところに何を書くかというと、

It's possible to configure the behaviour of certain resources using the features block - more details can be found below.
機能ブロックを使って、特定のリソースの動作を設定することができます。詳細は以下の通りです。

ということが書いてあります。 例えば virtual_machine の場合、仮想マシンが破棄されたときにリソースは仮想マシンに接続されているOSディスクを削除されますが、false にすると削除されます。 デフォルトは true で、仮想マシンを破棄する際に一緒に削除される動作になります。

Azure にログインする

まずはここから始めないといけないところとして、Azure 環境と接続します。
Azure にログインし、自分のアカウント情報を確認します。

$ az account show
{
  "environmentName": "AzureCloud",
  "homeTenantId": "XXXXXXXXXXXXXXXXXXXXX",
  "id": "XXXXXXXXXXXXXXXXXXXXX",
  "isDefault": true,
  "managedByTenants": [],
  "name": "mihoサブスクリプション",
  "state": "Enabled",
  "tenantId": "XXXXXXXXXXXXXXXXXXXXX",
  "user": {
    "name": "miho@mail",
    "type": "user"
  }
}

まだ環境と接続していない場合はログインします。

$ az login

最初の Terraform 構成ファイルを作成する

まずは、Azure に Resource Group を設定する構成ファイルを作成します。

Location は今回東日本を指定します。

https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/resource_group

beta.tf という名前で構成ファイルを作成します。
terraform 区分と provide で、Azure 環境を指定します。その後、resource 区分では、作成する ResorceGroup を記載します。名前を sample-rg にしました。
rg と記載している部分は、ResouceGroup を参照する時の変数名です。

# Azure provider source and version Setting
terraform {
    required_providers {
        azurerm = {
            source = "hashicorp/azurerm"
            version = "~>2.0"
        }
    }
}
# Azure provider
provider "azurerm" {
    features {}
}

# Create Resource Group
resource "azurerm_resource_group" "rg" {
    name = "sample-rg"
    location = "Japan East"
}

作成したのち、初期化を行います。

$ terraform init

Initializing the backend...

Initializing provider plugins...
- Finding hashicorp/azurerm versions matching "~> 2.0"...
- Installing hashicorp/azurerm v2.68.0...
- Installed hashicorp/azurerm v2.68.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 回目は失敗しました。 まずは成功例から。

$ terraform plan -out beta.tfplan

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:

  # azurerm_resource_group.rg will be created
  + resource "azurerm_resource_group" "rg" {
      + id       = (known after apply)
      + location = "japaneast"
      + name     = "sample-rg"
    }

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

───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

Saved the plan to: beta.tfplan

To perform exactly these actions, run the following command to apply:
    terraform apply "beta.tfplan"

で、こちらが失敗例です。
location を "East Japan" と書くと失敗しました。他の ResouceGroup は 方角から記載が始まりますが、一部地域は地名から始まるんですね、不思議。
利用するときは、ロケーションの名前をちゃんと調べてから書きましょう。

$ terraform plan -out beta.tfplan
╷
│ Error: "eastjapan" was not found in the list of supported Azure Locations: "westus,westus2,eastus,centralus,centraluseuap,southcentralus,northcentralus,westcentralus,eastus2,eastus2euap,brazilsouth,brazilus,northeurope,westeurope,eastasia,southeastasia,japanwest,japaneast,koreacentral,koreasouth,southindia,westindia,centralindia,australiaeast,australiasoutheast,canadacentral,canadaeast,uksouth,ukwest,francecentral,francesouth,australiacentral,australiacentral2,uaecentral,uaenorth,southafricanorth,southafricawest,switzerlandnorth,switzerlandwest,germanynorth,germanywestcentral,norwayeast,norwaywest,brazilsoutheast,westus3,eastusslv,swedencentral,swedensouth"
│
│   with azurerm_resource_group.rg,
│   on beta.tf line 18, in resource "azurerm_resource_group" "rg":
│   18:     location = "East Japan"
│

さて、成功と出たので実行します。

$ terraform apply beta.tfplan
azurerm_resource_group.rg: Creating...
azurerm_resource_group.rg: Creation complete after 0s [id=/subscriptions/XXXXXXXXXXXXXXXXXX/resourceGroups/sample-rg]

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

作成されたのがわかります。

$ az group list --query "[?location=='japaneast']
"
[
  {
    "id": "/subscriptions/XXXXXXXXXXXXXXXXXX/resourceGroups/sample-rg",
    "location": "japaneast",
    "managedBy": null,
    "name": "sample-rg",
    "properties": {
      "provisioningState": "Succeeded"
    },
    "tags": {},
    "type": "Microsoft.Resources/resourceGroups"
  }
]

環境を削除(元に戻す

環境を削除します。Plan の指定で "-destroy" を記載して、アウトプットするファイルも名前を別名で作成されるようにします。

$ terraform plan -destroy -out beta.destroy.tfplan
azurerm_resource_group.rg: Refreshing state... [id=/subscriptions/XXXXXXXXXXXXXXXXXX/resourceGroups/sample-rg]

Note: Objects have changed outside of Terraform

Terraform detected the following changes made outside of Terraform since the last "terraform apply":

  # azurerm_resource_group.rg has been changed
  ~ resource "azurerm_resource_group" "rg" {
        id       = "/subscriptions/XXXXXXXXXXXXXXXXXX/resourceGroups/sample-rg"
        name     = "sample-rg"
      + tags     = {}
        # (1 unchanged attribute hidden)
    }

Unless you have made equivalent changes to your configuration, or ignored the relevant attributes using ignore_changes,
the following plan may include actions to undo or respond to these changes.

───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

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

Terraform will perform the following actions:

  # azurerm_resource_group.rg will be destroyed
  - resource "azurerm_resource_group" "rg" {
      - id       = "/subscriptions/XXXXXXXXXXXXXXXXXX/resourceGroups/sample-rg" -> null
      - location = "japaneast" -> null
      - name     = "sample-rg" -> null
      - tags     = {} -> null
    }

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

───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

Saved the plan to: beta.destroy.tfplan

To perform exactly these actions, run the following command to apply:
    terraform apply "beta.destroy.tfplan"

プランが作成されたので、適用します。

$ terraform apply beta.destroy.tfplan
XXXXXXXXXXXXXXXXXX

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

Azure コマンドを使って環境が削除されたことを確認します。

$ az group list --query "[?location=='japaneast']"
[]

これで、Azure 環境での動作が検証できました。