[HCP Terraform]VCS連携したWorkspaceのPlanをローカルのCLIから実行する

[HCP Terraform]VCS連携したWorkspaceのPlanをローカルのCLIから実行する

Clock Icon2025.05.21

HCP TerraformのVCS Driven Workflowでは、VCSに変更があった際に自動的にTerraformのplan・applyを実行するように設定できます。

通常tfファイルにバックエンド用のWorkspaceを定義するのですが、VCS Driven Workflowでは設定を省略できます。

「VCS Driven Workflow利用時に、どうやってローカルからterraform planを実行すればよいのか?」という質問をもらったため、ブログにします。

結論、コンソールに環境変数で以下をセットすれば可能です。

  • HCP Terraform Organizations名(TF_CLOUD_ORGANIZATION)
  • Workspace名(TF_WORKSPACE)
export TF_CLOUD_ORGANIZATION=<Organizations名>
export TF_WORKSPACE=<Workspace名>

https://developer.hashicorp.com/terraform/language/terraform#environment-variables-for-the-cloud-block

Workspace(VCS Driven)とtfファイルの用意

以下のコードを使います。

https://github.com/msato0731/aws-tfc-introductory-book-samples/tree/main/infra/chapter5/aws/prod

cloudブロックの設定は以下で、空にしています。

main.tf
terraform {
  required_version = ">= 1.10.2"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.82.2"
    }
  }
  cloud {}
}

Working Directoryに上記のコードがある部分を設定、実行モードはRemoteでWorkspaceを作成しました。

Runが成功したところまで確認しました。

vscode-drop-1747703884607-3cnxygk6zh3.png

ちなみに、この状態でローカルでコマンドを実行すると以下のようにエラーがでます。

terraform plan
出力例
╷
│ Error: Invalid or missing required argument
│
│ "organization" must be set in the
│ cloud configuration or as an
│ environment variable:
│ TF_CLOUD_ORGANIZATION.
╵
╷
│ Error: Invalid workspaces configuration
│
│ Missing workspace mapping
│ strategy. Either workspace "tags"
│ or "name" is required.
│
│ The 'workspaces' block configures
│ how Terraform CLI maps its
│ workspaces for this single
│ configuration to workspaces
│ within an HCP Terraform or
│ Terraform Enterprise
│ organization. Two strategies are
│ available:
│
│ [bold]tags[reset] - A set of tags
│ used to select remote HCP
│ Terraform or Terraform Enterprise
│ workspaces to be used for this
│ single
│ configuration. New workspaces
│ will automatically be tagged with
│ these tag values. Generally, this
│ is the primary and recommended
│ strategy to use.  This option
│ conflicts with "name".
│
│ [bold]name[reset] - The name of a
│ single HCP Terraform or Terraform
│ Enterprise workspace to be used
│ with this configuration.
│ When configured, only the
│ specified workspace can be used.
│ This option conflicts with "tags"
│ and with the TF_WORKSPACE
│ environment variable.

環境変数をセット

ローカルのtfファイルがあるディレクトリに移動します。

以下のコマンドを実行して、環境変数をセットします。

export TF_CLOUD_ORGANIZATION=<Organizations名>
export TF_WORKSPACE=<Workspace名>

動作確認

ローカルからのPlan

ローカルからPlanを実行し、正常に実行できることを確認できました。

terraform plan
出力例
No changes. Your infrastructure matches the configuration.

ローカルのtfファイルを書き換えて、Planしてみます。

EC2のEnvタグをprod -> testに変更しました。

main.tf
resource "aws_instance" "main" {
  ami           = data.aws_ssm_parameter.amazonlinux_2023.value
  instance_type = "t3.micro"
  subnet_id     = module.vpc.private_subnets[0]
  tags = {
    Name = local.name
    # 自動デプロイのテスト時にコメント外す
+    Env = "test"
-    Env = "prod"
  }
}

Planを実行してみると、ローカルで変更したファイルの情報が反映されて差分が確認できました。

terraform plan
出力例
Terraform will perform the following actions:

  # aws_instance.main will be updated in-place
  ~ resource "aws_instance" "main" {
        id                                   = "i-hogehoge"
      ~ tags                                 = {
          ~ "Env"  = "prod" -> "test"
            "Name" = "prod-hcp-tf-aws-book"
        }
      ~ tags_all                             = {
          ~ "Env"  = "prod" -> "test"
            # (1 unchanged element hidden)
        }
        # (38 unchanged attributes hidden)

        # (8 unchanged blocks hidden)
    }

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

ちなみに、Plan自体はHCP Terraform上で行われてコンソールには結果がストリーミングされている形になります。

ローカルにAWS認証情報をセットする必要はありません。

ローカルからのApply

Applyの動作についても、確認します。

結論、Applyは実行できずエラーがでます。

「ローカルから、ユーザーが間違ってApplyしてしまった」といったことを避けられて良いですね。

terraform apply
出力例
│ Error: Apply not allowed for workspaces with a VCS connection
│
│ A workspace that is connected to a VCS
│ requires the VCS-driven workflow to ensure
│ that the VCS remains the single source of
│ truth.

おわりに

VCS Driven Workflow利用時の、ローカルからのPlanについてでした。

環境変数を設定することで、ローカルからPlanを実行できます。Applyは不可で、HCP Terraform上から実行する必要があります。

cloudブロックと環境変数両方で設定した場合は、cloudブロックが優先されることに注意してください。

以上、AWS事業本部の佐藤(@chari7311)でした。

Share this article

facebook logohatena logotwitter logo

© Classmethod, Inc. All rights reserved.