Terraform Import 사용

신동수·2024년 3월 6일
0

Terraform

목록 보기
5/10

개요

  • Terraform 을 사용하지 않고 AWS Console 에서 자원을 만드는 경우가 있을 것이다. Terraform 으로 관리가 필요하지 않다면 필요없지만, 추후 코드로 관리를 하기 위해서는 import 를 하여 관리할 수 있도록 할 수 있다.

구조

# Terraform tree 구조
.
├── _variables_
│   └── common-dev.yaml
├── main.tf
├── output.tf
├── provider.tf
├── s3
│   ├── s3.tf
│   └── varialbes.tf
└── variables.tf

실습을 위한 기본적인 구조는 위와 같다.

# _variables_/common-dev.yaml
---
env: dev
service_name: dolfin-global
role_arn: arn:aws:iam::<Account>:role/<Role>
account: '<Account>'
tf_state_s3: <S3>
tf_state_dynamo: <DynamoDB> 
common_tags:
	Service: Dolfin-Global
	Environment: Develop
	Project: IaC-Terraform
# ./variables.tf
variable "env" {
	description = "Environment"
	type = string
}

variable "region" {
	description = "region name"
	type = string
	default = "ap-northeast-2"
}

locals {
	# environment 별로 다른 파일 바라보도록 설정
	common_info = yamldecode(file("${path.module}/_variables_/common-${var.env}.yaml"))
	common_tags = local.common_info.common_tags
}

문제 재현


dev-dolfin-global-bucket-test 이름으로 버킷을 생성하였고, 추후 S3 폴더 아래에 s3.tf 파일에서 import 하여 관리할 수 있도록 진행하겠다. (태그는 따로 지정하지 않았으며, 추후 import 후 반영)

# Terraform 자원 확인
% terraform state list 
No state file was found!

State management commands require a state file. Run this command
in a directory where Terraform has been run or use the -state flag
to point the command to a specific state location.

# Terraform 실행
% terraform plan
var.env
  Environment

  Enter a value: dev 


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.

콘솔에서 S3 자원을 만들었기에 확인되는 자원이 없고, 변경할 사항이 없다는 문구가 뜬다.

문제 해결

# s3/s3.tf
resource "aws_s3_bucket" "dev-dolfin-global-bucket" {
  bucket = "${var.common_info.env}-${var.common_info.service_name}-bucket-test"
  tags = merge(
    {
      Name = "${var.common_info.env}-${var.common_info.service_name}"
    },
    var.common_tags
  )
}

위 파일처럼 리소스를 정의 하였다.
처음에 만든 S3 는 버킷명만 지정을 하고 기본 값으로 생성을 하였다. 그래서 import 가 완료 된 후 태그까지 추가하기 위해서 tag 도 넣어 반영이 되는지 확인을 하겠다.

# Terraform 초기화
% terraform init

# Terraform import 를 통한 리소스 가져오기
% terraform import module.s3.aws_s3_bucket.dev-dolfin-global-bucket dev-dolfin-global-bucket-test 
var.env
  Environment

  Enter a value: dev 

module.s3.aws_s3_bucket.dev-dolfin-global-bucket: Importing from ID "dev-dolfin-global-bucket-test"...
module.s3.aws_s3_bucket.dev-dolfin-global-bucket: Import prepared!
  Prepared aws_s3_bucket for import
module.s3.aws_s3_bucket.dev-dolfin-global-bucket: Refreshing state... [id=dev-dolfin-global-bucket-test]

Import successful!

The resources that were imported are shown above. These resources are now in
your Terraform state and will henceforth be managed by Terraform.

# Terraform 자원 확인
% terraform state list 
module.s3.aws_s3_bucket.dev-dolfin-global-bucket

위 과정에서 정상적으로 확인이 된 것을 확인할 수 있었다.

# Terraform plan
% terraform plan 
var.env
  Environment

  Enter a value: dev

module.s3.aws_s3_bucket.dev-dolfin-global-bucket: Refreshing state... [id=dev-dolfin-global-bucket-test]

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  ~ update in-place

Terraform will perform the following actions:

  # module.s3.aws_s3_bucket.dev-dolfin-global-bucket will be updated in-place
  ~ resource "aws_s3_bucket" "dev-dolfin-global-bucket" {
      + force_destroy               = false
        id                          = "dev-dolfin-global-bucket-test"
      ~ tags                        = {
          + "Environment" = "Develop"
          + "Name"        = "dev-dolfin-global"
          + "Project"     = "IaC-Terraform"
          + "Service"     = "Dolfin-Global"
        }
      ~ tags_all                    = {
          + "Environment" = "Develop"
          + "Name"        = "dev-dolfin-global"
          + "Project"     = "IaC-Terraform"
          + "Service"     = "Dolfin-Global"
        }
        # (8 unchanged attributes hidden)

        # (3 unchanged blocks hidden)
    }

