• English日本語한국어
  • 로그인지금 시작하기

사용자의 편의를 위해 제공되는 기계 번역입니다.

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

문제 신고

Terragrunt를 사용하여 여러 환경 관리

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

Terragrunt 는 다음을 위한 추가 도구를 제공하는 Terraform 주변의 얇은 래퍼입니다.

  • 반복 줄이기
  • 여러 Terraform 모듈 작업
  • 원격 상태 관리

이 가이드에서는 Terragrunt를 사용하여 다음을 수행합니다.

  • Terraform 구성 생성
  • 파일 만들기
  • 여러 환경 관리

시작하기 전에

이 가이드를 사용하려면 New Relic과 Terraform에 대한 기본 지식이 있어야 합니다.

아직 하지 않은 경우:

이 가이드의 예제를 따르려면 GitHub 에서 예제 코드를 찾을 수 있습니다.

구성 만들기

Terragrunt는 Terraform 구성을 위한 추가 도구를 제공합니다. 여기에서 Terragrunt, Terraform 및 New Relic을 사용하여 구성을 만듭니다.

작업공간 초기화:

bash
$
mkdir terragrunt-config && cd terragrunt-config

새 폴더에서 terragrunt.hcl 파일을 만듭니다.

bash
$
touch terragrunt.hcl

다음으로 dev 라는 하위 폴더가 있는 환경 폴더를 만듭니다.

bash
$
mkdir -p environments/dev

그런 다음 main.tfprovider.tf 파일이 있는 src 폴더를 만듭니다.

bash
$
mkdir src
$
touch src/main.tf
$
touch src/provider.tf

main.tf 에서 Terraform 리소스를 구성하고 provider.tf에서 공급자 를 구성합니다.

src/provider.tf 에서, New Relic 공급자 를 구성합니다.

terraform {
required_version = "~> 0.14.3"
required_providers {
newrelic = {
source = "newrelic/newrelic"
version = "~> 2.14.0"
}
}
}

src/main.tf 에서, DemoPolicy 라는 New Relic 알림 정책을 추가합니다.

resource "newrelic_alert_policy" "DemoPolicy" {
name = "My Demo Policy"
}

environment/dev 에서 terragrunt.hcl 파일을 생성합니다:

bash
$
touch environments/dev/terragrunt.hcl

여기에 다음 include 문을 추가합니다.

include {
path = find_in_parent_folders()
}

이것은 Terragrunt가 .hcl을 사용하도록 지시합니다. 상위 폴더에서 찾은 구성 파일.

terraform 블록을 추가하여 Terragrunt에 소스 참조를 제공합니다.

include {
path = find_in_parent_folders()
}
terraform {
source = "../../src"
}

src/provider.tf 에서, API 키, 계정 ID 및 리전으로 New Relic 공급자를 구성합니다.

terraform {
required_version = "~> 0.14.3"
required_providers {
newrelic = {
source = "newrelic/newrelic"
version = "~> 2.14.0"
}
}
}
variable "newrelic_personal_apikey" {}
variable "newrelic_account_id" {}
variable "newrelic_region" {}
provider "newrelic" {
account_id = var.newrelic_account_id
api_key = var.newrelic_personal_apikey
region = var.newrelic_region
}

변수를 사용하여 구성을 동적으로 유지합니다.

environment/dev 에서 terragrunt를 초기화합니다:

bash
$
terragrunt init

그러면 환경 변수를 포함하여 약간의 컨텍스트가 설정되고 terraform init 가 실행됩니다.

bash
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.
[terragrunt] [/workspace/terragrunt-config/environments/dev] 2021/02/02 13:30:31 Copying lock file [output] from /workspace/terragrunt-config/environments/dev/.terragrunt-cache/e-PoBgWhdv3v8QGOtDQxS_WeYu4/
69zjIFUfApJiUt8gFmi-6-dcPe8/.terraform.lock.hcl to /workspace/terragrunt-config/environments/dev

