この記事でわかること
先日正式提供となったAppRunのアプリケーションをterraform applyでデプロイする方法
terraform {
required_providers {
sakura = {
source = "sacloud/sakura"
version = "3.0.0-rc7"
}
}
}
provider "sakura" {
token = "<your-access-token>"
secret = "<your-access-secret>"
}
resource "sakura_apprun_shared" "my-app" {
name = "my-app"
timeout_seconds = 60
port = 8080
min_scale = 0
max_scale = 1
components = [{
name = "my-app:latest"
max_cpu = "0.5"
max_memory = "1Gi"
deploy_source = {
container_registry = {
image = "my-app.sakuracr.jp/my-app:latest"
server = "my-app.sakuracr.jp"
username = "<your-registry-username>"
password = "<your-registry-password>"
}
}
}]
}
AppRunについてと事前準備
AppRunの紹介と利用方法は以下の記事に書いていますので、「コンテナイメージの準備」まで進めてください
APIキーの作成
TerraformでアプリケーションをデプロイするためにAPIキーが必要です
https://secure.sakura.ad.jp/cloud/#/apikeys
以下の設定でAPIキーを作成して、アクセストークンとアクセストークンシークレットを保存してください
- アクセスレベル:「作成・削除」
- サービスへのアクセス権:「AppRun」
Terraform for さくらのクラウド
さくらのクラウドではリソースをTerraformで管理するためのproviderを提供しています
https://registry.terraform.io/providers/sacloud/sakuracloud/latest/docs
上記ツールは現在v2ですが、今後v3が正式に運用されていく予定なので、この記事ではv3を使った方法を紹介します
※v2とv3の記法は異なる部分があるためご注意ください
https://github.com/sacloud/terraform-provider-sakura/blob/main/CHANGES.md
Terraformでのデプロイ
Terraformのインストール
https://developer.hashicorp.com/terraform/install
# macOS
brew tap hashicorp/tap
brew install hashicorp/tap/terraform
トークンやアプリケーションのポート、コンテナレジストリの設定を書き換えて以下のファイルを作成してください
terraform {
required_providers {
sakura = {
source = "sacloud/sakura"
version = "3.0.0-rc7"
}
}
}
provider "sakura" {
# 環境変数やprofileを使った認証も可能
# https://registry.terraform.io/providers/sacloud/sakuracloud/latest/docs#authentication-methods
token = "<your-access-token>"
secret = "<your-access-secret>"
}
resource "sakura_apprun_shared" "my-app" {
name = "my-app"
timeout_seconds = 60
port = 8080
min_scale = 0
max_scale = 1
components = [{
name = "my-app:latest"
max_cpu = "0.5"
max_memory = "1Gi"
deploy_source = {
container_registry = {
image = "my-app.sakuracr.jp/my-app:latest"
server = "my-app.sakuracr.jp"
username = "<your-registry-username>"
password = "<your-registry-password>"
}
}
}]
}
あとは以下のコマンドを打っていくだけ
terraform init
terraform plan
terraform apply
AppRunのコントロールパネルからアプリケーションの確認をしてください
https://secure.sakura.ad.jp/apprun/shared/applications
参考情報
本記事で紹介した方法ではtfstateファイルを永続化していません
TerraformのBackendにS3を使う場合や、GitHub Actionsを使ったデプロイをする場合は以下の記事がとても参考になります!