Terraform Module 버전 관리 (with git)

신동수·2024년 3월 7일
0

Terraform

목록 보기
7/10

개요

  • Terraform 으로 인프라를 관리하면 모듈을 사용하게 될 것이다. 로컬, 또는 원격기 에서 사용을 할 것인데 로컬은 보통 혼자 사용하거나 테스트를 할 때 적합하며, 원격지(Github, Bitbucket 등) 는 협업하고 코드를 공유하거나 커밋 로그를 통해 디버깅도 할 수 있고, 버전 관리도 할 수 있어 본 포스팅을 작성 하였다.

구조

.
├── _variables_
│   └── common-dev.yaml
├── backend
│   └── backend-dev.conf
├── main.tf
├── output.tf
├── provider.tf
├── s3
│   ├── s3.tf
│   └── varialbes.tf
└── variables.tf

작성자가 업로드할 모듈은 S3 이다. (제일 간단하기 때문!!)
s3 디렉토리로 이동은 하지 않고 현재 있는 곳에서 git, terraform 환경을 구성할 것이다. 이렇게 해야 디렉토리에 생성되는 모듈을 관리할 수 있다.

# main.tf
module "s3" {
    source       = "git::https://bitbucket.org/<Project>/<Repo>.git//s3?ref=v0.0.2"
    
    common_info  = local.common_info
    common_tags  = local.common_tags
}
# 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/s3.tf 파일의 내용이다.
결론적으로 만들 버킷명은 "dev-dolfin-global-bucket-test" 이다.

# git config 설정
% git config --local user.name <name>
% git config --local user.email <email>
% git config --local credential.helper store
% git config --local credential.helper cache

# git 원격 저장소 추가
% git remote add origin https://<ID>@bitbucket.org/<Project>/<Repository>.git

# git 초기화
% git init

# Bitbucket 에 업로드할 디렉토리
% git add s3/
% git add main.tf
% git add variables.tf
% git commit -m "modify"

# 원격 저장소로 push
% git push -u origin main


성공적으로 원격 저장소에 업로드가 되었다.

Tag 지정


git tag -a "v0.0.2" 로 명령을 내리면 위와 같이 보일 것이다.

# 모듈이 있는 디렉토리에서 tag 지정 (Test 로 v0.0.1은 하였기에 v0.0.2로 진행)
% git tag -a "v0.0.2"
# 위와 같은 화면에서 주석 제거 후 저장

# 저장이 완료가 되었다면 원격 저장소로 push 한다.
% git push --follow-tags origin main

# tag 확인
% git show v0.0.2
tag v0.0.2
Tagger: <user> <email>
Date:   Thu Mar 7 17:23:01 2024 +0900

   v0.0.2

commit 0888d2b247f702766224026f2e5f9663091ee173 (HEAD -> main, tag: v0.0.2, origin/main)
Author: <user> <email>
Date:   Thu Mar 7 17:20:50 2024 +0900

    modifiy

diff --git a/s3/s3.tf b/s3/s3.tf
index ee12e69..fa07eb5 100644
--- a/s3/s3.tf
+++ b/s3/s3.tf
@@ -1,5 +1,5 @@
 resource "aws_s3_bucket" "dev-dolfin-global-bucket" {
-  bucket = "${var.common_info.env}-${var.common_info.service_name}-bucket-test123"
+  bucket = "${var.common_info.env}-${var.common_info.service_name}-bucket-test"
 
   tags = merge(
     {
 



원격 저장소에서 tag 지정이 잘 된 것으로 확인이 된다.

결과

# terraform 초기화
% terraform init 

Initializing the backend...
Initializing modules...
Downloading git::https://bitbucket.org/<Project>/<Repo>.git//s3?ref=v0.0.2 for s3...
- s3 in .terraform/modules/s3/s3

Initializing provider plugins...
- Reusing previous version of hashicorp/aws from the dependency lock file
- Using previously-installed hashicorp/aws v5.39.1

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.

# terraform plan
% terraform plan 
var.env
  Environment

  Enter a value: dev


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

Terraform will perform the following actions:

  # module.s3.aws_s3_bucket.dev-dolfin-global-bucket will be created
  + resource "aws_s3_bucket" "dev-dolfin-global-bucket" {
      + acceleration_status         = (known after apply)
      + acl                         = (known after apply)
      + arn                         = (known after apply)
      + bucket                      = "dev-dolfin-global-bucket-test"
      + bucket_domain_name          = (known after apply)
      + bucket_prefix               = (known after apply)
      + bucket_regional_domain_name = (known after apply)
      + force_destroy               = false
      + hosted_zone_id              = (known after apply)
      + id                          = (known after apply)
      + object_lock_enabled         = (known after apply)
      + policy                      = (known after apply)
      + region                      = (known after apply)
      + request_payer               = (known after apply)
      + 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"
        }
      + website_domain              = (known after apply)
      + website_endpoint            = (known after apply)
    }

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

# terraform apply
% terraform apply
var.env
  Environment

  Enter a value: dev 


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

Terraform will perform the following actions:

  # module.s3.aws_s3_bucket.dev-dolfin-global-bucket will be created
  + resource "aws_s3_bucket" "dev-dolfin-global-bucket" {
      + acceleration_status         = (known after apply)
      + acl                         = (known after apply)
      + arn                         = (known after apply)
      + bucket                      = "dev-dolfin-global-bucket-test"
      + bucket_domain_name          = (known after apply)
      + bucket_prefix               = (known after apply)
      + bucket_regional_domain_name = (known after apply)
      + force_destroy               = false
      + hosted_zone_id              = (known after apply)
      + id                          = (known after apply)
      + object_lock_enabled         = (known after apply)
      + policy                      = (known after apply)
      + region                      = (known after apply)
      + request_payer               = (known after apply)
      + 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"
        }
      + website_domain              = (known after apply)
      + website_endpoint            = (known after apply)
    }

Plan: 1 to add, 0 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: Creating...
module.s3.aws_s3_bucket.dev-dolfin-global-bucket: Creation complete after 1s [id=dev-dolfin-global-bucket-test]

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


콘솔에서 정상적으로 확인이 되었다.

Module 안의 Source 부분 (추가 참고)

source = "git::https://bitbucket.org/<Project>/<Repo>.git//s3?ref=v0.0.2"
  • source는 module을 불러오는 필수 옵션이고 Bitbucket 의 주소로 모듈을 불러오기로 선언하였다.
  • module이 들어있는 Bitbucket 의 주소를 적는데 git 호출을 위해 두 개의 슬래시 //가 필요하다.
source = "git::https://bitbucket.org/<Project>/<Repo>.git//modules/s3?ref=v0.0.2"
  • 디렉토리가 추가로 더 있다면 위의 예시처럼 지정을 하면 될 것이다.
profile
조금씩 성장하는 DevOps 엔지니어가 되겠습니다. 😄

0개의 댓글

관련 채용 정보