在Azure上通过Terraform设置一个可以让多人创建(修改)Azure资源的环境

Terraform 是一种用于构建、更改和版本控制基础设施资源的工具。配置代码使用 Terraform 配置文件(.tf 或 .tf.json 格式)来编写。

正如提到的提供者(Providers),Terraform 支持众多云服务,但在 Qiita 等地方,你可能经常看到关于 AWS 构建的文章。

undefined

这篇文章是关于使用Terraform在Azure上创建和修改资源(与多人共享状态文件)的步骤。

image.png

1) 安装 Azure CLI 和 Terraform

需要使用Azure CLI 2.0 (az命令)来执行。
按照安装Azure CLI的说明执行相应的命令进行安装。以下步骤是在Ubuntu 18.04上执行的。

※インストール実行※
$ which az
$ curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash
※出力は長いので省略※

※インストール結果の確認※
$ which az
/usr/bin/az
$ az --version
azure-cli                         2.0.68

command-modules-nspkg               2.0.3
core                              2.0.68
nspkg                              3.0.4
telemetry                          1.0.3

Python location '/opt/az/bin/python3'
Extensions directory '/home/azureuser/.azure/cliextensions'

Python (Linux) 3.6.5 (default, Jun 28 2019, 06:19:45)
[GCC 7.4.0]

Legal docs and information: aka.ms/AzureCliLegal


Your CLI is up-to-date.

只需下载和解压Terraform,然后将路径添加到单个文件即可。通过下载Terraform并确认最新版本的路径来指定。

※ダウンロード※
$ wget https://releases.hashicorp.com/terraform/0.12.3/terraform_0.12.3_linux_amd64.zip
--2019-07-05 06:15:42--  https://releases.hashicorp.com/terraform/0.12.3/terraform_0.12.3_linux_amd64.zip
Resolving releases.hashicorp.com (releases.hashicorp.com)... 151.101.77.183, 2a04:4e42:15::439
Connecting to releases.hashicorp.com (releases.hashicorp.com)|151.101.77.183|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 16036886 (15M) [application/zip]
Saving to: ‘terraform_0.12.3_linux_amd64.zip’

terraform_0.12.3_linux_amd64.zip      100%[=========================================================================>]  15.29M  23.3MB/s    in 0.7s

2019-07-05 06:15:43 (23.3 MB/s) - ‘terraform_0.12.3_linux_amd64.zip’ saved [16036886/16036886]

※解凍してパスを通す※
$ unzip terraform_0.12.3_linux_amd64.zip
Archive:  terraform_0.12.3_linux_amd64.zip
  inflating: terraform

$ sudo mkdir /opt/terraform0.12.3
$ sudo cp terraform /opt/terraform0.12.3
$ sudo ln -s /opt/terraform0.12.3/terraform /usr/local/bin/terraform

※確認※
$ which terraform
/usr/local/bin/terraform
$ terraform -v
Terraform v0.12.3

创建状态文件共享位置(存储账户和容器)

在Terraform中,我們使用一個名為「.tfstate」的文件來管理所管理基礎設施的狀態。如果這個狀態文件無法正確共享,可能會導致本意為變更的操作卻變成了創建同名資源的問題,所以需要注意。由於我們使用的是Azure,所以這次我們會在Blob儲存空間內創建一個共享用的容器。

image.png

3) 尝试创建或更改资源组。

创建第一个操作(创建资源组)。

请创建一个用于创建资源组的.tf文件。请根据执行环境自行调整状态文件设置部分。

# Azure Providerの設定
provider "azurerm" {
}

# ステートファイルの設定
terraform {
    backend "azurerm" {
        storage_account_name  = "<先ほど作成したストレージアカウント名>"
        container_name        = "<先ほど作成したコンテナ名>"
        key                   = "terraform.tfstate" # ステートファイル名
        resource_group_name  = "<先ほど作成したストレージアカウントのリソースグループ>"
    }
}

# 作成するリソースグループの設定
resource "azurerm_resource_group" "test_resource_group" {
    name     = "test_resource_group"
    location = "Japan East"
}

登录Azure CLI。如果有多个订阅,可以使用az account set命令设置所需的订阅。

※ログイン※
$ az login
To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code GZYxxxxxxx to authenticate.
※→ 表示されたURLをブラウザで表示し、表示されたコードを入力する※

※アカウント(サブスクリプション)一覧の確認※
$ az account list --output table
Name                             CloudName    SubscriptionId       State    IsDefault
-------------------------------  -----------  -------------------  -------  -----------
Azure_Dev                        AzureCloud   939cxxxxxxx-xxxxxxx  Enabled  True
Visual Studio Enterprise MPN     AzureCloud   0ce0xxxxxxx-xxxxxxx  Enabled  False
visionarts-demo-env              AzureCloud   65b7xxxxxxx-xxxxxxx  Enabled  False

※作業対象サブスクリプションの設定※
$ az account set --subscription "visionarts-demo-env"

※IsDefaultが設定されたことの確認※
$ az account list --output table
Name                             CloudName    SubscriptionId       State    IsDefault
-------------------------------  -----------  -------------------  -------  -----------
Azure_Dev                        AzureCloud   939cxxxxxxx-xxxxxxx  Enabled  False
Visual Studio Enterprise MPN     AzureCloud   0ce0xxxxxxx-xxxxxxx  Enabled  False
visionarts-demo-env              AzureCloud   65b7xxxxxxx-xxxxxxx  Enabled  True