Plan: 0 to add, 1 to change, 0 to destroy.
# Terraform apply
% terraform apply 
var.env
  Environment

  Enter a value: dev 

module.s3.aws_s3_bucket.dev-dolfin-global-bucket: Refreshing state... [id=dev-dolfin-global-bucket-test]

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  ~ update in-place

Terraform will perform the following actions:

  # module.s3.aws_s3_bucket.dev-dolfin-global-bucket will be updated in-place
  ~ resource "aws_s3_bucket" "dev-dolfin-global-bucket" {
      + force_destroy               = false
        id                          = "dev-dolfin-global-bucket-test"
      ~ tags                        = {
          + "Environment" = "Develop"
          + "Name"        = "dev-dolfin-global"
          + "Project"     = "IaC-Terraform"
          + "Service"     = "Dolfin-Global"
        }
      ~ tags_all                    = {
          + "Environment" = "Develop"
          + "Name"        = "dev-dolfin-global"
          + "Project"     = "IaC-Terraform"
          + "Service"     = "Dolfin-Global"
        }
        # (8 unchanged attributes hidden)

        # (3 unchanged blocks hidden)
    }

Plan: 0 to add, 1 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes 

module.s3.aws_s3_bucket.dev-dolfin-global-bucket: Modifying... [id=dev-dolfin-global-bucket-test]
module.s3.aws_s3_bucket.dev-dolfin-global-bucket: Modifications complete after 2s [id=dev-dolfin-global-bucket-test]

Apply complete! Resources: 0 added, 1 changed, 0 destroyed.

plan 명령을 통해서 만들어둔 버킷에 태그를 변경하도록 계획이 되어 있다. 태그를 추가할 것이므로 apply 를 통해서 진행을 하겠다.

결과


리소스 구문에 맞춰서 태그가 함께 반영이 된 것을 확인할 수 있었다.

삭제

# Terraform destroy
% terraform destroy 
var.env
  Environment

  Enter a value: dev 

module.s3.aws_s3_bucket.dev-dolfin-global-bucket: Refreshing state... [id=dev-dolfin-global-bucket-test]

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  - destroy

Terraform will perform the following actions:

  # module.s3.aws_s3_bucket.dev-dolfin-global-bucket will be destroyed
  - resource "aws_s3_bucket" "dev-dolfin-global-bucket" {
      - arn                         = "arn:aws:s3:::dev-dolfin-global-bucket-test" -> null
      - bucket                      = "dev-dolfin-global-bucket-test" -> null
      - bucket_domain_name          = "dev-dolfin-global-bucket-test.s3.amazonaws.com" -> null
      - bucket_regional_domain_name = "dev-dolfin-global-bucket-test.s3.ap-northeast-2.amazonaws.com" -> null
      - force_destroy               = false -> null
      - hosted_zone_id              = "Z3W03O7B5YMIYP" -> null
      - id                          = "dev-dolfin-global-bucket-test" -> null
      - object_lock_enabled         = false -> null
      - region                      = "ap-northeast-2" -> null
      - request_payer               = "BucketOwner" -> null
      - tags                        = {
          - "Environment" = "Develop"
          - "Name"        = "dev-dolfin-global"
          - "Project"     = "IaC-Terraform"
          - "Service"     = "Dolfin-Global"
        } -> null
      - tags_all                    = {
          - "Environment" = "Develop"
          - "Name"        = "dev-dolfin-global"
          - "Project"     = "IaC-Terraform"
          - "Service"     = "Dolfin-Global"
        } -> null

      - grant {
          - id          = "a08f5671df2db5e92c18000ba68cf6066f6d54e7ac1b1bafd08aa3b4750ee37c" -> null
          - permissions = [
              - "FULL_CONTROL",
            ] -> null
          - type        = "CanonicalUser" -> null
        }

      - server_side_encryption_configuration {
          - rule {
              - bucket_key_enabled = true -> null

              - apply_server_side_encryption_by_default {
                  - sse_algorithm = "AES256" -> null
                }
            }
        }

      - versioning {
          - enabled    = false -> null
          - mfa_delete = false -> null
        }
    }

Plan: 0 to add, 0 to change, 1 to destroy.

Do you really want to destroy all resources?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value:  yes 

module.s3.aws_s3_bucket.dev-dolfin-global-bucket: Destroying... [id=dev-dolfin-global-bucket-test]
module.s3.aws_s3_bucket.dev-dolfin-global-bucket: Destruction complete after 0s

Destroy complete! Resources: 1 destroyed.

import 를 한 자원이기에 destroy 를 통해 자원 삭제도 가능하다.

profile
조금씩 성장하는 DevOps 엔지니어가 되겠습니다. 😄

0개의 댓글

관련 채용 정보