Dev./Terraform

Terraform: 설치와 기본정보

Ivan'show 2023. 9. 1.
728x90
반응형

Install Terraform

brew tap hashicorp/tap
brew install hashicorp/tap/terraform

Terraform command

  • init
    • 테라폼 명령어 사용을 위해 각종 설정을 진행
    • 테라폼이 코드를 스캔하여 어느 공급자인지 확인하고 필요한 코드를 다운로드
  • plan
    • 테라폼으로 작성한 코드가 어떻게 만들어질지에 대한 예측결과 보여줌
  • apply
    • 실제로 테라폼 코드를 실행하여 인프라를 생성하는 명령어
  • import
    • 이미 만들어진 자원을 테라폼 state 파일로 옮겨주는 명령어
  • state
    • 테라폼 state 를 다루는 명령어로 mv, push 와 같은 명령어를 포함
  • destroy
    • 해당 코드로 생성된 모든 리소스를 제거

basic process

init -> plan -> apply

apply 를 실행하기전 항상 plan 으로 미리 체크하는 습관을 가지는게 좋다.

Using terraform

(venv) kimminhyeok@Ivans-Mac dev_django_app % mkdir infra/tutorial
(venv) kimminhyeok@Ivans-Mac tutorial % touch main.tf

Install Extension

코드작성 예시

# main.tf
terraform {
  required_providers {
    docker = {
        source = "kreuzwerker/docker"
        version = "~> 3.0.1"
    }
  }
}

provider "docker" {}

명령어 실행

terraform init
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.

Update code

terraform {
  required_providers {
    docker = {
        source = "kreuzwerker/docker"
        version = "~> 3.0.1"
    }
  }
}

provider "docker" {}

resource "docker_image" "nginx" {
    name = "nginx"
    keep_locally = false
}

resource "docker_container" "nginx" {
    image = docker_image.nginx.image_id
    name = "tutorial"

    ports {
        internal = 80
        external = 8888
    }
}

code execution

(venv) kimminhyeok@Ivans-Mac tutorial % 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:

  # docker_container.nginx will be created
  + resource "docker_container" "nginx" {
      + attach                                      = false
      + bridge                                      = (known after apply)
      + command                                     = (known after apply)
      + container_logs                              = (known after apply)
      + container_read_refresh_timeout_milliseconds = 15000
      + entrypoint                                  = (known after apply)
      + env                                         = (known after apply)
      + exit_code                                   = (known after apply)
      + hostname                                    = (known after apply)
      + id                                          = (known after apply)
      + image                                       = (known after apply)
      + init                                        = (known after apply)
      + ipc_mode                                    = (known after apply)
      + log_driver                                  = (known after apply)
      + logs                                        = false
      + must_run                                    = true
      + name                                        = "tutorial"
      + network_data                                = (known after apply)
      + read_only                                   = false
      + remove_volumes                              = true
      + restart                                     = "no"
      + rm                                          = false
      + runtime                                     = (known after apply)
      + security_opts                               = (known after apply)
      + shm_size                                    = (known after apply)
      + start                                       = true
      + stdin_open                                  = false
      + stop_signal                                 = (known after apply)
      + stop_timeout                                = (known after apply)
      + tty                                         = false
      + wait                                        = false
      + wait_timeout                                = 60

      + ports {
          + external = 8888
          + internal = 80
          + ip       = "0.0.0.0"
          + protocol = "tcp"
        }
    }

  # docker_image.nginx will be created
  + resource "docker_image" "nginx" {
      + id           = (known after apply)
      + image_id     = (known after apply)
      + keep_locally = false
      + name         = "nginx"
      + repo_digest  = (known after apply)
    }

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

code execution

(venv) kimminhyeok@Ivans-Mac tutorial % terraform apply
...
Enter a value: yes
Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
(venv) kimminhyeok@Ivans-Mac tutorial % 
(venv) kimminhyeok@Ivans-Mac tutorial % docker ps
CONTAINER ID   IMAGE          COMMAND                  CREATED          STATUS          PORTS                  NAMES
f3300d964e20   ab73c7fd6723   "/docker-entrypoint.…"   14 seconds ago   Up 13 seconds   0.0.0.0:8888->80/tcp   tutorial
(venv) kimminhyeok@Ivans-Mac tutorial %

.gitignore

테라폼을 실행하면 terraform.tfstate 파일이 생긴다. terraform.tfstate 파일은 민감한 정보까지 모두 담고 있기 때문에 조심해야한다.

그래서 바로 gitignore 에 추가해 준다.

## gitignore 아래쪽

...
...
...

# Local .terraform directories
**/.terraform/*

# .tfstate files
*.tfstate
*.tfstate.*

# Crash log files
crash.log
crash.*.log

# Exclude all .tfvars files, which are likely to contain sensitive data, such as
# password, private keys, and other secrets. These should not be part of version 
# control as they are data points which are potentially sensitive and subject 
# to change depending on the environment.
*.tfvars
*.tfvars.json

# Ignore override files as they are usually used to override resources locally and so
# are not checked in
override.tf
override.tf.json
*_override.tf
*_override.tf.json

# Include override files you do wish to add to version control using negated pattern
# !example_override.tf

# Include tfplan files to ignore the plan output of command: terraform plan -out=tfplan
# example: *tfplan*

# Ignore CLI configuration files
.terraformrc
terraform.rc

# lock file -> 팀으로 개발할 때 사용하므로 일단은 주석
.terraform.lock.hcl

infra 쪽에 main 을 생성하고 기존에 있던 테라폼을 삭제

terraform destroy

...

Enter a value: yes
(venv) kimminhyeok@Ivans-Mac tutorial % docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
(venv) kimminhyeok@Ivans-Mac tutorial %

 

728x90
반응형

'Dev. > Terraform' 카테고리의 다른 글

Terraform: Modules  (0) 2023.09.05
Terraform: LoadBalancer  (0) 2023.09.05
Terraform: AWS - VPC 생성  (0) 2023.09.04
Terrform: NCP 서버 생성  (0) 2023.09.02
Terraform: IaC  (0) 2023.09.01

댓글