• EnglishEspañol日本語한국어Português
  • 로그인지금 시작하기

이 한글 문서는 사용자의 편의를 위해 기계 번역되었습니다.

영문본과 번역본이 일치하지 않는 경우 영문본이 우선합니다. 보다 자세한 내용은 이 페이지를 방문하시기 바랍니다.

문제 신고

Terraform 모듈 및 원격 저장소 사용

Terraform 은 HashiCorp에서 구축한 널리 사용되는 코드형 인프라 소프트웨어 도구입니다. 이를 사용하여 New Relic 대시보드 및 경고를 포함하여 모든 종류의 인프라 및 서비스를 프로비저닝합니다.

이 가이드에서는 New Relic 구성에서 Terraform 모듈을 사용하는 방법을 배웁니다. 특히 모듈을 생성하고, 데이터를 가져오고, Github에 모듈을 저장하고, Amazon S3에서 원격으로 상태를 관리합니다.

영상에서는 Terraform을 설치하고 New Relic 경고를 설정하는 추가 단계를 검토합니다. Terraform을 시작하는 데 도움이 필요한 경우 New Relic 및 Terraform 시작하기에서는 Terraform을 설치하고 New Relic 경고를 설정하고 알림 채널을 지정하는 방법을 보여줍니다.

시작하기 전에

이 가이드를 사용하려면 New Relic과 Terraform에 대한 기본 지식이 있어야 합니다. 아직 New Relic 오픈 소스 에이전트를 배포하지 않은 경우 애플리케이션에 New Relic을 설치하세요 . 또한 Terraform CLI를 설치합니다.

작업 디렉터리를 초기화하여 시작합니다.

bash
$
mkdir terraform-config && cd terraform-config

이 가이드의 예제를 따르기 위해 함께 제공되는 예제 코드는 GitHub 에서 사용할 수 있습니다.

bash
$
git clone https://github.com/jsbnr/nr-terraform-intro-example.git

Terraform 모듈 생성

Terraform 모듈을 사용하면 Github와 같은 버전 제어를 사용하여 Terraform 구성을 재사용, 공유 및 저장할 수 있습니다. 다음 단계에서는 New Relic 구성을 재사용 가능한 모듈로 이동합니다.

먼저 프로젝트 루트에서 modules 이라는 모듈을 저장할 새 디렉터리를 만듭니다.

bash
$
mkdir modules && cd modules

모듈 디렉터리에서 HostConditions라는 새 모듈에 대한 새 디렉터리를 만들고 main.tf 이라는 새 파일을 만듭니다.

bash
$
mkdir HostConditions && cd HostConditions
$
touch main.tf

루트 프로젝트의 main.tf 파일에서 두 개의 공지 조건을 제거하고 이를 HostConditions 디렉터리의 새 main.tf 파일에 복사합니다.

루트 디렉터리의 main.tf 파일에서 모듈 블록을 사용하여 새 모듈을 호출합니다.

module "HostConditions" {
source = "./modules/HostConditions"
}

구성을 테스트하고 terraform planterraform init 을 실행하십시오.

bash
# Example output
------------------------------------------------------------------------
Initializing modules...
- HostConditions in
Error: Unreadable module directory
Unable to evaluate directory symlink: lstat modules/HostConditions: no such
file or directory
Error: Failed to read module directory
Module directory does not exist or cannot be read.
Error: Unreadable module directory
Unable to evaluate directory symlink: lstat modules/HostConditions: no such
file or directory
Error: Failed to read module directory
Module directory does not exist or cannot be read.

모듈 디렉터리에 공급자 세부 정보가 부족하여 콘솔에 오류가 표시됩니다. 오류를 수정하려면 HostConditions 디렉터리에 루트 공급자.tf의 복사본을 만듭니다.

provider "newrelic" {
account_id = 12345 # Your New Relic account ID
api_key = "NRAK-zzzzzz" # Your New Relic user key
region = "US" # US or EU (defaults to US)
}

구성을 테스트하고 terraform planterraform init 을 실행하십시오.

bash
# Example output
------------------------------------------------------------------------
Error: Reference to undeclared resource
on modules/HostConditions/main.tf line 2, in resource "newrelic_infra_alert_condition"
"cpuhot":
2: policy_id = newrelic_alert_policy.DemoPolicy.id
A managed resource "newrelic_alert_policy" "DemoPolicy" has not been declared
in module.HostConditions.
Error: Reference to undeclared resource
on modules/HostConditions/main.tf line 24, in resource "newrelic_infra_alert_condition"
"highDiskUsage":
24: policy_id = newrelic_alert_policy.DemoPolicy.id
A managed resource "newrelic_alert_policy" "DemoPolicy" has not been declared
in module.HostConditions.

