주요 커맨드
기본적인 커맨드를 익히기에 앞서 실습 환경 구성.
$ mkdir '02_command'
$ vi 02_command/main.tf
resource "local_file" "abc" {
content = "abc!"
filename = "${path.module}/abc.txt"
}
init
terraform init 명령은 테라폼 구성 파일이 있는 작업 디렉토리를 초기화하는 명령어다. 테라폼에서는 이 init 명령어를 실행하는 디렉토리를 루트 모듈이라고 칭한다. 테라폼을 사용하기에 앞서 최초이자 필수적으로 실행되는 명령어이다. 테라폼 코드를 기반으로 테라폼 구성에서 필요한 의존성을 읽고, 실행에 필요한 라이브러리 등을 다운로드한다.
$ terraform init
Initializing the backend...
Initializing provider plugins...
- Finding latest version of hashicorp/local...
- Installing hashicorp/local v2.7.0...
- Installed hashicorp/local v2.7.0 (signed by HashiCorp)
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!
해당 명령어를 실행하면 루트 모듈에 .terraform.lock.hcl 파일이 생성된다.
$ cat .terraform.lock.hcl
# This file is maintained automatically by "terraform init".
# Manual edits may be lost in future updates.
provider "registry.terraform.io/hashicorp/local" {
version = "2.7.0"
hashes = [
"h1:2RYa3j7m/0WmET2fqotY4CHxE1Hpk0fgn47/126l+Og=",
"zh:261fec71bca13e0a7812dc0d8ae9af2b4326b24d9b2e9beab3d2400fab5c5f9a",
"zh:308da3b5376a9ede815042deec5af1050ec96a5a5410a2206ae847d82070a23e",
"zh:3d056924c420464dc8aba10e1915956b2e5c4d55b11ffff79aa8be563fbfe298",
"zh:643256547b155459c45e0a3e8aab0570db59923c68daf2086be63c444c8c445b",
"zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3",
"zh:7aa4d0b853f84205e8cf79f30c9b2c562afbfa63592f7231b6637e5d7a6b5b27",
"zh:7dc251bbc487d58a6ab7f5b07ec9edc630edb45d89b761dba28e0e2ba6b1c11f",
"zh:7ee0ca546cd065030039168d780a15cbbf1765a4c70cd56d394734ab112c93da",
"zh:b1d5d80abb1906e6c6b3685a52a0192b4ca6525fe090881c64ec6f67794b1300",
"zh:d81ea9856d61db3148a4fc6c375bf387a721d78fc1fea7a8823a027272a47a78",
"zh:df0a1f0afc947b8bfc88617c1ad07a689ce3bd1a29fd97318392e6bdd32b230b",
"zh:dfbcad800240e0c68c43e0866f2a751cff09777375ec701918881acf67a268da",
]
}
이 파일에는 작업 당시의 provider와 테라폼 버전 등의 dependancy가 명기되며 작업 시에 이 파일을 참조하게 된다.
validate
테라폼 구성파일의 유효성을 점검하는 명령어. 코드적인 유효성만 점검한다.
-json 옵션을 활용하면 json 형식으로 출력할 수도 있다.
$ terraform validate
Success! The configuration is valid.
$ terraform validate -json
{
"format_version": "1.0",
"valid": true,
"error_count": 0,
"warning_count": 0,
"diagnostics": []
}
$ terraform validate -json | jq -r .valid
true
plan & apply
plan 명령은 적용할 인프라 변경 사항의 실행 계획을 생성한다. plan 명령은 적용 전 검토하는데 이용한다.
apply는 계획을 기반으로 작업을 실행한다. plan이 없이 apply를 한다면 우선 새 실행 계획을 자동으로 생성하고,
해당 계획을 적용여부를 묻게된다.
$ terraform plan
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# local_file.abc will be created
+ resource "local_file" "abc" {
+ content = "abc!"
+ content_base64sha256 = (known after apply)
+ content_base64sha512 = (known after apply)
+ content_md5 = (known after apply)
+ content_sha1 = (known after apply)
+ content_sha256 = (known after apply)
+ content_sha512 = (known after apply)
+ directory_permission = "0777"
+ file_permission = "0777"
+ filename = "./abc.txt"
+ id = (known after apply)
}
Plan: 1 to add, 0 to change, 0 to destroy.
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform apply" now.
위처럼 plan을 실행했을때, 적용될 사항들이 출력되며 하단에는 최종 결과를 요약하여 표시한다. 현재는 이전에 생성한 리소스가 없으므로 +로만 표시가 된다. 또한 마찬가지로 변경과 삭제되는 사항이 없기 때문에 add만 1이 표시되었다.
-detailed-exitcode 옵션을 이용하면 plan의 결과를 환경변수로 추출할 수 있다.
$ terraform plan -detailed-exitcode
...
$ echo $?
2
0: 변경사항이 없는 성공 / 1: error 있음 / 2: 변경사항이 있는 성공
-out =filename 옵션으로 plan 명령의 결과를 기록할 수 있고, 후에 apply 명령에서 해당 파일(계획)을 가지고 적용할 수 있다.
terraform plan 명령어로 task를 검토하고, 특이 사항이 없으면 apply를 입력하여 작업을 실행한다.
$ terraform apply
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# local_file.abc will be created
+ resource "local_file" "abc" {
+ content = "abc!"
+ content_base64sha256 = (known after apply)
생략
Plan: 1 to add, 0 to change, 0 to destroy.
local_file.abc: Creating...
local_file.abc: Creation complete after 0s [id=5678fb68a642f3c6c8004c1bdc21e7142087287b]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
-replace: 테라폼은 ansible과 마찬가지로 멱등성을 가지기 때문에, 변화없는 동일한 구성에 대해서 반복 작업을 수행하지 않는다. 하지만 필요에 의해서 해당 리소스를 다시 생성 해야하는 경우에 -replace 옵션을 이용할 수 있다.
destroy
테라폼의 모든 개체를 제거하는 명령이다. destroy 명령도 plan과 apply의 관계와 같이 계획과 실행이 동반되어야 한다.
$ terraform destroy
local_file.abc: Refreshing state... [id=5678fb68a642f3c6c8004c1bdc21e7142087287b]
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
- destroy
Terraform will perform the following actions:
# local_file.abc will be destroyed
- resource "local_file" "abc" {
- content = "abc!" -> null
- content_base64sha256 = "U+Dv8yBGJvPiVspjZXLXzN+OtaGQyd76P6VnvGOGa3Y=" -> null
생략
Plan: 0 to add, 0 to change, 1 to destroy.
local_file.abc: Destroying... [id=5678fb68a642f3c6c8004c1bdc21e7142087287b]
local_file.abc: Destruction complete after 0s
Destroy complete! Resources: 1 destroyed.
fmt
fmt 명령은 테라폼 구성 파일의 내용을 표준 형식과 표준 스타일로 적용하는데 사용한다.
$ cat main.tf
resource "local_file" "abc" {
content = "abc!"
filename = "${path.module}/abc.txt"
}
$ terraform fmt
main.tf
$ cat main.tf
resource "local_file" "abc" {
content = "abc!"
filename = "${path.module}/abc.txt"
}
-recursive 옵션을 이용하면 해당 디렉토리 하위의 모든 파일에 적용할 수 있다.
HCL
테라폼은 기본적으로 HCL을 사용한다. json은 공식적으로 호환이 되지만, 가독성이 안좋고 주석 기능을 지원하지 않는 단점이 있다. 직접 작성할 때는 HCL을 이용하고 다른 툴이 json 파일을 생성한 경우에는 .tf.json 확장자를 가진다면 호환이 가능하다. 추가로 테라폼은 yaml 파일은 지원하지 않지만 yamldecode() 함수를 이용하여 테라폼 변수로 변환할 수 있다.
'Engineering > Terraform' 카테고리의 다른 글
| 1. Terraform 시작하기 (3) | 2025.08.04 |
|---|