environment/dev/terragrunt.hcl 에서 inputs 블록을 추가하여 New Relic 계정 변수에 대한 값을 제공합니다.

inputs = {
newrelic_personal_apikey = "NRAK-***" # Your New Relic account ID
newrelic_account_id = "12345" # Your New Relic account ID
newrelic_region = "US" # US or EU (defaults to US)
}

이제 terragrunt plan 를 실행합니다.

bash
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:
# newrelic_alert_policy.DemoPolicy will be created
+ resource "newrelic_alert_policy" "DemoPolicy" {
+ account_id = (known after apply)
+ id = (known after apply)
+ incident_preference = "PER_POLICY"
+ name = "My Demo Policy"
}
Plan: 1 to add, 0 to change, 0 to destroy.
------------------------------------------------------------------------
Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.

Terragrunt는 inputs 블록의 값을 제공합니다.

terragrunt apply 실행:

bash
$
terragrunt apply

이제 데모 정책이 New Relic 계정에 있습니다.

구성에 추가

이제 기본 New Relic 구성을 생성했으므로 New Relic 및 Terraform 시작하기Terraform 모듈 가이드의 구성을 추가하세요.

이 가이드를 아직 수행하지 않은 경우 Terragrunt 소개 Github 리포지토리 에서 해당 구성을 복사할 수 있습니다.

src/main.tf 에서, 알림 채널의 이메일 주소를 원하는 이메일 주소로 업데이트합니다.

resource "newrelic_alert_policy" "DemoPolicy" {
name = "My Demo Policy"
}
resource "newrelic_alert_channel" "DemoChannel" {
name = "My Demo Channel"
type = "email"
config {
recipients = "your@email_address.com"
include_json_attachment = "1"
}
}
resource "newrelic_alert_policy_channel" "ChannelSubs" {
policy_id = newrelic_alert_policy.DemoPolicy.id
channel_ids = [
newrelic_alert_channel.DemoChannel.id
]
}
module "HostConditions" {
source = "git::https://github.com/jsbnr/demo-terraform.git"
policyId = newrelic_alert_policy.DemoPolicy.id
cpu_critical = 88
cpu_warning = 78
diskPercent = 68
}

여기에서 New Relic 알림 채널을 추가하고 알림 채널에 대한 데모 정책을 구독하고 Github에서 호스팅되는 모듈을 추가했습니다.

terragrunt init 를 실행한 다음 terragrunt apply 을 실행합니다.

bash
$
terragrunt init
$
terragrunt apply

Terraform이 처리를 완료하면 경고 정책에 두 가지 조건과 하나의 경고 채널이 있습니다.

환경을 Terragrunt 변수로 사용

Terragrunt를 사용하면 생성 중인 데이터의 이름에 실행 중인 환경의 이름을 추가하여 New Relic에서 리소스를 더 쉽게 식별할 수 있습니다.

루트 terragrunt.hcl 파일에서 env_name 에 대한 입력을 만듭니다.

inputs = {
env_name = "develop"
}

src/main.tf 에서, 파일에 env_name 라는 새 변수를 추가합니다.

variable "env_name" {}

알림 정책 및 알림 채널 리소스 블록에 새 env_name 변수를 추가합니다.

resource "newrelic_alert_policy" "DemoPolicy" {
name = "${var.env_name}: My Demo Policy"
}
resource "newrelic_alert_channel" "DemoChannel" {
name = "${env_name}: My Demo Channel"
type = "email"
config {
recipients = "your@email_address.com"
include_json_attachment = "1"
}
}

terragrunt plan 를 실행하여 정책 이름에 추가된 환경 변수를 확인합니다.

bash
# newrelic_alert_policy.DemoPolicy will be updated in-place
~ resource "newrelic_alert_policy" "DemoPolicy" {
id = "1216533"
~ name = "My Demo Policy" -> "develop: My Demo Policy"
# (2 unchanged attributes hidden)
}
# newrelic_alert_policy_channel.ChannelSubs must be replaced
-/+ resource "newrelic_alert_policy_channel" "ChannelSubs" {
~ channel_ids = [
- 4737437,
] -> (known after apply) # forces replacement
~ id = "1216533:4737437" -> (known after apply)
# (1 unchanged attribute hidden)
}

