티스토리 뷰

Terraform를 사용하게 되면 원격 state 사용이 필요하다.
일반적으로 AWS s3를 사용하지만 public에 올리는것이 아무래도 조심스러울수 있고 이러한 경우 내부 s3 호환이 가능한 minio 서버를 내부에 구성하여 이러한 우려를 종식시킬수 있다. 그러면 minio를 통해 terraform state file을 관리하는 방법에 대하여 알아보자.

minio 설치

minio의 경우 kubernetes 환경에서 helm chart를 통해 간단히 배포를 하였다.

helm install stable/minio -n minio

참고로 minio access_key와 secret_key는 "testkey" 라고 가정하였다.

minio를 terraform backend로 사용하기

이제 minio를 terraform backend로 사용할수 있게 설정해보자.

bucket 생성

먼저 minio의 bucket 생성이 필요하다.

jacob@jacob-laptop:~$ export AWS_ACCESS_KEY_ID="testkey"
jacob@jacob-laptop:~$ export AWS_SECRET_ACCESS_KEY="testkey"
jacob@jacob-laptop:~$ aws --region main --endpoint-url http://minio.testlab:9000 s3 mb s3://tfe
make_bucket: tfe

위와 같이 aws cli를 활용하여 생성한다.

기존 terraform script에서 backend 지정

기존에 terraform script가 있을 경우 아래와 같이 backend 지정을 위한 항목을 추가한다.

jacob@jacob-laptop:~/workspaces/tf-scripts/tf-libvirt$ cat 0-provider.tf 
provider "libvirt" {
  uri = "qemu+ssh://root@192.168.101.1/system"
}

terraform {
  backend "s3" {
    endpoint = "http://minio.testlab:9000"
    key = "terraform.tfstate"
    region = "main"
    skip_requesting_account_id = true
    skip_credentials_validation = true
    skip_get_ec2_platforms = true
    skip_metadata_api_check = true
    skip_region_validation = true
    force_path_style = true
  }
}

물론 새로 생성하는 경우도 위와 거의 동일한 내용을 추가하면 된다.
참고로 위는 terraform libvirt module을 사용한 예제이기에 위부분은 제외하고 "terraform {" 부터 참고하면 된다.

NOTE
만약 여러개의 terraform.tfstate 파일을 보관 관리해야할 경우
backend 설정 중 key를 다르게 가져가면 된다.
key = "terraform-test.tfstate"

지정된 backend 를 사용하도록 initialization 수행

이제 terraform script가 존재하는 directory에서 다음 명령어를 수행한다.

## when you set the minio bucket as terraform backend, this script have to run before you run the terraform deploy.

export MINIO_ACCESS_KEY="testkey"
export MINIO_SECRET_KEY="testkey"
export BUCKET="tfe"
terraform init -backend-config="access_key=$MINIO_ACCESS_KEY" -backend-config="secret_key=$MINIO_SECRET_KEY" -backend-config="bucket=$BUCKET"

위명령어를 bash script file로 생성하여 진행하였다. 아래와 같은 결과를 얻게 된다.

jacob@jacob-laptop:~/workspaces/tf-scripts/tf-libvirt$ ./init.sh 

Initializing the backend...

Successfully configured the backend "s3"! Terraform will automatically
use this backend unless the backend configuration changes.

Initializing provider plugins...
- Checking for available provider plugins...
- Downloading plugin for provider "template" (hashicorp/template) 2.1.2...

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.template: version = "~> 2.1"

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.

참고사항

앞서 "force_path_style = true"를 사전에 추가해놓아서 아래와 같은 이슈는 발생되지 않을것이다. 다만 참고를 위해 아래와 같은 상황이 나타날수 있음을 정리하였다. 관련 명령을 bash script file로 지정하여 다음과 같이 수행하였다.

jacob@jacob-laptop:~/workspaces/tf-scripts/tf-libvirt$ ./init.sh 

Initializing the backend...

Successfully configured the backend "s3"! Terraform will automatically
use this backend unless the backend configuration changes.
Error refreshing state: RequestError: send request failed
caused by: Get http://tfe.minio.testlab:9000/terraform.tfstate: dial tcp: lookup tfe.minio.testlab on 192.168.100.100:53: no such host

위와 같이 aws의 경우 virtual-host style의 URL 요청을 수행한다. 이러한 경우 minio가 가지는 path style이 적용되지 못한다. 하여 force_path_style을 true로 해주어야 한다. 참고로 해당 기능은 terraform v0.12 이후부터 적용되니 해당 부분은 terraform에 대한 버전 확인이 필요하다.

NOTE
만약 초기화가 실패한 경우 해당 directory내 .terraform 디렉토리를 삭제한후 다시 실행하면 정상적으로 초기화 작업을 수행한다.
간혹 기존 정보가 그대로 출력되어 문제가 되는 경우가 있으니 참고하면 좋을것 같다.

Verification

이제 initalization이 완료된 것이다.
terraform sciprt를 apply 하여 실제 terraform script를 실행하고 state 파일이 minio에 저장되는지 확인해보자.

실제 terraform apply를 수행해보면 다음과 같이 terraform.tfstate파일이 생성됨을 확인할 수 있다.

참고사이트

'DevOps > System&Tools' 카테고리의 다른 글

Jenkins Directories  (0) 2020.08.14
Jenkins Debugging  (0) 2020.08.13
Helm usage  (0) 2020.01.23
Use ssh with jenkinsfile as scripted pipeline  (0) 2019.12.11
How to use GitLab API  (0) 2019.11.27
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함