본문 바로가기
공부/IaC

[Terraform] Terraform import와 terraforming (AWS)

by haejang 2021. 11. 7.
728x90
728x90

 

 

1. Terraform import란?


https://www.terraform.io/docs/cli/import/index.html

 

Import - Terraform by HashiCorp

Terraform can import and manage existing infrastructure. This can help you transition your infrastructure to Terraform.

www.terraform.io

 

Terraform import는 말 그대로 기존에 존재하던 인프라를 가져오는 기능이다

 

그러면 기존에 구성된 리소스들을 한꺼번에 코드로 땡겨올 수 있다는건가???

는 너무 내 희망회로였고, 공식 도큐를 잘 읽어보면 알겠지만 리소스를 그저 "상태"로 땡겨오는 기능이었다

심지어는 가져올 개체가 매핑될 리소스에 대한 빈 블록을 수동으로 미리 작성해놔야 했다

 

일단 한 번 해보자! (AWS 자격증명은 되어있다고 생각하고 진행)

 

2. Terraform import 사용하기


참조

 

우선 현재 내 계정엔 아래와 같은 EC2들이 존재한다

 

 

이 중 tf-ec2-pri-0 인스턴스를 땡겨와보겠다

 

먼저 aws instance를 import하는 명령줄 예시는 aws instance를 생성하는 리소스 도큐의 맨 밑에서 찾아볼 수 있다

https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/instance#import

 

https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/instance#import

 

registry.terraform.io

 

# 도큐에 적혀있는 예시
$ terraform import aws_instance.web i-12345678

처음엔 그냥 이렇게 인스턴스 아이디만 박아서 갖고오면 되나? 싶어서 그대로 시도해봤다

(aws provider 만 선언해두고 terraform init 실행 후 진행)

 

 

web이라는 aws_instance 리소스 블럭을 미리 만들어놔야된다고 한다...

 

# 빈 리소스 블럭 선언
resource "aws_instance" "web" {}

 

이러고 다시 위의 명령을 내려보니

 

 

성공했고,,,tfstate 파일이 새로 생겼다 (이미 tfstate 파일이 있다면 그 파일에 업데이트 됨)

 

 

내가 가져온 인스턴스의 속성들이 상태로 가져와진걸 확인할 수 있다

 

그러나 여기서 terraform plan 명령을 내리면?

 

 

빈 리소스 블럭에 속성들을 채워넣지 않았기 때문에 에러가 난다

즉,,,땡겨올 때 리소스 블럭 만들어놓는걸로도 모자라서 tfstate 파일 보면서 속성까지 직접 선언해줘야한다는 뜻이다

 

일단 시키는대로 ami랑 instance type 속성만 넣어서 다시 plan을 해봤다

 

 

선언하지 않은 속성인 instance profile과 tag는 사라질 예정이라고 한다

하.............결국 그대로 사용하고 싶으면 하나하나 다 선언해줘야 한다는 뜻이다

 

 

다행히도 기존 리소스를 terraform code로 만들어주는 도구가 있었다

 

3. terraforming 사용하기


https://github.com/dtan4/terraforming

 

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

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

github.com

 

terraforming은 AWS 리소스를 tf code 또는 tfstate 파일로 가져올 수 있는 Ruby 프로젝트이다 (AWS만 지원된다고 함)

 

따라서 terraforming을 사용하기 위해선 Ruby가 깔려있어야 한다 : https://rubyinstaller.org/downloads/

 

 

WITH DEVKIT에서 가장 최신버전을 받아 기본 설치를 진행했다

Ruby 설치가 끝난 후 새로 터미널을 열어 아래 명령을 내리면 terraforming 설치가 끝난다

$ gem install terraforming

 

 

이제 terraforming ec2 명령을 내려보겠다

 

PS C:\Users\sci97\Desktop\terraform\terraform-import> terraforming ec2
resource "aws_instance" "tf-ec2-pri-1" {
    ami                         = "ami-0e4a9ad2eb120e054"   
    availability_zone           = "ap-northeast-2a"
    ebs_optimized               = false
    instance_type               = "t3.medium"
    monitoring                  = false
    key_name                    = "home"
    subnet_id                   = "subnet-04a0d58df8fca00b7"
    vpc_security_group_ids      = ["sg-0e3a85073058337e1"]  
    associate_public_ip_address = true
    private_ip                  = "10.0.1.240"
    source_dest_check           = true

    root_block_device {
        volume_type           = "gp2"
        volume_size           = 8
        delete_on_termination = true
    }

    tags {
        "Name" = "tf-ec2-pri-1"
    }
}

