0
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?

Terraformで意図しないAWSアカウントへのデプロイを防ぐ!自己チェックコードの紹介

Last updated at Posted at 2025-05-06

問題点

Terraformを使っていると、どの認証情報(クレデンシャル)で操作しているか不安になることありませんか?
私はもれなくあります。膝が震えちゃいますね。

特に複数のAWSアカウントを扱っていると、意図しない環境に planapply してしまうリスクが常に付きまといます。

そんな「うっかり事故」を防ぐために、Terraformコードに自己チェックの仕組みを組み込んでみましょう。

対策

次のコードを用意してみてください。

check.tf

# 現在AWSにログインしているアカウントIDとリージョンを取得しています
data "aws_caller_identity" "check_deploy_account" {}

data "aws_region" "check_deploy_region" {}

# 利用したいAWSアカウントを設定
variable "deploy_account_id" {
  description = "The AWS account ID where the resources will be deployed."
  type        = string
  default = "123456789999"
}

locals {
  is_allowed_account = data.aws_caller_identity.check_deploy_account.account_id == var.deploy_account_id
}

# テストコードの代わりにnull_resource
resource "null_resource" "check_deploy_account" {
  lifecycle {
    precondition {
      condition = local.is_allowed_account
      error_message = "このTerraformコードは指定されたアカウント(${var.deploy_account_id})でのみ実行可能です。現在のアカウントは: ${data.aws_caller_identity.check_deploy_account.account_id}です。"
    }
  }
}

効果確認

これを指定外の認証情報がセットされた状態でterraform plan, applyすると、以下のエラーが発生します。

terraform plan出力結果
│ Error: Resource precondition failed
│ 
│   on modules/network/check.tf line XX, in resource "null_resource" "check_deploy_account":
│   xx:       condition = local.is_allowed_account
│     ├────────────────
│     │ local.is_allowed_account is false
│ 
│ このTerraformコードは指定されたアカウント(123456789999)でのみ実行可能です。現在のアカウントは: XXXXXXXXXXXXです。

これでデプロイの向き先を確認することができますね。
都度確認するのも良いですが、仕組みで防ぐ方法も取り入れてみてはいかがでしょうか。

この記事がみなさんのエンジニアリングに貢献できれば幸いです。
最後までお読みいただき、ありがとうございました。

0
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
0
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?