淡々と備忘録を綴る

IT周りの行き詰まったところやメモを備忘録として記録します

TerraformでProxmoxのLXCコンテナを建ててみた

概要

最近自宅ラボの構成が大きくなってきたので、管理の煩雑さを回避するための技術を導入し始めている。

そのための一策として、みながすなるIaCといふものを我もしてみむとすなり。ということでterraformを導入した。

その時の作業や設定を備忘録として残す。

やったこと

  • terraformのインストール
  • 環境変数への登録
  • tfファイルの作成
  • 実行

terraformのインストール~初期設定

以下のインストールコマンドを実行する。

Dockerのように、GPGキーを追加してリポジトリに追加する必要がある。

curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo apt-key add -
sudo apt-add-repository "deb [arch=amd64] https://apt.releases.hashicorp.com $(lsb_release -cs) main"
sudo apt update
sudo apt install terraform

次に、今回使用するAPItokenを環境変数に登録する。

どうせIaCで管理するなら構成ファイルをGithubで管理しようとしているので、secret情報だけは別で管理する必要がある。

今回は一旦実行環境の構成ファイルに仕込むことにした。

export PM_API_TOKEN_ID='YOUR-ID@pam!YOUR-TOKEN-ID’
export PM_API_TOKEN_SECRET="YOUR-SECRET-TOKEN-ID"

ここで、proxmoxのTOKENIDには!が使用されるのだが、シェルの仕様上!は予約文字であり、ヒストリを表す。

よって''で囲まずに""で囲むとエスケープされずに直前に打ち込んだコマンドに変換されてしまう。気をつけよう。(一敗)

tfファイルの作成~実行

terraformの構成ファイルとして、main.tfを以下で作成した。

terraform {
  required_providers {
    proxmox = {
      source = "Telmate/proxmox"
      version = "2.9.11"
    }
  }
}

provider "proxmox" {
  pm_api_url = "https://10.1.1.118:8006/api2/json"
  # pm_api_token_id = "{トークンID}"
  # pm_api_token_secret = "{シークレット}"
  # 環境変数に格納するためコメントアウト
}

resource "proxmox_lxc" "basic" {
  target_node  = "sv-proxmox"
  hostname     = "cnt-tst-terraform-dev-prxmx-01"
  ostemplate   = "local:vztmpl/ubuntu-22.04-standard_22.04-1_amd64.tar.zst"
  password     = "terraform"
  unprivileged = true

  rootfs {
    storage = "local-lvm"
    size    = "8G"
  }

  network {
    name   = "eth0"
    bridge = "vmbr0"
    ip     = "dhcp"
  }
}

tfファイルができたらterraform initterraform applyを実行する。

terraformの基本的なコマンドの使い分けは以下の通り。

コマンド 説明
terraform init Terraform構成の初期化を実施する。モジュール等をDLしている。使用しているプロバイダーが増えた場合もこのコマンドを実行する必要がある。
terraform plan 実行された場合にTerraformが行う予定の変更を表示する。確認のためのコマンドなので、インフラへの実行はされない。
terraform apply 構成ファイルに基づいて実際にインフラを変更する。

実行した結果は以下。

zaki@DESKTOP-9SJJCLK:~/homelab/proxmox/lxc$ terraform init

Initializing the backend...

Initializing provider plugins...
- Finding telmate/proxmox versions matching "2.9.11"...
- Installing telmate/proxmox v2.9.11...
- Installed telmate/proxmox v2.9.11 (self-signed, key ID A9EBBE091B35AFCE)

Partner and community providers are signed by their developers.
If you'd like to know more about provider signing, you can read about it here:
https://www.terraform.io/docs/cli/plugins/signing.html

Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.

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.
zaki@DESKTOP-9SJJCLK:~/homelab/proxmox/lxc$ ll
total 20
drwxr-xr-x 3 zaki zaki 4096 Apr  5 00:14 ./
drwxr-xr-x 3 zaki zaki 4096 Apr  5 00:03 ../
drwxr-xr-x 3 zaki zaki 4096 Apr  5 00:13 .terraform/
-rw-r--r-- 1 zaki zaki 1333 Apr  5 00:14 .terraform.lock.hcl
-rw-r--r-- 1 zaki zaki  391 Apr  5 00:08 main.tf
zaki@DESKTOP-9SJJCLK:~/homelab/proxmox/lxc$ terraform plan