....

resource "aws_instance" "tf-ec2-pri-0" {
    ami                         = "ami-0e4a9ad2eb120e054"
    availability_zone           = "ap-northeast-2a"
    ebs_optimized               = false
    instance_type               = "t3.medium"
    monitoring                  = false
    key_name                    = "home"
    subnet_id                   = "subnet-04a0d58df8fca00b7"
    vpc_security_group_ids      = ["sg-0e3a85073058337e1"]
    associate_public_ip_address = true
    private_ip                  = "10.0.1.179"
    source_dest_check           = true

    root_block_device {
        volume_type           = "gp2"
        volume_size           = 8
        delete_on_termination = true
    }

    tags {
        "Name" = "tf-ec2-pri-0"
    }
}

 

기존에 존재하던 8개 ec2의 정보를 모두 불러오게 된다

여기서 난 tf-ec2-pri-0 의 속성만 그대로 갖고와서 아까 import할 때 사용한 블럭에 갖다 넣어봤다

 

 

이제 다시 plan을 진행해보겠다

 

 

아.....테라포밍에서 인스턴스 프로파일은 안불러왔네..?

 

뭐 아무튼 이런식으로...terraforming에서도 못가져오는 부분들이 있다고 한다

그래도 이정도만 불러와줘도 굉장히 고마운 도구인 것 같다

 

그리고 기존 운영 인프라와 테라폼 인프라를 같이 관리할 목적이 아니라, 기존 인프라를 그대로 다른 곳에 똑같이 배포하고 싶을 땐 그냥 terraforming만 잘 활용해서 사용하면 되지 않나 싶다

.....만! terraforming이 가능한 AWS 리소스도 아직 한정적이다

 

아래는 terraforming github README에 있는 내용이다 (21.11.07 기준)

$ terraforming
Commands:
  terraforming alb             # ALB
  terraforming asg             # AutoScaling Group
  terraforming cwa             # CloudWatch Alarm
  terraforming dbpg            # Database Parameter Group
  terraforming dbsg            # Database Security Group
  terraforming dbsn            # Database Subnet Group
  terraforming ddb             # DynamoDB
  terraforming ec2             # EC2
  terraforming ecc             # ElastiCache Cluster
  terraforming ecsn            # ElastiCache Subnet Group
  terraforming efs             # EFS File System
  terraforming eip             # EIP
  terraforming elb             # ELB
  terraforming help [COMMAND]  # Describe available commands or one specific command
  terraforming iamg            # IAM Group
  terraforming iamgm           # IAM Group Membership
  terraforming iamgp           # IAM Group Policy
  terraforming iamip           # IAM Instance Profile
  terraforming iamp            # IAM Policy
  terraforming iampa           # IAM Policy Attachment
  terraforming iamr            # IAM Role
  terraforming iamrp           # IAM Role Policy
  terraforming iamu            # IAM User
  terraforming iamup           # IAM User Policy
  terraforming igw             # Internet Gateway
  terraforming kmsa            # KMS Key Alias
  terraforming kmsk            # KMS Key
  terraforming lc              # Launch Configuration
  terraforming nacl            # Network ACL
  terraforming nat             # NAT Gateway
  terraforming nif             # Network Interface
  terraforming r53r            # Route53 Record
  terraforming r53z            # Route53 Hosted Zone
  terraforming rds             # RDS
  terraforming rs              # Redshift
  terraforming rt              # Route Table
  terraforming rta             # Route Table Association
  terraforming s3              # S3
  terraforming sg              # Security Group
  terraforming sn              # Subnet
  terraforming snst            # SNS Topic
  terraforming snss            # SNS Subscription
  terraforming sqs             # SQS
  terraforming vgw             # VPN Gateway
  terraforming vpc             # VPC

Options:
  [--merge=MERGE]                                # tfstate file to merge
  [--overwrite], [--no-overwrite]                # Overwrite existng tfstate
  [--tfstate], [--no-tfstate]                    # Generate tfstate
  [--profile=PROFILE]                            # AWS credentials profile
  [--region=REGION]                              # AWS region
  [--use-bundled-cert], [--no-use-bundled-cert]  # Use the bundled CA certificate from AWS SDK

 

물론 기본적인 리소스 명령은 거의 존재하지만, 무수히 많은 AWS 서비스의 갯수에 비하면 아직 한참 모자란 것 같다

 

밑의 옵션을 참조해서 tfstate 파일로 가져오고 merge도 할 수 있으니 그건 알아서 해보자

 

이상! 끝!

 

 

 

728x90
728x90

댓글