새소식

기술/AWS

terraformer를 이용하여 aws resource import 해보기

  • -

들어가기 앞서서..
지금 회사는 아무래도 중도 입사를 했다 보니 인프라를 다 콘솔로 만들어놔서 Terraform을 사용하려면 import가 필요했다.

terraform import의 문제점
1. 각 리소스를 하나 하나 나열해야 하며
2. 각 리소스에 맞는 리소스 id을 매칭해야 한다.
예시)

terraform import aws_vpc.test_vpc vpc-a0123456
                  리소스   리소스 이름  리소스 id

3. 이것만 해야 하는 것이 아니라 아래 양식의 tf 파일도 만들어줘야 한다.
예시)

resource "aws_vpc" "test_vpc" {}

어느 세월에 vpc, subnet, routing table, igw, eip 기타 등등 명시하고 리소스id 가져오고 한단 말인가...

1인 전산인 나는 이런 노가다에는 관심도 없고 시간을 소모하기도 싫었기에 더 간단하게 꿀을 빨 방법을 찾았다.

그것이 바로 Terraformer!!

이것은 Google에서 GCP를 위해 개발한 도구로써, 기존 리소스를 terraform import를 손쉽게 도와주는 도구인데

GCP 외에도 aws, azure 등을 지원한다.

작업하기 앞서서 준비물
terraformer, terraform, awscli, aws access key

Terraformer는 brew를 통해 간단하게 설치할 수 있음

brew install terraformer

#준비물이 하나도 없다면..
brew install terraformer terraform awscli


아래 공식 Github를 통해 cli와 지원되는 리소스 종류를 확인할 수 있다.
https://github.com/GoogleCloudPlatform/terraformer/blob/master/docs/aws.md

 

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


나는 vpc에 존재하는 대부분의 리소스 (vpc, subnet, route_table, igw, sg)를 import하려고 한다.

아래 명령어를 입력하자.

terraformer import aws --resources=vpc,subnet,route_table,igw,sg,nat  --path-pattern="{output}/" --connect=true --regions=ap-northeast-2 --profile=aws-env-profile

--resource : import 시킬 리소스 지정
--path-pattern : 경로를 어떻게 할 것인지.. (요렇게 안해주면 리소스 별로 폴더가 생성되고 그 안에 각가의 .tf파일들이 생성됨)
--regions : 리전 지정
--profile : aws를 멀티 어카운트로 사용할 경우 인증키의 프로필 지정

오류가 날 경우!

처음에 오류가 나길래 뭐지 했는데.. terraform이 nodejs처럼 plugin을 글로벌(?)하게 설치하지 않아서 생기는 문제인데

aws provider가 없기 때문에 tf를 만들 수가 없어서 생긴 문제로 아래 링크에서 최신 버전에 맞는 aws provider를 다운로드 후

아래 폴더를 만들어서 넣어주자.

AWS Provider : https://releases.hashicorp.com/terraform-provider-aws

mkdir -p ~/.terraform.d/plugins/darwin_arm64 (m1, m2사용자용)

#글 작성 당시 최신 버전인 4.44.0의 링크 추가
curl -OL https://releases.hashicorp.com/terraform-provider-aws/4.44.0/terraform-provider-aws_4.44.0_darwin_arm64.zip > ~/.terraform.d/plugins/darwin_arm64/terraform-provider-aws_4.44.0_darwin_arm64.zip

unzip ~/.terraform.d/plugins/darwin_arm64/terraform-provider-aws_4.44.0_darwin_arm64.zip


정상적으로 import가 되었다면 다음 구조로 파일들이 생성된다.

├── internet_gateway.tf
├── main_route_table_association.tf
├── nat_gateway.tf
├── outputs.tf
├── provider.tf
├── route_table.tf
├── route_table_association.tf
├── security_group.tf
├── subnet.tf
├── variables.tf
└── vpc.tf

여기서 provider.tf에 한번 더 작업을 해줘야 하는 것이 있다.

provider "aws" {
  region                   = "ap-northeast-2"
  profile                  = "aws env profile"
  shared_config_files      = ["~/.aws/config"]
  shared_credentials_files = ["~/.aws/credentials"]
}

terraform {
	required_providers {
		aws = {
	    	version = "~> 4.44.0"
		}
  	}
}

terraformer로 생성된 provider에는 shared_config_files, shared_credentials_files 옵션이 없기 때문에 terraform init&plan이 불가능하기 때문에 꼭 필요한 작업이다.

이후 generated 폴더로 이동하여 terraform init을 진행하기 전 한가지 작업을 더 해야한다.

바로 terraform state replace-provider 작업인데.. terraformer가 아직 aws를 완전하게 지원하지 않는지 init을 할 때 문제가 생긴다.

아래 cli를 입력하여 변환 작업을 진행한다.

cd generated && terraform state replace-provider -auto-approve -- -/aws hashicorp/aws

이러면 약 수십개의 파일들이 변환이 된다.

이후 terraform init 과 terraform plan을 하면 정상적으로 import된 것들을 확인할 수 있다.

teraform plan

data.terraform_remote_state.local: Reading...
data.terraform_remote_state.local: Read complete after 0s
aws_vpc.tfer--vpc-1234567: Refreshing state... 
.
.
.
No changes. Your infrastructure matches the configuration.

Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed.
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.