在包含.tf文件的目录中执行terraform init。

$ terraform init

Initializing the backend...

Successfully configured the backend "azurerm"! Terraform will automatically
use this backend unless the backend configuration changes.

Initializing provider plugins...
- Checking for available provider plugins...
- Downloading plugin for provider "azurerm" (terraform-providers/azurerm) 1.31.0...

The following providers do not have any version constraints in configuration,
so the latest version was installed.

To prevent automatic upgrades to new major versions that may contain breaking
changes, it is recommended to add version = "..." constraints to the
corresponding provider blocks in configuration, with the constraint strings
suggested below.

* provider.azurerm: version = "~> 1.31"

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.

执行 terraform plan 命令,并确保显示创建了一个资源组(计划)。

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

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

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.

执行terraform apply命令(在要求确认时输入”yes”)

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

  # azurerm_resource_group.test_resource_group will be created
  + resource "azurerm_resource_group" "test_resource_group" {
      + id       = (known after apply)
      + location = "japaneast"
      + name     = "test_resource_group"
      + tags     = (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

azurerm_resource_group.test_resource_group: Creating...
azurerm_resource_group.test_resource_group: Creation complete after 2s [id=/subscriptions/65b7xxxxxxx-xxxxxxx/resourceGroups/test_resource_group]

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

确认资源组已成功创建。

image.png
image.png

更改第二个操作(资源组)。

接下来,是第二个任务。安装和登录及切换至目标订阅的步骤与第一个任务完全相同,需按照同样的步骤进行操作。

创建用于更改的.tf文件。差异在最后4行中,添加了标签。

# Azure Providerの設定
provider "azurerm" {
}

# ステートファイルの設定
terraform {
    backend "azurerm" {
        storage_account_name  = "<1台目で設定したのと同じストレージアカウント名>"
        container_name        = "<1台目で設定したのと同じコンテナ名>"
        key                   = "terraform.tfstate" # ステートファイル名
        resource_group_name  = "<1台目で設定したのと同じリソースグループ名>"
    }
}

# 作成するリソースグループの設定
resource "azurerm_resource_group" "test_resource_group" {
    name     = "test_resource_group"
    location = "Japan East"

    tags = {
        environment = "Demo"
    }
}

执行terraform init。

$ terraform init

Initializing the backend...

Successfully configured the backend "azurerm"! Terraform will automatically
use this backend unless the backend configuration changes.

Initializing provider plugins...
- Checking for available provider plugins...
- Downloading plugin for provider "azurerm" (terraform-providers/azurerm) 1.31.0...

The following providers do not have any version constraints in configuration,
so the latest version was installed.

To prevent automatic upgrades to new major versions that may contain breaking
changes, it is recommended to add version = "..." constraints to the
corresponding provider blocks in configuration, with the constraint strings
suggested below.

* provider.azurerm: version = "~> 1.31"

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.

请执行terraform plan命令,确保资源组将显示为1个变更(计划)。
如果这里显示了与第一台设备相同的新创建(计划),则说明状态文件的引用失败,请重新确认之前的步骤。

$ 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.

azurerm_resource_group.test_resource_group: Refreshing state... [id=/subscriptions/65b7xxxxxxx-xxxxxxx/resourceGroups/test_resource_group]

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

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:

  # azurerm_resource_group.test_resource_group will be updated in-place
  ~ resource "azurerm_resource_group" "test_resource_group" {
        id       = "/subscriptions/65b7xxxxxxx-xxxxxxx/resourceGroups/test_resource_group"
        location = "japaneast"
        name     = "test_resource_group"
      ~ tags     = {
          + "environment" = "Demo"
        }
    }

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

执行terraform apply(与第一台服务器一样,输入”yes”进行确认)

$ terraform apply
azurerm_resource_group.test_resource_group: Refreshing state... [id=/subscriptions/65b7xxxxxxx-xxxxxxx/resourceGroups/test_resource_group]

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:

  # azurerm_resource_group.test_resource_group will be updated in-place
  ~ resource "azurerm_resource_group" "test_resource_group" {
        id       = "/subscriptions/65b7xxxxxxx-xxxxxxx/resourceGroups/test_resource_group"
        location = "japaneast"
        name     = "test_resource_group"
      ~ tags     = {
          + "environment" = "Demo"
        }
    }

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

azurerm_resource_group.test_resource_group: Modifying... [id=/subscriptions/65b7xxxxxxx-xxxxxxx/resourceGroups/test_resource_group]
azurerm_resource_group.test_resource_group: Modifications complete after 3s [id=/subscriptions/65b7xxxxxxx-xxxxxxx/resourceGroups/test_resource_group]

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

确认资源组已添加标签。

image.png

另外,我们可以通过第二个操作确认状态文件已经更新。

image.png

通过以上步骤,我们确认了使用Terraform创建和更改Azure资源(多人共享状态文件)的功能。

请参考下列资料。

    • Introduction to Terraform

 

    • Download Terraform

 

    • Terraform: Azure Provider

 

    Azure CLI のインストール
广告
将在 10 秒后关闭
bannerAds