Terraform #2

임상규·2023년 11월 15일
1

Terraform

목록 보기
2/3

resource

  • 가상 네트워크나 인스턴스 같은 객체를 표현
  • resource type은 provider에 따라 다름
resource "aws_instance" "web"

➡️ "aws_instance" = resource type / "web" = local name

data

  • terraform 외부에서 정의된 정보 (기본 ami, iam policy id...)
data "aws_ami" "example" {
  most_recent = true
  
  owners = ["self"]
  tags = {
    Name   = "app-server"
    Tested = "true"
  }
}

local-only data

  • terraform 내에서만 작동하는 data source
  • EX)
    • rendering templates
    • reading local files
    • rendering AWS IAM policies
data "aws_iam_policy_document" "example_multiple_condition_keys_and_values" {
  statement {
    actions = [
      "kms:Decrypt",
      "kms:GenerateDataKey"
    ]

    resources = ["*"]

    condition {
      test     = "ForAnyValue:StringEquals"
      variable = "kms:EncryptionContext:service"
      values   = ["pi"]
    }

    condition {
      test     = "ForAnyValue:StringEquals"
      variable = "kms:EncryptionContext:aws:pi:service"
      values   = ["rds"]
    }

    condition {
      test     = "ForAnyValue:StringEquals"
      variable = "kms:EncryptionContext:aws:rds:db-id"
      values   = ["db-AAAAABBBBBCCCCCDDDDDEEEEE", "db-EEEEEDDDDDCCCCCBBBBBAAAAA"]
    }

  }
}
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Action": [
        "kms:GenerateDataKey",
        "kms:Decrypt"
      ],
      "Resource": "*",
      "Condition": {
        "ForAnyValue:StringEquals": {
          "kms:EncryptionContext:aws:pi:service": "rds",
          "kms:EncryptionContext:aws:rds:db-id": [
            "db-AAAAABBBBBCCCCCDDDDDEEEEE",
            "db-EEEEEDDDDDCCCCCBBBBBAAAAA"
          ],
          "kms:EncryptionContext:service": "pi"
        }
      }
    }
  ]
}

module

  • 함께 사용되는 여러개의 리소스에 대한 컨테이너
  • 디렉토리 안에 여러개의 .tf/.tf.json 파일로 구성됨
  • 리소스 설정을 패키징하거나 재사용하기 위한 주요 방법 중 하나
  • 모든 terraform 설정은 적어도 하나의 module로 구성됨 (=root module)
    • child module: root module 내의 다른 module
  • public/private registry를 통해서 선언한 module을 publish or load 가능

source

  • 필수 argument
  • 설정 파일이 포함된 local directory path 또는 download 가능한 remote module
  • module block이 추가/수정/삭제되면 무조건 terraform init을 실행
module "servers" {
  source = "./app-cluster"
  
  
  server = 5
}

version

  • 설치하고자할 module version
module "consul" {
  source = "hashicorp/consul/aws"
  version = "0.0.5"
  
  
  server = 3
}

(input) variable

  • module에 대한 parameter
  • 코드 수정 없이 module에 영향을 줄 수 있는 요소 (변수)
  • arguments

    • defaule: 기본값

    • type: string, number, bool, list, set, map, object, tuple

    • description: 설명

    • validation: 검증 규칙

      variable "image_id" {
        type        = string
        description = "The id of machine image (AMI) to use for the server."
      
      validation {
        condition     = length(var.image_id) > 4 && substr(var.image_id, 0, 4) == "ami-"
        error_message = "The image_id value must be a valid AMI id, starting with \"ami-\"."
    • sensitive: plan, apply 할 때 해당 값을 출력하지 않게 하는 옵션 (개인정보 등 민감한 정보)

    • nullable: null 여부

local

  • 표현식에 할당하는 짧은 이름 (alias)
    locals {
      service_name = "forum"
      owner        = "Community Team"
  • 표현식을 여러번 반복할 때 사용

    locals {
      instance_ids = concat (aws_instance.blue.*.id, aws_instance.green.*.id)
    }
    
    locals {
      common_tag = {
        Service = local.service_name
        Owner   = local.owner
      }
    }

output

  • module이 return 하는 값
  • terraform 설정에 대한 정보를 노출하기 위한 요소
  • 사용 예시
    • child module의 output을 parent module에서 사용
    • terraform apply 이후 root module의 output을 노출
    • remote state를 사용할 때, root module output은
      terraform remote state 명령어를 통해서 접근가능
# main.tf

module "foo" {
  source = "./mod"
}

resource "test_instance" "x" {
  some_attribute = module.foo.a
}

output "out" {
  value     = "xyz"
  sensitive = true
}

# mod/main.tf, our module containing a sensitive output

output "a" {
  value     = "secret"
  sensitive = true
}

값 참조 방식

- resource : <resource type>.<name>
- data : data.<data type>.<name>
- input : var.<name>
- local : local.<name>
- child module output : module.<module name>.<output> 
- workspace : terraform.workspace
- filesystem : path.module, path.root, path.cw`

String Templates

  • interpolation: ${...}
  • directive: %{...}
profile
Cloud Engineer / DevOps Engineer

0개의 댓글