1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

TerraformでAzure Virtual Machineのブートストラップする方法

Last updated at Posted at 2023-03-23

はじめに

TerraformでAzure VMのブートストラップする方法を備忘録として残します。
自分が確認した限りでは3通り方法があったのでそのやり方について記載します。

VMのUser Dataで設定する

azurerm_linux_virtual_machineuser_dataに設定する。

VirtualMachine.tf
resource "azurerm_linux_virtual_machine" "test" {
  name                = "test-machine"
  resource_group_name = azurerm_resource_group.test.name
  location            = azurerm_resource_group.test.location
  size                = "Standard_B1ls"

  # SSHキー設定省略

  os_disk {
    caching              = "ReadWrite"
    storage_account_type = "Standard_LRS"
  }

  ## Ubuntu 22.04
  source_image_reference {
    publisher = "Canonical"
    offer     = "0001-com-ubuntu-server-jammy"
    sku       = "22_04-lts-gen2"
    version   = "latest"
  }
  # ここで設定する
  # file関数で読み込み、base64でエンコードする必要がある
  user_data = base64encode(file("init.sh"))
}
init.sh
#! /bin/bash
sudo apt-get update
sudo apt-get install -y nginx

Terraform内で変数宣言して格納することも可能です。

VMのremote-exec Provisionerを設定する

VirtualMachine.tf
resource "azurerm_linux_virtual_machine" "test" {
  name                = "test-machine"
  resource_group_name = azurerm_resource_group.test.name
  location            = azurerm_resource_group.test.location
  size                = "Standard_B1ls"

  # SSHキー設定省略

  os_disk {
    caching              = "ReadWrite"
    storage_account_type = "Standard_LRS"
  }

  ## Ubuntu 22.04
  source_image_reference {
    publisher = "Canonical"
    offer     = "0001-com-ubuntu-server-jammy"
    sku       = "22_04-lts-gen2"
    version   = "latest"
  }

  # remote-execの接続設定
  connection {
    type     = "ssh"
    user     = "root"
    password = var.root_password
    host     = self.public_ip
  }

  # ここで設定する
  provisioner "remote-exec" {
    inline = [
      "apt update",
      "apt install -y nginx",
    ]
  }
}

カスタムスクリプトを設定する

azurerm_virtual_machine_extensionで設定する。

resource "azurerm_virtual_machine_extension" "test" {
  name                 = "test-vm-nginx"
  virtual_machine_id   = azurerm_linux_virtual_machine.test.id
  publisher            = "Microsoft.Azure.Extensions"
  type                 = "CustomScript"
  type_handler_version = "2.0"

  settings = <<INIT
  {
    "commandToExecute": "apt-get update && apt-get install -y nginx"
  }
INIT
}

以上です。

最後に

誰かの参考になれば嬉しいです!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?