본문 바로가기

♻ Terraform(테라폼)/👉 Terraformer

Terraformer를 활용하여 기존의 인프라 리소스를 Terraform으로 가져오기

# 기존에 생성한 인프라 리소스를 Terraformer를 활용하여 Terraform으로 가져오기

1. ec2 인스턴스 생성

2021.10.24 - [⭐ AWS/EC2] - EC2 생성

 

EC2 생성

EC2 인스턴스 생성 1. 인스턴스 시작을 클릭하여 EC2 생성을 시작합니다. 2. 설치할 OS를 확인하고 선택을 클릭합니다. 3. 원하는 스펙을 선택하고 다음으로 넘어 갑니다. 4. 네트워크를 구성 후 다음

may9noy.tistory.com

2. 생성한 ec2에 terraformer 설치

- 일단 생성한 ec2에 접근

2020.11.01 - [⭐ AWS/EC2] - MobaXterm을 활용한 SSH 접속

 

MobaXterm을 활용한 SSH 접속

1. MobaXterm 다운로드 웹페이지 접속 후 다운로드 : https://mobaxterm.mobatek.net/ MobaXterm free Xserver and tabbed SSH client for Windows The ultimate toolbox for remote computing - includes X server, enhanced SSH client and much more! mobax

may9noy.tistory.com

- 패키지 목록 업데이트

sudo apt-get update

3. Terraformer 설치

export PROVIDER=aws

curl -LO https://github.com/GoogleCloudPlatform/terraformer/releases/download/$(curl -s https://api.github.com/repos/GoogleCloudPlatform/terraformer/releases/latest | grep tag_name | cut -d '"' -f 4)/terraformer-${PROVIDER}-linux-amd64

chmod +x terraformer-${PROVIDER}-linux-amd64

sudo mv terraformer-${PROVIDER}-linux-amd64 /usr/local/bin/terraformer

- Terraformer 설치 확인

terraformer version

Terraformer v0.8.22

- 정상설치 확인

4. 공통으로 사용할 Terraform plugin 경로를 생성

참고 자료는 아래와 같다.

https://developer.hashicorp.com/terraform/cli/config/config-file

 

CLI Configuration | Terraform | HashiCorp Developer

Learn to use the CLI configuration file to customize your CLI settings, including credentials, plugin caching, provider installation methods, etc.

developer.hashicorp.com

우분투 홈 경로에서 .terraformrc 파일을 생성하고 아래의 내용을 작성한다.

우분투 홈 경로 : /home/ubuntu

vi .terraformrc
plugin_cache_dir   = "$HOME/.terraform.d/plugins"
disable_checkpoint = true

위에서 생성한 경로에 플러그인 폴더를 생성한다.

pwd
/home/ubuntu/.terraform.d
ubuntu@ip-10-0-40-167:~/.terraform.d$ mkdir plugins

5. 조금늦었지만 terraform 설치

2021.08.29 - [Terraform(테라폼)/Terraform 기본 구성] - AWS CLI 및 Terraform 설치

 

AWS CLI 및 Terraform 설치

1. AWS CLI 설치 curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" 2. 다운받은 CLI 파일을 압축해제 unzip awscliv2.zip sudo ./aws/install 3. Terraform 설치 # 테라폼 다운로드 사이트 https://releases.has

may9noy.tistory.com

6. terraform init

생성된 plugins 폴더에는 aws 프로바이더에 대한 정보가 없으므로 terraform init을 수행하여 해당 정보를 생성해야 한다.

임시로 main.tf 파일을 생성 후 terraform init을 수행한다.

- main.tf 내용

provider "aws" {

region = "ap-northeast-2"

}

- init 결과

ubuntu@ip-10-0-40-167:~/.terraform.d/plugins$ vim main.tf
ubuntu@ip-10-0-40-167:~/.terraform.d/plugins$ terraform init

Initializing the backend...

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

- init이 완료되면 init을 수행한 폴더에 linux_amd64 폴더와 함께 관련 파일이 생성된다.

7. aws configure를 통해 aws 자격증명을 수행한다.

- 현재 생성된 aws 자격증명을 확인한다. 여기서는 새로운 서버를 생성하고 자격증명을 해준적이 없으니 아래와 같이 not set이라고 표시된다.

