본문 바로가기

IaC/Terraform

[Terraform]테라폼 기본 사용법 with local provider

원하는 provider 선택

Terraform provider doc
https://registry.terraform.io/browse/providers

  • 위 링크에서 원하는 테라폼에서 사용할 provider를 검색한다.

테라폼  local provider 사용하기

local provider는 파일과 같은 로컬 리소스를 관리하는데 사용한다.

local provider doc
https://registry.terraform.io/providers/hashicorp/local/latest/docs

테라폼 local provider 사용하기 - local_file (Resource)

  • resource "local_file"
    • Generates a local file with the given content.

Example
https://registry.terraform.io/providers/hashicorp/local/latest/docs/resources/file

main.tf

mkdir jeff-terraform-1
cd jeff-terraform-1
vim main.tf
  • version을 명시하지 않으면 최신버전을 사용하게 된다.
terraform {
  required_providers {
    local = {
      source = "hashicorp/local"
      version = "2.2.3"
    }
  }
}

provider "local" {
  # Configuration options
}

resource "local_file" "jeff" {
    content  = "hello terraform"
    filename = "${path.module}/jeff.txt"
}
  • ${path.module}
    • 해당 파일이 위치한 dir 경로

terraform init

  • Terraform 구성 파일이 포함된 작업 디렉터리를 초기화하는 명령어
  • 새로운 prdovier가 추가되면 해준다.
jeff-terraform-1 ❯ terraform init                 

Initializing the backend...

Initializing provider plugins...
- Finding hashicorp/local versions matching "2.2.3"...
- Installing hashicorp/local v2.2.3...
- Installed hashicorp/local v2.2.3 (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!

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.

terraform plan

  • Terraform이 인프라에 적용할 계획인 변경 사항을 미리 볼 수 있는 실행 계획을 생성
jeff-terraform-1 ❯ tf 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.foo will be created
  + resource "local_file" "jeff" {
      + content              = "hello terraform"
      + directory_permission = "0777"
      + file_permission      = "0777"
      + filename             = "./jeff.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.

terraform apply

  • Terraform plan에서 제안된 작업을 실행
jeff-terraform-1 ❯ tf 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.foo will be created
  + resource "local_file" "jeff" {
      + content              = "hello terraform"
      + directory_permission = "0777"
      + file_permission      = "0777"
      + filename             = "./jeff.txt"
      + id                   = (known after apply)
    }

Plan: 1 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

local_file.jeff: Creating...
local_file.jeff: Creation complete after 0s [id=7658d663d255c6ba8bfe2c02bf7f82c93c4e6e1f]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

테라폼 결과 확인

jeff-terraform-1 ❯ ll
total 24
-rwxr-xr-x@ 1 dewble  staff    15B 12 22 00:11 jeff.txt
-rw-r--r--@ 1 dewble  staff   273B 12 22 00:10 main.tf
-rw-r--r--@ 1 dewble  staff   858B 12 22 00:11 terraform.tfstate
jeff-terraform-1 ❯ cat jeff.txt       
hello terraform%

.terraform.tfstate 확인 - 테라폼 상태 관리

  • 현재 테라폼 결과를 확인할 수 있다.
## 중략
"resources": [
    {
      "mode": "data",
      "type": "local_file",
      "name": "jm",
      "provider": "provider[\"registry.terraform.io/hashicorp/local\"]",
      "instances": [
        {
          "schema_version": 0,
          "attributes": {
            "content": "jm data sources",
            "content_base64": "am0gZGF0YSBzb3VyY2Vz",
            "filename": "./jm.txt",
            "id": "3baae6578ab929f21871089e036df68a29d8049a"
          },
          "sensitive_attributes": []
        }
      ]
    },
## 중략

테라폼 local provider 사용하기 - local_file (Data Source)

  • data "local_file" 
    • local_file reads a file from the local filesystem.

Example
https://registry.terraform.io/providers/hashicorp/local/latest/docs/data-sources/file#example-usage

data "local_file" "foo" {
    filename = "${path.module}/foo.bar"
}

resource "aws_s3_bucket_object" "shared_zip" {
  bucket     = "my-bucket"
  key        = "my-key"
  content     = data.local_file.foo.content
}

main.tf

terraform {
  required_providers {
    local = {
      source = "hashicorp/local"
      version = "2.2.3"
    }
  }
}

provider "local" {
  # Configuration options
}

resource "local_file" "jeff" {
    content  = "hello terraform"
    filename = "${path.module}/jeff.txt"
}

data "local_file" "jm" {
    filename = "${path.module}/jm.txt"

output "file_jm" {
    value = data.local_file.jm
}    
}

tf apply

jeff-terraform-1 ❯ tf apply
data.local_file.bar: Reading...
local_file.foo: Refreshing state... [id=7658d663d255c6ba8bfe2c02bf7f82c93c4e6e1f]
data.local_file.bar: Read complete after 0s [id=3baae6578ab929f21871089e036df68a29d8049a]

No changes. Your infrastructure matches the configuration.

Terraform has compared your real infrastructure against your configuration and
found no differences, so no changes are needed.

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Outputs:

file_jm = {
  "content" = "jm data sources"
  "content_base64" = "am0gZGF0YSBzb3VyY2Vz"
  "filename" = "./jm.txt"
  "id" = "3baae6578ab929f21871089e036df68a29d8049a"
}

 

참고 https://fastcampus.co.kr/dev_online_awsdevops