테라폼에서 aws_caller_identity는 어디에 쓰이나요?

2022. 6. 17. 09:33IT/d . e . v . O . p . s

aws_caller_identity가 뭐야?

테라폼 도큐멘트를 보면 가끔 아래와 같은 코드가 나오는 경우가 있습니다.
도큐멘트에는 특별히 설명되어 있지 않아 이게 무슨 코드인가 싶은 분이 계실겁니다.

data "aws_caller_identity" "current" {}

나온지는 좀 되었습니다만(Terraform Version 0.7.1) 모르시는 분들이 계시는 것 같아서 이번 기회를 빌려 설명 드리려 합니다.
Terraform으로 AWS의 환경을 구성할 때 가끔 자신(또는 다른) 계정 ID 를 참조하고 싶을 때가 있습니다.

예를 들면 sns_topic_policy 작성시 자신의 계정에서 서브스크립션을 허용하기 위한 정책을 추가할 때 계정 ID가 필요합니다.
또 VPC 피어링 연결시에는 피어링을 할 상대방의 계정 ID가 필요하게 됩니다.

이러한 경우, 예전에는 환경 변수에 정의를 하고 읽어오거나, 계정 ID를 하드 코딩하시는 방법으로 사용하시기도 했는데요

예:
계정 ID를 변수 로 정의

variable "account_id" {
  type    = "string"
  default = "123456789000"
}

# 참조시에는 아래와 같이
${var. account_id}

리소스에 직접 쓰기

resource "aws_vpc_peering" "vpc_peer" {
    peer_owner_id = "123456789000"

    # ...
}

테라폼 0.7.1 부터 지원

테라폼 0.7.1 부터는 aws_caller_identity 라는 내장함수를 지원하는데 이것을 사용하면
간단하게 자신 또는 다른 계정의 ID를 참조하는 것이 가능합니다.

아래와 같이 데이터 소스를 정의하는 것만으로 각 리소스에

data "aws_caller_identity" "current" {}

를 추가 하는 것만으로 계정 ID를 가져와 사용할 수 있습니다.

${data.aws_caller_identity.current.account_id}

aws_caller_identity로 불러올 수 있는 데이터는 아래와 같습니다.

data "aws_caller_identity" "current" {}

output "account_id" {
  value = data.aws_caller_identity.current.account_id
}

output "caller_arn" {
  value = data.aws_caller_identity.current.arn
}

output "caller_user" {
  value = data.aws_caller_identity.current.user_id
}

예 : s3의 패스에 어카운트 ID가 포함되어 있는 경우

"Resource": "${aws_s3_bucket.foo.arn}/prefix/AWSLogs/${data.aws_caller_identity.current.account_id}/\*"

다른 계정 ID를 원하신다면 사전에 provider "aws"해당 계정의 자격 증명을 설정하면 :

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

data "aws_caller_identity" "peer_owner" {
  provider = "aws.peering_target"
}

# ${data.aws_caller_identity.peer_owner.account_id}

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

다른 계정 ID를 볼 수도 있습니다.