# Terraform을 사용한 AWS S3 로그 소스 관리

## 개요

Panther S3 로그 소스를 Terraform에서 완전히 정의할 수 있습니다. 즉, AWS에서 S3 버킷과 관련 인프라를 생성한 다음 이를 Panther 인스턴스에 온보딩할 수 있다는 의미입니다. Panther는 [Terraform provider](https://registry.terraform.io/providers/panther-labs/panther/latest).

S3 로그 소스를 생성하는 다른 방법에는 다음이 포함됩니다. [Panther API를 사용하여](/ko/panther/api/graphql/log-source.md#creating-an-s3-log-source) 직접 수행하는 방법과 [Panther Console에서 수동으로 생성하는 방법이 있습니다.](/ko/data-onboarding/data-transports/aws/s3.md).

## Terraform에서 Panther S3 로그 소스를 정의하는 방법

다음 섹션에서는 HashiCorp Configuration Language(HCL)에서 S3 로그 소스를 정의하는 방법을 설명합니다. AWS와 Panther 인프라를 모두 HCL로 정의하게 됩니다.

{% hint style="warning" %}
Panther에서 처음 생성하는 로그 소스는 반드시 Panther Console에서 수행해야 합니다. Terraform을 사용하여 첫 Panther 로그 소스를 설정하면, 다음에 자세히 설명된 "pending confirmation" 문제가 발생할 수 있습니다. [이 Knowledge Base 문서](https://help.panther.com/articles/2327494518-why-is-my-sns-topic-stuck-in-a-pending-confirmation-state-for-the-sqs-confirmation-for-panther).
{% endhint %}

### 사전 요구 사항

* 시작하기 전에 다음 권한이 있는 API URL과 토큰이 있는지 확인하세요. `Manage Log Sources` 권한. 이는 다음을 완료하는 데 필요합니다. [단계 2](#step-2-provide-values-for-the-defined-variables).
  * 필요한 경우 다음을 따르세요. [Panther Console에서 API 토큰을 생성하는 방법에 대한 이 지침](/ko/panther/api.md#how-to-create-a-panther-api-token).

### 1단계: 변수 정의

* 다음 AWS 및 Panther 변수가 포함된 `variables.tf` 파일을 생성합니다:

```hcl
variable "aws_account_id" {
  type        = string
  description = "템플릿이 배포되는 AWS 계정 ID"
}

variable "panther_aws_account_id" {
  type        = string
  description = "Panther 인스턴스의 AWS 계정 ID"
}

variable "panther_aws_region" {
  type = string
  default = "us-east-1"
  description = "Panther 인스턴스가 배포된 리전"
}

variable "panther_aws_partition" {
  type        = string
  default     = "aws"
  description = "Panther 백엔드를 실행하는 계정의 AWS 파티션 예: aws, aws-cn, 또는 aws-us-gov"
}

variable "s3_bucket_name" {
  type        = string
  description = "온보딩할 S3 버킷 이름"
}

variable "log_source_name" {
  type = string
  description = "Panther에 생성할 로그 소스의 이름"
}

variable "panther_api_token" {
  type = string
}

variable "panther_api_url" {
  type = string
}
```

### 2단계: 정의한 변수에 값 제공

* 다음과 같은 `*.tfvars` 파일을 추가하여 1단계에서 정의한 변수에 값을 할당합니다. 이 섹션을 완료하려면 [사전 요구 사항 섹션](#prerequisite).
  * 에 설명된 API URL과 토큰이 필요합니다. `panther_api_url` 값은 루트 API URL이어야 합니다. 이는 다음 중 하나입니다:
    * 다음의 [GraphQL API URL](/ko/panther/api/graphql.md#step-1-identify-your-panther-graphql-api-url) 에서 `/public/graphql` 접미사를 제거한 것
    * 다음의 [REST API URL](/ko/panther/api/rest.md#step-1-identify-your-panther-rest-api-url) 그대로 사용(REST URL에는 루트 URL 뒤에 접미사가 없습니다)

```hcl
aws_account_id         = "XXXXXXXXXX"
panther_aws_account_id = "XXXXXXXXXX"
panther_aws_region     = "us-east-1"
panther_aws_partition  = "aws"
s3_bucket_name         = "test-bucket"
log_source_name        = "test-integration"
panther_api_token      = "XXXXXXXXXX"
panther_api_url        = "https://your-panther-url/v1"
```

### 3단계: Terraform provider 정의

* 다음과 같이 두 가지를 모두 포함합니다. [AWS](https://registry.terraform.io/providers/hashicorp/aws/latest/docs) 및 [Panther](https://registry.terraform.io/providers/panther-labs/panther/latest) Terraform provider:

```hcl
terraform {
  required_providers {
    panther = {
      source = "panther-labs/panther"
    }
    aws = {
      source  = "hashicorp/aws"
    }
  }
}
```

### 4단계: AWS 인프라 정의

AWS에서 S3 버킷과 SNS 토픽을 생성해야 합니다. S3 버킷에서 로그를 수집하려면, 버킷은 객체 생성 시 알림을 SNS 토픽에 기록해야 합니다. 이 토픽에 대한 구독은 객체 정보를 Panther의 입력 대기열로 전달하는 데 필요합니다.

<figure><img src="/files/6fb380032d8a25446bcb30c5ba4e49d4e2a354dd" alt="An AWS infrastructure diagram is shown. A Log Source Bucket is pointing to a Panther Notifications Topic, which points to a Panther Input Notifications Queue" width="563"><figcaption></figcaption></figure>

#### S3 버킷 정의

다음 HCL 구성은 S3 버킷과 해당 콘텐츠에 액세스하기 위한 연결된 IAM 역할을 정의합니다. 이 역할은 들어오는 로그를 읽기 위해 Panther 인스턴스가 맡게 되므로 S3 버킷에 대한 읽기 권한이 필요합니다.

```hcl
resource "aws_s3_bucket" "log_bucket" {
  bucket = var.s3_bucket_name
}

resource "aws_iam_role" "log_processing_role" {
  name = "PantherLogProcessingRole-${var.s3_bucket_name}"

  # 엔터티가 역할을 맡도록 허용하는 권한 정책
  assume_role_policy = jsonencode({
    Version : "2012-10-17",
    Statement : [
      {
        Action : "sts:AssumeRole",
        Effect : "Allow",
        Principal : {
          AWS : "arn:${var.aws_partition}:iam::${var.panther_aws_account_id}:root"
        }
        Condition : {
          Bool : { "aws:SecureTransport" : true }
        }
      }
    ]
  })

  tags = {
    Application = "Panther"
  }
}


# S3 데이터 읽기를 위한 IAM 역할 인라인 정책 제공
resource "aws_iam_role_policy" "read_data_policy" {
  name = "ReadData"
  

  role = aws_iam_role.log_processing_role.id
  policy = jsonencode({
    Version : "2012-10-17",
    Statement : [
      {
        Effect : "Allow",
        Action : [
          "s3:GetBucketLocation",
          "s3:ListBucket",
        ],
        Resource : "arn:${var.aws_partition}:s3:::${aws_s3_bucket.log_bucket.bucket}"
      },
      {
        Effect : "Allow",
        Action : "s3:GetObject",
        Resource : "arn:${var.aws_partition}:s3:::${aws_s3_bucket.log_bucket.bucket}/*"
    }, ]
  })
}


```

#### SNS 토픽 정의

다음 HCL 구성은 S3 버킷 알림을 활성화하기 위한 SNS 토픽과 관련 정책을 생성합니다. 또한 메시지를 Panther의 입력 데이터 알림 큐로 전달하는 구독도 생성합니다.

동일한 SNS 토픽은 여러 S3 버킷 통합에 사용할 수 있습니다.

```hcl
resource "aws_sns_topic" "panther_notifications_topic" {
  name = "panther-notifications-topic"
}

resource "aws_sns_topic_policy" "default" {
  arn = aws_sns_topic.panther_notifications_topic.arn

  policy = data.aws_iam_policy_document.panther_notifications_topic_policy.json
}

data "aws_iam_policy_document" "panther_notifications_topic_policy" {
  statement {
    sid = "AllowS3EventNotifications"
    actions = [
      "sns:Publish",
    ]
    effect = "Allow"
    principals {
      type = "Service"
      identifiers = ["s3.amazonaws.com"]
    }
    resources = [
      aws_sns_topic.panther_notifications_topic.arn,
    ]
  }
  statement {
    sid = "AllowCloudTrailNotification"
    actions = [
      "sns:Publish",
    ]
    effect = "Allow"
    principals {
      type = "Service"
      identifiers = ["cloudtrail.amazonaws.com"]
    }
    resources = [
      aws_sns_topic.panther_notifications_topic.arn,
    ]
  }
  statement {
    sid = "AllowSubscriptionToPanther"
    actions = [
      "sns:Subscribe",
    ]
    effect = "Allow"
    principals {
      type = "AWS"
      identifiers = ["arn:${var.panther_aws_partition}:iam::${var.panther_aws_account_id}:root"]
    }
    resources = [
      aws_sns_topic.panther_notifications_topic.arn,
    ]
  }
}

resource "aws_s3_bucket_notification" "panther_event_notifications" {
  bucket = aws_s3_bucket.log_bucket.id

  topic {
    topic_arn = aws_sns_topic.panther_notifications_topic.arn
    events        = ["s3:ObjectCreated:*"]
  }
}

resource "aws_sns_topic_subscription" "panther_notifications_subscription" {
  topic_arn = aws_sns_topic.panther_notifications_topic.arn
  protocol  = "sqs"
  endpoint  = "arn:${var.panther_aws_partition}:sqs:${var.panther_aws_region}:${var.panther_aws_account_id}:panther-input-data-notifications-queue"
  raw_message_delivery = false
}

```

### 5단계: Panther S3 로그 소스 정의

다음 HCL 구성은 Panther에서 S3 로그 소스를 정의합니다.

{% hint style="info" %}
다음을 참고하세요. `panther_managed_bucket_notifications_enabled` 가 `false`로 설정되어 있습니다. 이는 이 로그 소스와 관련된 모든 인프라가 외부에서, 이 경우 Terraform을 통해, 관리되고 있음을 의미합니다.
{% endhint %}

```hcl
provider "panther" {
  token = var.panther_api_token
  url   = var.panther_api_url
}

resource "panther_s3_source" "demo_source" {
  aws_account_id                          = var.aws_account_id
  name                                    = var.log_source_name
  log_processing_role_arn                 = aws_iam_role.log_processing_role.arn
  log_stream_type                         = "JSON"
  panther_managed_bucket_notifications_enabled = false
  bucket_name                             = aws_s3_bucket.log_bucket.bucket
  prefix_log_types = [{
    excluded_prefixes = []
    log_types         = ["AWS.CloudTrail"]
    prefix            = ""
  }]
}
```

### 6단계: 드롭오프 알람 구성(선택 사항)

로그 소스가 데이터 수신을 중지할 때 알러트를 트리거하려면 다음을 추가하세요. `panther_log_source_alarm` 위에서 생성한 S3 소스를 가리키는 리소스:

```hcl
resource "panther_log_source_alarm" "demo_alarm" {
  source_id         = panther_s3_source.demo_source.id
  type              = "SOURCE_NO_DATA"
  minutes_threshold = 60
}
```

전체 인수 참조와 가져오기 구문은 다음을 참조하세요. [Terraform으로 로그 소스 알람 관리](/ko/panther/terraform/log-source-alarms.md).


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.panther.com/ko/panther/terraform/s3.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
