데보션앱 소개페이지 바로가기
로그인 선택

신고하기

CLOSE
신고사유 (대표 사유 1개)
상세내용 (선택)
0/200
  • 신고한 게시글은 더 이상 보이지 않습니다.
  • 이용약관과 운영정책에 따라 신고사유에 해당하는지 검토 후 조치됩니다.
  • 허위 신고인 경우, 신고자의 서비스 이용이 제한될 수 있으니 유의하시어 신중하게 신고해 주세요.
(이 회원이 작성한 모든 댓글과 커뮤니티 게시물이 보이지 않고, 알림도 오지 않습니다.)

미리보기

커뮤니티

      1,234

      badge 23.06.15

      글 등록

      카테고리를 선택해주세요.

      DEVOTEE를 활성화 시키면
      지금 작성한 커뮤니티 글에 대해 1개의 댓글을 달아줍니다.

      버튼을 누르면 글 수정 시 ChatGPT가 작성한 댓글이 수정됩니다.

      임시저장함에 저장되었습니다. 저장일시 : 2022.5.17 14:29:08

      임시저장함

      제목을 선택하시면 이어서 작성이 가능하며,
      최대 20건까지 저장합니다.
      컨텐츠 유형, 제목, 저장일시, 삭제로 이뤄진 임시저장 목록
      컨텐츠 유형 제목 저장일 삭제

      데보션 블로그 게재 요청

      CLOSE
      • *
      • *

      본인인증

      효율적인 데보션 서비스 이용 및
      고객님의 소중한 개인정보보호를 위해
      본인인증을 진행해주세요. 본인인증 미 진행 시 로그인이 제한됩니다.
      본인인증 실패

      본인인증 로그인에 실패하였습니다.
      회원이 아니시거나 본인인증 등록이
      완료되지 않은 사용자입니다.

      회원정보 연결

      AWS SQS 생성하기 by Terraform (연재#3)

      KIDO 21.09.06
      1,776 4 0

      AWS SQS by Terraform (연재#3)

      • 지난번에는 SQS를 AWS Console로 생성하고, 테스트를 해 보았으니 이제는 Terraform 을 이용하여 자동화 해보자.

       

      Terraform 설치

      • Terraform 설치의 경우에는 Install Terraform 에서 참조하여 설치하자.

       

      Terraform SQS IaC 구조 만들기

      • Terraform SQS의 파일 구조는 다음과 같다.

        • provider.tf : 프로바이더는 Terraform사용 권한 및 리젼 정보를 설정한다.
        • main.tf : Terraform 으로 SQS를 생성하기 위한 템플릿 정보이다.
        • outputs.tf : Terraform 출력 결과를 노출을 위한 정의를 수행한다.
        • vars.tf : SQS를 생성하기 위한 변수를 설정한다.
      • 위와 같은 구조로 파일을 구성하고, 실제 코드를 확인해 보자.

       

      SQS 큐 생성

      provider 설정하기

      • 가장 먼저 확인해 볼 사항이 provider를 살펴 보는 것이다.
      • provider는 리젼과, 테라폼 생성권한에 대한 정보를 설정한다.
      provider "aws" {
        region = var.AWS_REGION
        profile = var.PROFILE
        shared_credentials_file = var.CREDENTIAL_FILES
      }
      • region: 리젼은 SQS를 생성할 리젼을 지정한다. var.AWS_REGION 변수로 설정했으며 이 값은 vars.tf 에 기입되어 있다.
      • profile: 프로파일은 실행하고자 하는 AWS Credential 의 프로파일 이름이다. 이 값은 aws cli 를 통해 "aws configure" 로 설정할때 지정할 수 있는 프로파일을 기입할 수 있따. (profile을 설정하지 않는다면 / acess_key, secret_key 등을 통해서 등록할 수 도 있다.)
      • shared_credentials_file: aws credential 파일 위치를 지정해 줄 수 있다.

       

      vars.tf 파일보기

      • vars.tf 파일에서 provider 부분은 다음과 같이 지정된다.
      variable "AWS_REGION" {
        default = "ap-northeast-2"
      }
      
      variable "PROFILE" {
        description = "This is an aws profile for shared credentials file"
        default = "terraform_user"
      }
      
      variable "CREDENTIAL_FILES" {
        description = "This is a path of credentials file"
        default = "/Users/kido/.aws/credentials"
      }
      • 위와 같이 변수를 AWS_REGIOIN, PROFILE, CREDENTIAL_FILES 르 설정했다.
        • variable "변수명" 으로 변수 이름을 지정하였다.
        • description: 변수 설명을 지정한다.
        • default: 변수 값을 지정한다.

       

      sqs 생성

      • main.tf 파일을 살펴보자.

       

      sqs 리소스 생성하기

      resource "aws_sqs_queue" "my_todo2" {
        name = var.SQS_NAME
        delay_seconds = var.DELAY_SEC
        max_message_size = var.MAX_MESSAGE_SIZE
        visibility_timeout_seconds = var.VISIBILITY_TIMEOUT_SECONDS
        message_retention_seconds = var.MESSAGE_RETENTION_SECONDS
        receive_wait_time_seconds = var.RECEIVE_WAIT_TIME_SECONDS
        fifo_queue = var.FIFO_QUEUE
        content_based_deduplication = var.CONTENT_BASED_DEDUPLICATION
      }
      • resource "aws_sqs_queue" "리소스이름" : 리소스 생성을 하겠다는 의미로 이름은 my_todo2 로 잡았다.
      • name: 리소스 이름을 지정한다.
      • delay_second: sqs에서 설정 정보인 큐 메시지를 제공할 딜레이 시간을 지정한다. (기본값은 0 ~ 900초) 로 설정이 가능하다.
      • max_message_size: 메시지 하나가 가질 수 있는 컨테츠의 크기를 지정ㅎ나다. 1kb ~ 256kb 까지 설정 가능하다.
      • visibility_timeout_seconds: 메시지가 큐에 노출되는 기간을 지정한다. (0 ~ 43200초) 즉 12시간 가능하며 기본은 30초이다.
      • message_retention_seconds: 메시지에 머무를 시간을 초로 지정한다. 이는 1분 에서 14일까지 가능하며 기본은 4일이다.
      • receive_wait_time_seconds: 메시지 호출이 반환되기 전에 메시지가 도착하기까지 기다리는 시간이며 (롱 폴링) 0 ~ 20초 이며 기본값은 0이다. (즉 즉시 반환이다.)
      • fifo_queue: FIFO queue를 사용할지 여부를 지정한다.
      • content_based_deduplication: FIFO 대기열이 설정된 경우 지정하며, 중복 제거를 활성화 할지 여부를 지정한다.

       

      vars.tf 변수값 확인하기

      variable "SQS_NAME" {
        description = "This is sqs name to be created"
        default = "my-todo2"
      }
      
      variable "DELAY_SEC" {
        description = "대기열의 모슨 메시지 배달이 지연되는 시간 (초) 기본은 0, 0 ~ 900 까지 가능"
        type = number
        default = 0
      }
      
      variable "MAX_MESSAGE_SIZE" {
        description = "메시지가 리젝되기 전에 가질 수 있는 바이트 수, 1024 ~ 262144 바이트까지 가능, 기본값 = 262144"
        type = number
        default = 262144
      }
      
      variable "MESSAGE_RETENTION_SECONDS" {
        description = "SQS가 메시지를 보관하는 시간, 60초 ~ 1209600 (14일), 기본값 345600 (4일)"
        type = number
        default = 345600
      }
      
      variable "RECEIVE_WAIT_TIME_SECONDS" {
        description = "ReceiveMessage 호출이 반환되기 전에 메시지가 도착하기를 기다리는 시간, 0 ~ 20초 사이"
        type = number
        default = 0
      }
      
      variable "VISIBILITY_TIMEOUT_SECONDS" {
        description = "큐에서 가시성 타임아웃, 0 에서 43200 (12 hours)"
        type        = number
        default     = 30
      }
      
      variable "FIFO_QUEUE" {
        description = "FIFO Queue 를 만들지 여부"
        type = bool
        default = false
      }
      
      variable "CONTENT_BASED_DEDUPLICATION" {
        description = "FIFO 큐에서 컨텐츠 기반의 중복 제거를 활성화 할지 여부"
        type        = bool
        default     = false
      }

       

      queue 정책 정보 설정하기

      • 큐를 사용하는 사용자에 대한 권한을 지정한다.
      • 메시지 전송, 메시지 수신을 누가 수행할 수 있는지 지정한다.
      resource "aws_sqs_queue_policy" "my_sqs_to_test_policy" {
        queue_url = aws_sqs_queue.my_todo2.id
      
        policy = <<POLICY
        {
          "Version": "2012-10-17",
          "Id": "sqspolicy",
          "Statement": [
            {
              "Sid": "First",
              "Effect": "Allow",
              "Principal": "*",
              "Action": "sqs:SendMessage",
              "Resource": "${aws_sqs_queue.my_todo2.arn}"
            }
          ]
        }
        POLICY
      }
      • 위 내용은 모두가 메시지에 대해서 전송을 할 수 있다는 의미이다.

       

      출력 설정하기

      • outputs.tf 출력 설정을 수행한다.
      output "sqs_queue_id" {
        description = "SQS URL을 반환한다."
        value = aws_sqs_queue.my_todo2.id
      }
      
      output "sqs_queue_name" {
        description = "SQS Queue 의 이름"
        value = aws_sqs_queue.my_todo2.name
      }

       

       

      실행하기

      • 파일 구성을 했다면 다음과 같이 실행하자.

       

      테라폼 파일 초기화 하기

      terraform init
      Initializing the backend...
      
      Initializing provider plugins...
      - Finding latest version of hashicorp/aws...
      - Installing hashicorp/aws v3.53.0...
      - Installed hashicorp/aws v3.53.0 (self-signed, key ID 34365D9472D7468F)
      
      Partner and community providers are signed by their developers.
      If you'd like to know more about provider signing, you can read about it here:
      https://www.terraform.io/docs/cli/plugins/signing.html
      
      Terraform has created a lock file .terraform.lock.hcl to record the provider
      selections it made above. Include this file in your version control repository
      so that Terraform can guarantee to make the same selections by default when
      you run "terraform init" in the future.
      
      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 디렉토리와 .terraform.lock.hcl 파일이 생성된다.
      • .terraform 디렉토리: 테라폼 생성용 바이너리 파일이 만들어진다.
      • .terraform.lock.hcl: 실행될 테라폼의 해시 값이 생성된다.

       

      생성하기

      terraform apply
      • 위 커맨드를 실행하면 terraform 생성을 직접 수행하게 된다.

       

      An execution plan has been generated and is shown below.
      Resource actions are indicated with the following symbols:
        + create
      
      Terraform will perform the following actions:
      
        # aws_sqs_queue.my_sqs_to_test will be created
        + resource "aws_sqs_queue" "my_sqs_to_test" {
            + arn                               = (known after apply)
            + content_based_deduplication       = false
            + deduplication_scope               = (known after apply)
            + delay_seconds                     = 0
            + fifo_queue                        = false
            + fifo_throughput_limit             = (known after apply)
            + id                                = (known after apply)
            + kms_data_key_reuse_period_seconds = (known after apply)
            + max_message_size                  = 262144
            + message_retention_seconds         = 345600
            + name                              = "my-todo2"
            + name_prefix                       = (known after apply)
            + policy                            = (known after apply)
            + receive_wait_time_seconds         = 0
            + tags_all                          = (known after apply)
            + url                               = (known after apply)
            + visibility_timeout_seconds        = 30
          }
      
        # aws_sqs_queue_policy.my_sqs_to_test_policy will be created
        + resource "aws_sqs_queue_policy" "my_sqs_to_test_policy" {
            + id        = (known after apply)
            + policy    = (known after apply)
            + queue_url = (known after apply)
          }
      
      Plan: 2 to add, 0 to change, 0 to destroy.
      
      Changes to Outputs:
        + sqs_queue_id   = (known after apply)
        + sqs_queue_name = "my-todo2"
      
      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
      
      aws_sqs_queue.my_sqs_to_test: Creating...
      aws_sqs_queue.my_sqs_to_test: Creation complete after 0s [id=https://sqs.ap-northeast-2.amazonaws.com/103946/my-todo2]
      aws_sqs_queue_policy.my_sqs_to_test_policy: Creating...
      aws_sqs_queue_policy.my_sqs_to_test_policy: Creation complete after 0s [id=https://sqs.ap-northeast-2.amazonaws.com/10336/my-todo2]
      
      Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
      
      Outputs:
      
      sqs_queue_id = "https://sqs.ap-northeast-2.amazonaws.com/103346/my-todo2"
      sqs_queue_name = "my-todo2"
      • yes를 입력하고 엔터를 치면 AWS에 SQS가 생성이 된다.

      • 참고로 우리가 outputs.tf 파일에 지정한 출력 정보가 그대로 출력된 것을 확인할 수 있다.

      • 실제 콘솔에 들어가서 살펴보면 방금 생성한 sqs를 확인할 수 있다.

      • terraform.tfstate 파일은 생성된 리소스에 대한 상태 정보를 가지고 있다. 이 정보를 버젼 관리하여 테라폼의 변경을 컨트롤 할 수 있다.

       

      리소스 삭제하기

      • terraformm 은 생성한 리소스에 대한 트래킹을 하기 위한 정보를 가지고 있다.
      • 그러므로 삭제 역시 동일한 디렉토리에서 수행하면 테라폼을 삭제할 수 있다.
      terraform destroy
      • 프롬프트에서 yes를 입력하면 리소스가 삭제된다.
      • 콘솔에서 삭제 여부를 확인해 보자.

      댓글 0

      DEVOTEE를 활성화 시키면
      지금 작성한 댓글에 AI가 댓글을 달아줍니다.

      KIDO 님의 최신 블로그

      더보기

      관련 블로그

      동영상 기고하기