본문 바로가기
공부/IaC

[Terraform/AWS] EC2를 Directory Service에 Seamlessly하게 join시키기

by haejang 2023. 1. 16.
728x90
728x90

 

 

콘솔에서 진행 시엔 적절한 EC2 Role과 Directory Service를 지정해주면 된다.

그러나 API로는 EC2 생성 시 Directory Service를 연결해주는 옵션이 없고, SSM Document를 사용해야 한다.

 

locals {
  domain = "honglab.com"
  
  ec2role_policies = [
    "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore",
    "arn:aws:iam::aws:policy/AmazonSSMDirectoryServiceAccess",
  ]
}

## Directory Service
resource "aws_directory_service_directory" "this" {
  name = local.domain
  ## 필요한 정보들 입력
}

## Join시킬 EC2
resource "aws_instance" "this" {
  ec2_role = aws_iam_role.this
  ## 필요한 정보들 입력
}

## EC2에 붙일 Role
resource "aws_iam_role" "this" {
  name = "ADJoin"
  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action = "sts:AssumeRole"
        Effect = "Allow"
        Principal = {
          Service = "ec2.amazonaws.com"
        }
      },
    ]
  })
}

## EC2에 붙일 Role에 Managed Policy Attach
resource "aws_iam_role_policy_attachment" "this" {
  for_each   = toset(local.ec2role_policies)
  role       = aws_iam_role.this.name
  policy_arn = each.value
}

## Domain에 Join시키는 SSM Document 생성
resource "aws_ssm_document" "this" {
  name          = "${local.domain}_Join"
  document_type = "Command"
  content       = <<DOC
{
    "schemaVersion": "1.0",
    "description": "Automatic Domain Join Configuration",
    "runtimeConfig": {
        "aws:domainJoin": {
            "properties": {
                "directoryId": "${aws_directory_service_directory.this.id}",
                "directoryName": "${local.domain}",
                "dnsIpAddresses": ${jsonencode(aws_directory_service_directory.this.dns_ip_addresses)}
            }
        }
    }
}
DOC
}

## EC2에 SSM Document 적용
resource "aws_ssm_association" "this" {
  name = aws_ssm_document.this.name

  targets {
    key    = "InstanceIds"
    values = [aws_instance.this.id]
  }
}

 

 

EC2랑 Directory Service 리소스블럭에 대한 건 본 글의 목적에 벗어나므로 생략했다.

 

 

 

 

 

 

728x90
728x90

댓글