새소식

기술/Application

Terraform Kubernetes Provider 설정하기 (1)

  • -

안녕하세요. 오늘은 Terraform Provider 중 Kubernetes를 설정하는 법에 대해서 간단하게 가이드해보고자 합니다.

 

<공식 문서>

 

 

준비물 : kubectl에서 사용하는 config 파일

 

config파일에 내용은 다음처럼 구성되어 있습니다.

apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: base64 encoding
    server: https://server ip:port
  name: cluster.local
contexts:
- context:
    cluster: cluster.local
    user: kubernetes-admin
  name: kubernetes-admin@cluster.local
current-context: kubernetes-admin@cluster.local
kind: Config
preferences: {}
users:
- name: kubernetes-admin
  user:
    client-certificate-data: base64 encoding
    client-key-data: base64 encoding

 

Terraform Provider를 사용하려면 provider.tf에 대해서 설정을 먼저 진행해야 합니다.

 

방법은 두 가지가 있습니다.

 

첫번째 기존 config파일을 사용하는 방법

 

1. Windows 기준

C:\Users\사용자 폴더\.kube 폴더를 생성하여 이곳에 config 파일을 생성하여 넣어주면 됩니다.

C:\Users\사용자 폴더\.kube>dir
 C 드라이브의 볼륨: 새 볼륨
 볼륨 일련 번호: 60C5-9C15

 C:\Users\사용자 폴더\.kube 디렉터리

2020-11-12  오후 01:09    <DIR>          .
2020-11-12  오후 01:09    <DIR>          ..
2020-09-02  오후 07:29             4,189 config
               1개 파일               4,189 바이트
               2개 디렉터리  129,708,806,144 바이트 남음

2. Mac, Linux 기준

마찬가지로 사용자 폴더인 ~/.kube 폴더 안에 config파일 생성 후 넣어주면 됩니다.

root@node1:~/.kube# ll
total 8
drwx------  4 root root 4096 Nov 12 02:12 ./
drwx------ 27 root root 4096 Nov 12 02:12 ../
-rw-------  1 root root 5577 Oct  7 04:16 config

이후 provider.tf 작성 시 아래와 같이 입력합니다.

provider "kubernetes" {
  load_config_file = "true"
}

다른 옵션 없이 사용자 폴더에 있는 config파일을 이용하여 인증한다는 것을 선택하는 방법입니다.

 

 

두번째 config파일에 생성된 내용을 참고하여 pem key와 server 정보를 입력해서 사용하는 방법

 

위에 예제로 보여드린 config에서 base64 encoding이라는 부분이 있는데 해당 내용들은 decode 하게 되면 pem 형식의 파일이 됩니다.

 

해당 키를 decode 하는 방법은 decode를 지원하는 사이트에서 해도 좋지만 보안 상 중요한 키이기 때문에 local에서 decode를 하여 사용합니다.

 

pem key로 작성해야 하는 파일이 3개이기 때문에 다음과 같이 입력하여 생성합니다.

#client key data 출력
cat config | grep client-key-data | awk '{print $2}' | base64 -d > ./client-key.pem

#client certificate data 출력
cat config | grep client-certificate-data | awk '{print $2}' | base64 -d > ./client-cert.pem

#client authority data 출력
cat config | grep certificate-authority-data | awk '{print $2}' | base64 -d > ./ca.pem

이후 같은 폴더 안에 provider.tf 파일을 생성 후 다음과 같이 입력합니다.

provider "kubernetes" {
  load_config_file = "false"

  host = "https://server ip:port"

  client_certificate     = file("./client-cert.pem") #같은 폴더가 아니라 다른 곳에 있을 경우 path를 지정해도 됩니다.
  client_key             = file("./client_key.pem") #같은 폴더가 아니라 다른 곳에 있을 경우 path를 지정해도 됩니다.
  cluster_ca_certificate = file("./ca.pem") #같은 폴더가 아니라 다른 곳에 있을 경우 path를 지정해도 됩니다.
 }

 

 

이제 준비가 완료되었습니다.

 

첫번째 방법이나, 두번째 방법 등으로 문법이나 파일 위치 실수가 없었다면 terraform init 을 입력합니다.

C:\Users\사용자 폴더\test>terraform init

Initializing the backend...

Initializing provider plugins...
- Checking for available provider plugins...
- Downloading plugin for provider "kubernetes" (hashicorp/kubernetes) 1.13.3...

The following providers do not have any version constraints in configuration,
so the latest version was installed.

To prevent automatic upgrades to new major versions that may contain breaking
changes, it is recommended to add version = "..." constraints to the
corresponding provider blocks in configuration, with the constraint strings
suggested below.

* provider.kubernetes: version = "~> 1.13"

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.

 

이후 예제로 namespace를 하나 생성해보도록 하겠습니다.

 

resource "kubernetes_namespace" "ns-test" {
  metadata {
    annotations = {
      name = "test"
    }
    name = "test"
  }
}

 

test라는 namespace를 생성하는 .tf파일입니다.

 

plan 후 바로 apply 해보도록 하겠습니다.

 

C:\Users\사용자 폴더\test>terraform plan
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.


------------------------------------------------------------------------

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:

  # kubernetes_namespace.ns-test will be created
  + resource "kubernetes_namespace" "ns-test" {
      + id = (known after apply)

      + metadata {
          + annotations      = {
              + "name" = "test"
            }
          + generation       = (known after apply)
          + name             = "test"
          + resource_version = (known after apply)
          + self_link        = (known after apply)
          + uid              = (known after apply)
        }
    }

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.


C:\Users\사용자 폴더\test>terraform apply

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:

  # kubernetes_namespace.ns-test will be created
  + resource "kubernetes_namespace" "ns-test" {
      + id = (known after apply)

      + metadata {
          + annotations      = {
              + "name" = "test"
            }
          + generation       = (known after apply)
          + name             = "test"
          + resource_version = (known after apply)
          + self_link        = (known after apply)
          + uid              = (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

kubernetes_namespace.ns-test: Creating...
kubernetes_namespace.ns-test: Creation complete after 0s [id=test]

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

정상적으로 생성이 되었다고 나타납니다.

 

이제 서버에서 확인해볼까요?

root@node1:~/.kube# kubectl get ns
NAME                 STATUS   AGE
argo                 Active   30d
argo-rollouts        Active   21d
bluegreen            Active   29d
canary               Active   20d
default              Active   36d
grafana              Active   35d
ingress-nginx        Active   36d
keycloak             Active   28d
kube-node-lease      Active   36d
kube-public          Active   36d
kube-system          Active   36d
local-path-storage   Active   36d
monitoring           Active   30d
nginx                Active   21d
test                 Active   73s

정상적으로 생성이 된 것을 확인할 수 있습니다.

 

이상으로 Terraform에서 Kubernetes Provider 설정법에 대한 가이드를 마칩니다.

 

감사합니다.

 

 

* 추가 내용

 

config_path 옵션을 지원합니다.

 

optional이라 기본이 false였기 때문에 기본 config 파일 path가 ~/.kube로 잡혀 있습니다.

 

해당 옵션과 file을 이용하여 path를 원하는 곳으로 지정할 수 있습니다. :)

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.