succi0303 blog

This is my personal blog. All posts are my own.

Ubuntu 24.04にTerraformをインストールしてTerraformでProxmox VEを操作する

Proxmox VEをTerraformで操作するために作業用のUbuntu 24.04環境を準備した。環境構築の手順を記録する。

Terraformのインストール

# aptパッケージを更新してパッケージを導入
sudo apt update && sudo apt upgarde -y
sudo apt install -y curl gnupg software-properties-common git jq

## Terraformをインストール
# https://developer.hashicorp.com/terraform/install
wget -O - https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(grep -oP '(?<=UBUNTU_CODENAME=).*' /etc/os-release || lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
sudo apt update && sudo apt install terraform

ProxmoxのAPIトークンを設定

ProxmoxのウェブコンソールでAPIトークンを作成し、ubuntu 24.04の.bashrcに以下を追記する。

export PM_API_TOKEN_SECRET="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

Proxmox操作用のプロジェクト作成

cd ~
mkdir -p terraform-proxmox
cd terraform-proxmox

test.tfファイルを作成して次のように編集する。

terraform {
  required_providers {
    proxmox = {
      source  = "bpg/proxmox"
      version = "0.70.0" 
    }
  }
}

provider "proxmox" {
  endpoint = "https://192.168.1.10:8006/" #接続先を設定
  insecure = true # 自己署名証明書の場合
}

data "proxmox_virtual_environment_nodes" "test_nodes" {}

output "proxmox_nodes" {
  value = data.proxmox_virtual_environment_nodes.test_nodes.names
}

Terraformをテスト実行する。

terraform init
terraform apply

次のように表示され、接続できたことを確認

data.proxmox_virtual_environment_nodes.test_nodes: Reading...
data.proxmox_virtual_environment_nodes.test_nodes: Read complete after 0s [id=nodes]
Changes to Outputs:
+ proxmox_nodes = [
+ "pve",
]
You can apply this plan to save these new output values to the
Terraform state, without changing any real infrastructure.

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
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Outputs:
proxmox_nodes = tolist([
"pve",
])

後片付けをする。

terraform destroy
rm test.tf terraform.tfstate*

作業用端末からTerraformでProxmox VEの設定を実行できるようになった。