Terraform init는 더 이상 오류를 표시하지 않지만 terraform 계획을 실행하면 여전히 오류가 발생합니다.

오류는 ./modules/HostConditions/provider.tf 에 사용된 정책 ID가 존재하지 않기 때문에 발생합니다. 모듈에 전달하려면 변수가 필요합니다.

변수 만들기

변수는 모듈에 세부 정보를 전달하고 기본값을 설정합니다.

먼저, HostConditions/provider.tf 상단에 새 변수를 만듭니다.

variable "providerId" {}

다음으로 리소스 블록에서 기존 policyId 새 변수로 바꿉니다.

var.policy

모듈에 변수 전달

모듈을 동적으로 만들려면 모듈 리소스 블록을 사용하여 변수를 모듈에 전달합니다.

루트 디렉터리 main.tf 에서 모듈 블록을 업데이트하여 policyId 변수를 추가합니다.

module "HostConditions" {
source = "./modules/HostConditions"
policyId = newrelic_alert_policy.DemoPolicy.id
}

모듈에 변수를 추가한 후 terraform plan 를 실행합니다.

bash
$
terraform plan

이제 더 많은 변수를 추가하고 CPU 위험, CPU 경고 및 디스크 백분율 값을 바꿉니다. 그런 다음 새 변수를 모듈에 전달합니다.

HostConditions/main.tf 에 새 변수를 추가합니다.

variable cpu_warning {}
variable cpu_critical {}
variable diskPercent {}

HostConditons/main.tf 에 추가된 새 변수를 사용하려면 공지 조건을 업데이트하세요.

resource "newrelic_infra_alert_condition" "cpuhot" {
policy_id = var.policyId
name = "CPU hot!"
type = "infra_metric"
event = "SystemSample"
select = "cpuPercent"
comparison = "above"
where = "(hostname LIKE '%myhost%')"
critical {
duration = 5
value = var.cpu_critical
time_function = "all"
}
warning {
duration = 5
value = var.cpu_warning
time_function = "all"
}
}
resource "newrelic_infra_alert_condition" "highDiskUsage" {
policy_id = var.policyId
name = "high disk usage"
type = "infra_metric"
event = "SystemSample"
select = "diskUsedPercent"
comparison = "above"
where = "(hostname LIKE '%myhost%')"
critical {
duration = 5
value = var.diskPercent
time_function = "all"
}
}

모듈에 변수를 추가한 후 terraform plan 를 실행합니다. 누락된 변수 값으로 인해 오류 메시지가 표시됩니다. 값은 모듈 블록에 추가하거나 기본값으로 추가할 수 있습니다.

bash
$
terraform plan

기본값 추가

HostConditions/main.tf 에 기본 변수 값을 추가합니다.

variable cpu_warning { default=80}
variable cpu_critical { default=90}
variable diskPercent { default=60 }

모듈 블록을 사용하여 변수 값 전달

루트 디렉터리 main.tf 에서 모듈 블록을 업데이트하여 cpu_critical, cpu_warningdiskPercentage 변수를 추가합니다.

module "HostConditions" {
source = "./modules/HostConditions"
policyId = newrelic_alert_policy.DemoPolicy.id
cpu_critical = 88
cpu_warning = 78
diskPercentage = 66
}

모듈에 변수를 추가한 후 terraform plan 를 실행합니다.

bash
$
terraform plan

모듈 재사용

이미 존재하는 블루베리 정책에 연결하여 모듈을 재사용할 수 있습니다. 시작하기 전에 뉴켈릭 계정에서 Preexisting Policy 라는 새 공지를 생성하세요.

기존 경고 정책 연결

먼저 루트 main.tf 파일에 데이터 블록을 추가하여 기존 정책을 가져옵니다.

data "newrelic_alert_policy" "ExistingPolicy" {
name = "Preexisting Policy"
}

다음으로 두 번째 모듈 블록 이름 HostConditions2 을 만듭니다. 기존 정책에 공지 조건을 추가합니다.

module "HostConditions2" {
source = "./modules/HostConditions"
policyId = data.newrelic_alert_policy.ExistingPolicy.id
cpu_critical = 87
cpu_warning = 77
diskPercentage = 67
}

terraform init 실행하여 새 모듈을 초기화하고 terraform apply 실행하여 뉴렐릭 계정에 변경 사항을 적용합니다.