ubuntu@ip-10-0-40-167:~/.terraform.d/plugins$ aws configure list
      Name                    Value             Type    Location
      ----                    -----             ----    --------
   profile                <not set>             None    None
access_key                <not set>             None    None
secret_key                <not set>             None    None
    region           ap-northeast-2             imds

- aws 자격증명 수행

aws configure를 입력하여 자격증명을 수행한다.

- 자격증명 후 리스트로 조회하면 아래와 같이 나타난다.

ubuntu@ip-10-0-40-167:~/.terraform.d/plugins$ aws configure list
      Name                    Value             Type    Location
      ----                    -----             ----    --------
   profile                <not set>             None    None
access_key     ****************OOOL shared-credentials-file
secret_key     ****************OOOh shared-credentials-file
    region           ap-northeast-2      config-file    ~/.aws/config

8. terraform import 명령어를 통해 이미 생성된 리소스를 tf 파일로 변환한다.

- 명령어 예시 및 설명

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를 멀티 어카운트로 사용할 경우 인증키의 프로필을 지정한다.

기본 명령어는 아래와 같다.

terraformer import aws --resources=vpc,subnet --connect=true --regions=ap-northeast-2 --profile=default

- 변환중인 모습

- 완료되면 generated/ 라는 폴더 안에 해당 리소스들이 생성되어 있다.

- vpc 와 관련된 tf 파일이 저장된 모습

/home/ubuntu/.terraform.d/plugins/generated/aws/vpc
ubuntu@ip-10-0-40-167:~/.terraform.d/plugins/generated/aws/vpc$ ll
total 28
drwxrwxr-x 2 ubuntu ubuntu 4096 Mar 21 05:00 ./
drwxrwxr-x 4 ubuntu ubuntu 4096 Mar 21 05:00 ../
-rwxrwxr-x 1 ubuntu ubuntu  320 Mar 21 05:00 outputs.tf*
-rwxrwxr-x 1 ubuntu ubuntu  129 Mar 21 05:00 provider.tf*
-rwxrwxr-x 1 ubuntu ubuntu 6227 Mar 21 05:00 terraform.tfstate*
-rwxrwxr-x 1 ubuntu ubuntu 1033 Mar 21 05:00 vpc.tf*

- subnet과 관련된 tf 파일이 저장된 모습

drwxrwxr-x 2 ubuntu ubuntu  4096 Mar 21 05:00 ./
drwxrwxr-x 4 ubuntu ubuntu  4096 Mar 21 05:00 ../
-rwxrwxr-x 1 ubuntu ubuntu  1903 Mar 21 05:00 outputs.tf*
-rwxrwxr-x 1 ubuntu ubuntu   129 Mar 21 05:00 provider.tf*
-rwxrwxr-x 1 ubuntu ubuntu  7510 Mar 21 05:00 subnet.tf*
-rwxrwxr-x 1 ubuntu ubuntu 31497 Mar 21 05:00 terraform.tfstate*
-rwxrwxr-x 1 ubuntu ubuntu   136 Mar 21 05:00 variables.tf*

9. generated된 데이터를 vscode 에서 실행 후 plan 으로 현재의 aws 인프라와 매핑하기

- 일단 모든 generated된 코드를 vs코드로 복사한다.

- vs코드에서 새로운 폴더를 생성 후 복사하자.

일단 vpc와 관련된 내용을 모두 복사하고 아래와 같이 terraform init 및 terraform plan을 수행하였다.

정상적으로 리소스를 가져오는것을 볼 수 있다.

- subnet과 관련된 리소스들을 vs code로 복사 한뒤 terraform plan을 수행한다.

- 최종 폴더 구조는 아래와 같다.

- 아무리 dev 환경이라도... plan까지는 가능한데 apply 하기가 좀 그릏다...ㅋㅋ

새로운 리전에 s3 버킷 같은 리소스를 만들고 한번 테스트를 해보자.

terraform import보다 terraformer로 aws 자원을 importing 하여 사용하는게 매우 유용할듯 싶다.

* 트러블 슈팅하기

- 해당문제는 해결이 안됐다.

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x4d70abf]

- 끝 -