여기에서 terragrunt.hcl 에 환경을 하드코딩했습니다. 이를 보다 동적으로 만들려면 terragrunt 내장 함수를 사용하여 환경을 가져오십시오.

루트 terragrunt.hcl 파일에서 path_relative_to_include() 를 사용하도록 입력을 업데이트하고 값을 env_name 변수로 전달합니다.

inputs = {
env_name = path_relative_to_include()
}

terragrunt plan 실행:

bash
# newrelic_alert_policy.DemoPolicy will be updated in-place
~ resource "newrelic_alert_policy" "DemoPolicy" {
id = "1216533"
~ name = "My Demo Policy" -> "environments/dev: My Demo Policy"
# (2 unchanged attributes hidden)
}
# newrelic_alert_policy_channel.ChannelSubs must be replaced
-/+ resource "newrelic_alert_policy_channel" "ChannelSubs" {
~ channel_ids = [
- 4737437,
] -> (known after apply) # forces replacement
~ id = "1216533:4737437" -> (known after apply)
# (1 unchanged attribute hidden)
}
Plan: 2 to add, 1 to change, 2 to destroy.

env_name 변수에는 전체 ./environments/dev/ 경로가 있습니다. 대신 "dev" 부분만 포함하려고 합니다.

terragrunt.hcl 을 업데이트하여 env_name 에서 "environements/"를 제거합니다.

locals {
env_name = replace(path_relative_to_include(), "environments/", "")
}
inputs = {
env_name = local.env_name
}

여기에서 locals 블록을 추가하여 로컬 변수를 생성하고 내장된 replace 함수를 사용하여 상대 경로의 불필요한 부분을 제거했습니다. 그런 다음 로컬 변수를 사용하도록 inputs 블록을 업데이트했습니다.

terragrunt plan 실행:

bash
# newrelic_alert_policy.DemoPolicy will be updated in-place
~ resource "newrelic_alert_policy" "DemoPolicy" {
id = "1216533"
~ name = "My Demo Policy" -> "dev: My Demo Policy"
# (2 unchanged attributes hidden)
}
# newrelic_alert_policy_channel.ChannelSubs must be replaced
-/+ resource "newrelic_alert_policy_channel" "ChannelSubs" {
~ channel_ids = [
- 4737437,
] -> (known after apply) # forces replacement
~ id = "1216533:4737437" -> (known after apply)
# (1 unchanged attribute hidden)
}
Plan: 2 to add, 1 to change, 2 to destroy.

새 정책 이름은 "dev: My Demo Policy"입니다.

terragrunt apply 를 실행하여 구성을 업데이트합니다.

bash
$
terragrunt apply

상태를 원격 저장소로 이동

현재 상태 파일은 로컬입니다. 이제 Terraform 구성을 업데이트하여 Amazon S3에 저장합니다.

Terragrunt를 사용하면 여러 환경을 구성할 수 있으므로 서로 덮어쓰지 않도록 상태 파일을 자체 S3 버킷에 저장해야 합니다.

개발 상태 파일용 S3 버킷을 생성 합니다.

루트 terragrunt.hcl 에서 S3에서 파일을 배치할 위치를 Terragrunt에 알려주는 remote_state 블록을 추가합니다.

remote_state {
backend = "s3"
generate = {
path = "backend.tf"
if_exists = "overwrite_terragrunt"
}
config = {
bucket = "YOUR_S3_BUCKET_NAME" # Amazon S3 bucket required
key = "envs/${local.env_name}/terraform.tfstate"
region = "us-east-1"
encrypt = true
profile = "YOUR_PROFILE_NAME" # Profile name required
}
}

