43
24

More than 1 year has passed since last update.

*.tf 内で AWS アカウント ID を自動参照(取得)する aws_caller_identity Data Source

Last updated at Posted at 2016-10-03

結論

aws_caller_identity を使います。

data "aws_caller_identity" "self" { }

output "account_id" {
  value = "${data.aws_caller_identity.self.account_id}"
}

経緯

Terraform で AWS の各構成を組んでいる時、たまに 自身(もしくは別)アカウントID を参照したくなる時があります。

例:

  • sns_topic_policy
    • 「自身のアカウントからの Subscription を許可する」というポリシーを追加する時はアカウントIDが必要
  • aws_vpc_peering_connection
    • VPC ピア接続の際に、接続先である相手のアカウントIDが必要

こういったケースでは、これまではアカウントIDを variable として定義したり:

variable "peer_to_account_id" {
  type    = "string"
  default = "123456789012"
}

# 参照する時は `${var.peer_to_account_id}`

それすらも必要無いと直接書き込んだり:

resource "aws_vpc_peering_connection" "foo" {
    peer_owner_id = "123456789012"

    # ...
}

環境変数から読むという技もありますが、とりあえずアカウントIDをハードコーディングすることがほとんどだったと思います。

aws_caller_identity の登場

ハードコーディングで構わないと思いつつも、どうにかいい感じに Terraform が AWS アカウント ID を取得してくれないかなーという願いを叶えるために、 Terraform version 0.7.1 から aws_caller_identity が実装されました。

Usage

data "aws_caller_identity" "self" { }

上記のように data ソースを定義しておくだけで、各リソースで

${data.aws_caller_identity.self.account_id}

を使ってアカウントID を参照(取得)することができます。

Usage (別アカウント)

他のアカウントIDも欲しいよーという場合は、事前に provider "aws" で対象のアカウントの認証情報をセットしておくと:

provider "aws" {
  access_key = "XXXXXXXXXX"
  secret_key = "YYYYYYYYYY"
  region     = "ap-northeast-1"
  alias      = "consumer"
}

data "aws_caller_identity" "peer_owner" {
  provider = "aws.consumer" # <= ここ追加
}

# ${data.aws_caller_identity.peer_owner.account_id}

他アカウントIDを参照することができます。

参考資料

43
24
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
43
24