はじめに
テスト目的でTerraformとAzure Blob Storageで静的Webサイトをホストすることがあったので備忘録的に残します。
Webサイトをホストする必要がなくシンプルにAzure Blob Storage作成したい場合は下記の記事をご参照ください。
とりあえずTerraformでAzure Blob Storageをつくってみる
方法
1. まず適当なhtmlファイルを用意します。
# サンプル
<!DOCTYPE html>
<html>
<head>
<title>Hello, World!</title>
</head>
<body>
<h1>Hello, Wold!</h1>
</body>
</html>
ファイル名をindex.htmlとして保存してください。
2. 次にTerraformのファイルを以下の内容で作成します。
resource "random_integer" "test" {
min = 1
max = 100
}
resource "random_pet" "test" {
length = 1
separator = ""
}
resource "azurerm_resource_group" "test" {
name = "blobstorage-test-rg"
location = "japaneast"
}
resource "azurerm_storage_account" "test" {
name = "${random_pet.test.id}${random_integer.test.result}"
resource_group_name = azurerm_resource_group.test.name
location = azurerm_resource_group.test.location
account_tier = "Standard"
account_kind = "StorageV2"
account_replication_type = "LRS"
static_website {
index_document = "index.html"
}
}
resource "azurerm_storage_blob" "test" {
name = "index.html"
storage_account_name = azurerm_storage_account.test.name
storage_container_name = "$web"
type = "Block"
content_type = "text/html"
source = "./index.html"
}
ファイル名をmain.tfなどにして保存してください。
どのように静的Webサイトを構築しているのか具体的に説明すると、
azurerm_storage_account内のstatic_websiteでストレージアカウントの静的webサイトの機能を有効化して、
index.htmlをインデックスドキュメントとして指定しています。
azurerm_storage_blobではストレージアカウントの$webコンテナにindex.htmlをアップロードしています。
$webコンテナは静的Webサイトをホスティングする際の特別なコンテナです。
これらの記述をすることで静的Webサイトを構築することが可能です。
あとは、terraformのコマンドでリソースの作成を行なってください。
terraform init terraform plan -out main.tfplan terraform apply main.tfplan
Blob Storage作成後にURLにアクセスしたい場合は、以下の記述をTerraformのコードに追加してください。
output "website_url" {
value = azurerm_storage_account.test.primary_web_endpoint
}
必要であれば、Github上にコード全体を載せるのでぜひ参考にしてください。
https://github.com/tkhs1121/terraform-azure-sample/tree/master/blobstorage-website
さいごに
誰かの参考になれば幸いです。