IT

사용중인 인프라를 Terraform 코드화 하기

hexcode 2022. 4. 8. 17:47

여러 사람이 AWS 를 관리하다보면 콘솔로 작업한 부분 또는 CLI 로 작업한 부분 Terraform 과 같은 IaC 코드화 된 부분이 혼재 될수 밖에 없다. Infra 를 IaC 로 관리 하기로 했으면 일관성과 통일성을 위해서 IaC 화 하는게 맞을 것이다.

그렇지 않으면 일관적인 관리를 하지 못해 관리가 잘되지 않아 사고로 이어질수 있다.

Terraform 에서는 기본적으로 import 기능을 제공하여 기존 구성된 인프라를 가져오는 기능이 있다. 그러나 이 기능은 Terraform 의 상태 파일인  terraform.tfstate 만 가져 올뿐 .tf 파일은  terraform.tfstate 상태 파일을 참조하여 직접 코딩을 해야 되는 번거로움이 있다. 그러나 이게 가장 확실한 방법이다.

import 사용방법은 간단하다
terraform import [aws_resource] [resource_id] 

예를들어 vpc 를 가져온다고 하면 아래와 같이 한다.

tf 껍데기 파일을 먼저 만든다.

cat vpc.tf
resource "aws_vpc" "infra-vpc-kr" {
 # 껍데기 파일엔 우선 내용이 없어도 되고, 내용이 틀려도 import 단계에서는 내용을 참조하지 않으므로 아무내용이 있어도 된다.
}

껍데기 파일을 만들었음 import 명령어로 terraform.tfstate 상태 파일을 가져온다.

terraform import  aws_vpc.infra-vpc-kr vpc-08b75573cb8266b11

이후  가져온 terraform.tfstate 상태 파일을 보면서 vpc.tf 파일을 수정해야 한다.

vpc.tf 파일을 수정후 정합성을 어떻게 체크하나? => tf 파일의 내용을 채우면서 terraform plan 에서 No changes 메시지가 나올때까지 수정 해야 한다.

terraform plan
aws_vpc.infra-vpc-kr: Refreshing state... [id=vpc-08b75573cb8266b11]

No changes. Your infrastructure matches the configuration.

그러나 매우 tf 파일을 채우기란 번거로운 일이다. 따라서 tf 파일 까지 채워주는 툴들이 있다. 사용해본결과 정확하지는 않지만 대략 많은 노가다를 줄일수가 있다. 정확한 정합성을 위해서 terraform.tfstate  파일을 보면서 일일히 수정하는 방법이 정확 할 것이다.

terraforming : ruby 제작 https://github.com/dtan4/terraforming

 

GitHub - dtan4/terraforming: Export existing AWS resources to Terraform style (tf, tfstate) / No longer actively maintained

Export existing AWS resources to Terraform style (tf, tfstate) / No longer actively maintained - GitHub - dtan4/terraforming: Export existing AWS resources to Terraform style (tf, tfstate) / No lon...

github.com

  • 단점 : aws sso 의 경우엔 동작되지 않는다. 
    •  ~/.aws/credentials file에  aws_access_key_id 와 aws_secret_access_key 를 정의 해 주어야 한다.
  •  장점 :  terraform.tfstate  상태 자동 머지 

 

terraformer : go 로 제작 https://github.com/GoogleCloudPlatform/terraformer 

 

GitHub - GoogleCloudPlatform/terraformer: CLI tool to generate terraform files from existing infrastructure (reverse Terraform).

CLI tool to generate terraform files from existing infrastructure (reverse Terraform). Infrastructure to Code - GitHub - GoogleCloudPlatform/terraformer: CLI tool to generate terraform files from e...

github.com

  • 장점 : aws sso 에도 잘 동작한다.

'IT' 카테고리의 다른 글

Terraform S3 Backend 사용하기  (0) 2022.04.08
volumio 를 VMware 에 설치  (0) 2020.04.08