terraform 스크립트는 새 경고 정책과 두 가지 조건을 생성하지만 기존 정책에도 경고 조건을 적용합니다.

기존 정책에서 New Relic 계정을 살펴보고 CPU 핫 및 높은 디스크 사용량에 대해 추가된 경고 조건을 확인하십시오.

Github에 모듈 저장

모듈을 만든 후 다른 사람들이 사용할 수 있는 곳에 모듈을 저장하고 싶다면 Github가 그 방법입니다.

새 Github 리포지토리 만들기

먼저 HostModules 디렉터리 내에서 새 Github 리포지터리를 초기화합니다. 커밋을 위해 단계에 main.tfprovider.tf 추가합니다.

bash
$
git add main.tf provider.tf
$
git commit -m "init"

다음으로 새 리포지토리에 제공된 명령을 사용하여 Github에 커밋을 푸시합니다.

bash
$
git remote add origin <repo_url>
$
git branch -M main
$
git push -u origin main

Github에 저장된 모듈 사용

Github 리포지터리를 확인하여 이제 main.tfprovider.tf 이 리포지터리에 있는지 확인하세요. GitHub 리포지터리의 웹 URL을 복사하여 리포지터리를 복제하세요.

GitHub를 HostConditions 의 소스로 사용하여 루트 main.tf 파일을 업데이트합니다.

module "HostConditions" {
source = "git::https://github.com/<your_username>/<your_repo_name>" # Add your repo URL
policyId = newrelic_alert_policy.DemoPolicy.id
cpu_critical = 88
cpu_warning = 78
diskPercentage = 66
}
module "HostConditions2" {
source = "git::https://github.com/<your_username>/<your_repo_name>" # Add your repo URL
policyId = data.newrelic_alert_policy.ExistingPolicy.id
cpu_critical = 87
cpu_warning = 77
diskPercentage = 67
}

terraform init 를 실행하여 새 모듈을 초기화합니다. terraform init 를 실행하면 Terraform이 저장소를 로컬로 복제합니다. 달리다 terraform plan

git repo에 대한 업데이트로 로컬 모듈을 업데이트해야 하는 경우 다음을 실행하십시오. terraform get -update

Amazon S3에서 원격으로 상태 관리

상태 파일은 terraform이 생성된 리소스에 대해 보유하고 있는 표현입니다. 상태 파일은 루트 디렉토리에 있지만 삭제되거나 손상되면 문제가 발생할 수 있습니다. 상태 파일을 원격으로 저장하면 보안이 제공되고 공유 및 원격 액세스가 허용됩니다.

규정의 provider.tf 에서 Amazon S3용 terraform 백앤드 블록을 추가합니다.

terraform {
backend "s3" {
bucket = "<s3_bucket_name>"
key = "<s3_bucket_key>"
region = "<s3_bucket_region>"
}
}

올바른 S3 버킷 세부 정보를 제공하려면 변수가 필요하며 액세스 권한이 필요합니다.

Amazon 계정의 S3 버킷에 대한 액세스 권한을 부여하려면 IAM 사용자를 생성하십시오. IAM 사용자에게 terraform 상태를 저장하는 S3 버킷에 대한 액세스 권한을 부여합니다.

terraform 백엔드 블록에 프로필을 추가합니다.

terraform {
backend "s3" {
bucket = "<s3_bucket_name>"
key = "<s3_bucket_key>"
region = "<s3_bucket_region>"
profile = "<iam_user_profile_name>"
}
}

상태를 Amazon S3에 저장하기 전에 현재 구성을 삭제하여 깨끗한 슬레이트에서 시작합니다.

bash
$
terraform destroy

Terraform을 초기화하고 Terraform init를 실행합니다.

bash
$
terraform init

터미널에서 출력은 S3로 초기화된 백엔드를 보여줍니다. 필요하지 않으므로 로컬 상태를 삭제합니다.

bash
$
rm terraform.*

terraform apply 를 실행하여 Terraform 구성 변경 사항을 적용합니다.

bash
$
terraform apply

상태 파일은 이제 로컬이 아닌 S3에 저장됩니다. S3 버킷을 살펴보고 terraform 상태가 존재하는지 확인합니다.

결론

축하해요! terraform 구성을 보다 유연하게 만들기 위해 모듈을 사용하고 있습니다. New Relic Terraform 제공자 문서를 검토하여 구성을 한 단계 끌어올리는 방법을 알아보세요.

Copyright © 2024 New Relic Inc.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.