LoginSignup
1
0

More than 1 year has passed since last update.

Terraformでストレージアカウント名に乱数をつける

Last updated at Posted at 2023-04-04

ストレージアカウントを作成していると、名前が競合することがよくあったので乱数をつかってアカウント名を自動で生成してくれる構成ファイルを作成してみました。

乱数を使わないケース

まずは乱数を使わない場合の構成ファイルを作成します。
構成ファイル内の<resource-group-name>は適当な名前に置き換えてください。

main.tf
terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "=3.50.0"
    }
    random = {
      source  = "hashicorp/random"
      version = "=3.4.3"
    }
  }
}

provider "azurerm" {
  features {}
}

resource "azurerm_resource_group" "rg" {
  name     = "<resource-group-name>"
  location = "Japan East"
}

resource "azurerm_storage_account" "st" {
  name                     = "storetest"
  resource_group_name      = azurerm_resource_group.rg.name
  location                 = azurerm_resource_group.rg.location
  account_tier             = "Standard"
  account_replication_type = "LRS"
}

乱数を使うケース

次にRandom Providerを使ってストレージアカウントの名前がランダムに決定されるように変更しました。

main.tf
terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "=3.50.0"
    }
    random = {
      source  = "hashicorp/random"
      version = "=3.4.3"
    }
  }
}

provider "azurerm" {
  features {}
}

resource "random_id" "account" {
  byte_length = 4
}

resource "azurerm_resource_group" "rg" {
  name     = "rg-akimasa-nishimura-2"
  location = "Japan East"
}

resource "azurerm_storage_account" "st" {
  name                     = "store${random_id.account.hex}"
  resource_group_name      = azurerm_resource_group.rg.name
  location                 = azurerm_resource_group.rg.location
  account_tier             = "Standard"
  account_replication_type = "LRS"
}
1
0
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
1
0