No changes. Your infrastructure matches the configuration.

Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed.
zaki@DESKTOP-9SJJCLK:~/homelab/proxmox/lxc$ terraform plan

Planning failed. Terraform encountered an error while generating this plan.

╷
│ Error: your API TokenID username should contain a !, check your API credentials
│ 
│   with provider["registry.terraform.io/telmate/proxmox"],
│   on main.tf line 10, in provider "proxmox":
│   10: provider "proxmox" {
│ 
╵
zaki@DESKTOP-9SJJCLK:~/homelab/proxmox/lxc$ export PM_API_TOKEN_ID="root@pam!terraform"
export PM_API_TOKEN_ID="root@pamterraform plan"
zaki@DESKTOP-9SJJCLK:~/homelab/proxmox/lxc$ export PM_API_TOKEN_ID="root@pam!terraform"
export PM_API_TOKEN_ID="root@pamterraform plan"
zaki@DESKTOP-9SJJCLK:~/homelab/proxmox/lxc$ export PM_API_TOKEN_ID='root@pam!terraform'
zaki@DESKTOP-9SJJCLK:~/homelab/proxmox/lxc$ terraform plan

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # proxmox_lxc.basic will be created
  + resource "proxmox_lxc" "basic" {
      + arch         = "amd64"
      + cmode        = "tty"
      + console      = true
      + cores        = 1
      + cpulimit     = 0
      + cpuunits     = 1024
      + hostname     = "cnt-tst-terraform-dev-prxmx-01"
      + id           = (known after apply)
      + memory       = 512
      + onboot       = false
      + ostemplate   = "local:vztmpl/ubuntu-22.04-standard_22.04-1_amd64.tar.zst"
      + ostype       = (known after apply)
      + password     = (sensitive value)
      + protection   = false
      + start        = false
      + swap         = 0
      + target_node  = "sv-proxmox"
      + tty          = 2
      + unprivileged = true
      + unused       = (known after apply)
      + vmid         = (known after apply)

      + network {
          + bridge = "vmbr0"
          + hwaddr = (known after apply)
          + ip     = "dhcp"
          + name   = "eth0"
          + tag    = (known after apply)
          + trunks = (known after apply)
          + type   = (known after apply)
        }

      + rootfs {
          + size    = "8G"
          + storage = "local-lvm"
          + volume  = (known after apply)
        }
    }

Plan: 1 to add, 0 to change, 0 to destroy.

───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform apply" now.

zaki@DESKTOP-9SJJCLK:~/homelab/proxmox/lxc$ terraform apply

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # proxmox_lxc.basic will be created
  + resource "proxmox_lxc" "basic" {
      + arch         = "amd64"
      + cmode        = "tty"
      + console      = true
      + cores        = 1
      + cpulimit     = 0
      + cpuunits     = 1024
      + hostname     = "cnt-tst-terraform-dev-prxmx-01"
      + id           = (known after apply)
      + memory       = 512
      + onboot       = false
      + ostemplate   = "local:vztmpl/ubuntu-22.04-standard_22.04-1_amd64.tar.zst"
      + ostype       = (known after apply)
      + password     = (sensitive value)
      + protection   = false
      + start        = false
      + swap         = 0
      + target_node  = "sv-proxmox"
      + tty          = 2
      + unprivileged = true
      + unused       = (known after apply)
      + vmid         = (known after apply)

      + network {
          + bridge = "vmbr0"
          + hwaddr = (known after apply)
          + ip     = "dhcp"
          + name   = "eth0"
          + tag    = (known after apply)
          + trunks = (known after apply)
          + type   = (known after apply)
        }

      + rootfs {
          + size    = "8G"
          + storage = "local-lvm"
          + volume  = (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

proxmox_lxc.basic: Creating...
proxmox_lxc.basic: Still creating... [10s elapsed]
proxmox_lxc.basic: Creation complete after 11s [id=sv-proxmox/lxc/106]

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

やり残したこと

  • terraformでインフラを構築したあと、公開鍵認証でログインできるようにしたい。
    • 建てるのがVMならproxmox provider内で設定できるが、LXCコンテナだとできない模様。
    • 同じくcloud-initの機能もVMにしか対応してなさそう。
    • コンテナが建った後にansibleを動かすことも考えたが、DHCPでIPをふりたいので、ansibleの接続先情報を取ってこれなくて断念。
  • 構成ファイルをGithubで管理して、GitHub ActionsをトリガーにCI/CDを実行したい。