[Terraform] terraform_remote_state

업데이트:     Updated:

카테고리:

태그:

🎯terraform_remote_state

terraform_remote_state 라는 데이터 소스를 사용하면 다른 테라폼 구성 세트에 저장된 테라폼 상태 파일을 가져올 수 있습니다.

예제: RDS 상태 파일 참조

예를 들어 웹 서버 클러스터가 테라폼으로 관리되는 Amazon RDS for MySQL 데이터베이스와 통신해야 한다고 가정해 봅시다.

1. 웹 서버 클러스터와 MySQL 데이터베이스 테라폼 구성 파일은 폴더 구조로 부터 격리되어 다음과 같은 구조를 같습니다.

└── stage
    ├── data-stores
    │   └── mysql
    └── services
        └── webserver-cluster

⚠️Note: 웹 서버 클러스터는 MySQL 데이터베이스보다 훨씬 자주 배포할 것이므로 그 과정에서 실수로 데이터베이스를 손상시키고 싶지 않다면 웹 서버 클러스터와 MySQL 데이터베이스 설정은 같은 위치에 정의하지 않아야 합니다.

2. stage/data-stores/mysql/main.tf 파일에 데이터베이스 리소스를 정의합니다.

provider "aws" {
  region = "us-east-2"
}

resource "aws_db_instance" "example" {
  identifier_prefix     = "terraform-up-and-running"
  engine                = "mysql"
  allocated_storage     = 10
  instance_class        = "db.t2.micro"
  name                  = "example_database"
  username              = "admin"
  password              = "???"
}

⚠️Note: aws_db_instance 리소스에 전달해야 할 매개 변수 중 마스터 패스워드는 다른 사용자에게 노출되면 안 되는 정보이므로 코드에 직접 평문으로 입력해서는 안됩니다. 대신 테라폼 리소스로 전달할 수 있는 방법은 2가지가 있습니다. 자세한 내용은 여기를 참고하세요.

3. MySQL 테라폼 구성 세트에 S3 Backend를 구성합니다.

terraform {
  backend "s3" {
    bucket         = "terraform-up-and-running-state"
    key            = "stage/data-stores/mysql/terraform.tfstate"
    region         = "us-east-2"
    dynamodb_table = "terraform-up-and-running-locks"
    encrypt        = true
  }
}

📌Note: 여기서 사용된 S3와 다이나모DB 테이블은 이미 만들어졌다고 가정합니다.

4. stage/data-stores/mysql/output.tf 파일에 2개의 출력 변수를 추가합니다.

output "address" {
  value       = aws_db_instance.example.address
  description = "Connect to the database at this endpoint"
}

output "port" {
  value       = aws_db_instance.example.port
  description = "The port the database is listening on"
}

5. stage/services/webserver-cluster/main.tf 파일에 terraform_remote_state 데이터 소스를 추가하여 S3에 저장된 tfstate 파일을 읽습니다.

data "terraform_remote_state" "db" {
  backend = "s3"

  config = {
    bucket = "terraform-up-and-running-state"
    key    = "stage/data-stores/mysql/terraform.tfstate"
    region = "us-east-2"
  }
}

📌Note: 모든 테라폼 데이터 소스로 부터 반환된 데이터는 읽기 전용이라는 점을 상기해야 합니다. 웹 서버 클러스터에서 수행하는 테라폼 코드는 데이터베이스의 상태에 문제가 발생할 위험이 없습니다.

6. terraform_remote_state 데이터 소스에서 데이터베이스 주소 및 포트를 가져와 user_data에서 사용합니다.

user_data <<EOF
#!/bin/bash
echo "Hello, World!"" >> index.html
echo "${data.terraform_remote_state.db.outputs.address}" >> index.html
echo "${data.terraform_remote_state.db.outputs.port}" >> index.html
nohup busybox httpd -f -p ${var.server_port} &
EOF

📌Note: 모든 데이터베이스의 출력 변수는 상태 파일에 저장되며 아래와 같은 형식의 속성 참조를 이용해 terraform_remote_state 데이터 소스에서 읽을 수 있습니다.

data.terraform_remote_state.<terraform_remote_state_NAME>.outputs.<ATTRIBUTE>

📌출처

Terraform Up & Running


👍 개인 공부 기록용 블로그입니다. 오류나 조언이 있으시면 언제든지 댓글 혹은 메일로 남겨주시면 감사하겠습니다! 😄

맨 위로 이동하기

terraform 카테고리 내 다른 글 보러가기

댓글남기기