여기에서 버킷 이름, 리전, 암호화 및 프로필을 지정하는 원격 상태 구성을 정의했습니다. 자리 표시자 값을 실제 값으로 바꿔야 합니다. key 의 경우 이전에 만든 로컬 env_name 을 사용하여 상태 파일의 환경을 동적으로 설정했습니다. 마지막으로 Terragrunt에게 버킷에 backend.tf 라는 새 파일을 생성하도록 지시했습니다.

terragrunt plan 실행:

bash
$
terragrunt plan

버킷에 envs라는 폴더가 표시됩니다. 내부에는 terraform.tfstate 파일이 포함된 devs 라는 폴더가 있습니다.

envs/dev 내부에는 terragrunt-cache 라는 숨겨진 폴더가 있습니다. 그 안에는 Terragrunt가 생성한 backend.tf 파일이 있습니다.

새로운 환경 만들기

이제 개발 환경을 구성했으므로 대부분의 작업을 재사용하는 다른 환경을 만듭니다.

환경 에서 nonprod 라는 폴더를 만듭니다. 그 안에 terragrunt.hcl 이라는 파일을 만듭니다.

bash
$
mkdir nonprod && cd nonprod
$
touch terragrunt.hcl

environment/nonprod/terragrunt.hcl 에서 environment/dev/terragrunt.hcl 의 구성을 복사합니다.

include {
path= find_in_parent_folders()
}
terraform {
source = "../../src"
}
inputs = {
newrelic_personal_apikey = "NRAK-***" # Your New Relic account ID
newrelic_account_id = "12345" # Your New Relic account ID
newrelic_region = "US" # US or EU (defaults to US)
}

비프로덕션 환경에 다른 계정을 사용하는 경우 새 계정 ID, API 키 및 리전으로 inputs 를 업데이트하세요.

nonprod 내부에서 terragrunt initterragrunt apply 을 실행합니다.

bash
$
terragrunt init
$
terragrunt apply

Terraform은 "nonprod:"라는 접두사가 붙은 새로운 리소스 세트를 생성합니다.

이제 dev와 nonprod라는 두 가지 환경을 만들었지만 이름을 제외하고는 동일합니다.

src/main.tf 에서, 호스트 조건 모듈에 대한 새 변수를 추가합니다.

variable "cpu_critical" {default = 89}
variable "cpu_warningl" {default = 79}
variable "diskPercentage" {default = 69}

이와 같은 변수를 사용하면 구성이 더욱 동적으로 됩니다.

cpu_critical , cpu_warningdiskPercentage 변수를 사용하도록 HostConditions 를 업데이트합니다.

module "HostConditions" {
source = "git::https://github.com/jsbnr/demo-terraform.git"
policyId = newrelic_alert_policy.DemoPolicy.id
cpu_critical = var.cpu_critical
cpu_warning = var.cpu_warninig
diskPercent = var.dskPercentage
}

terragrunt plan 실행:

bash
$
terragrunt plan

이제 HostConditions 값에 변수 기본값이 포함됩니다.

nonprod/terragrunt.hcl 에서, 변수에 대한 값을 추가하십시오.

inputs = {
newrelic_personal_apikey = "NRAK-***" # Your New Relic account ID
newrelic_account_id = "12345" # Your New Relic account ID
newrelic_region = "US" # US or EU (defaults to US)
cpu_critical = 50
cpu_warninig = 40
diskPercentage = 98
}

이렇게 하면 값이 환경 구성으로 전달됩니다.

terragrunt apply 실행:

bash
$
terragrunt apply

New Relic 계정에는 비프로덕션 관련 구성이 포함된 새 정책이 있습니다.

결론

축하합니다! Terragrunt를 사용하여 New Relic 구성을 생성하고 여러 환경을 관리했습니다. Terragrunt 소개 예제 , New Relic Terraform 제공자 문서Terragrunt 빠른 시작 을 검토하여 구성을 한 단계 끌어올리는 방법을 알아보세요.

Copyright © 2024 New Relic Inc.

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