★★cloudNet@ 팀의 가시다 님이 진행하는 Terraform 101 Study 4기 내용과 한빛미디어 테라폼으로 시작하는 IaC 책을 참고하여 정리하였습니다. |
[ 참고 링크 ]
|
★ OpenTofu 소개
: IaC 툴
: OpenTofu는 클라우드와 온프레미스 리소스를 모두 사람이 읽을 수 있는 구성 파일에 정의하여 버전 관리, 재사용 및 공유할 수 있는 코드 도구로서의 인프라, 그런 다음 일관된 워크플로를 사용하여 라이프사이클 전체에 걸쳐 모든 인프라를 프로비저닝하고 관리할 수 있습니다.
: OpenTofu는 애플리케이션 프로그래밍 인터페이스(API)를 통해 클라우드 플랫폼 및 기타 서비스에서 리소스를 생성하고 관리. 공급자는 OpenTofu가 액세스 가능한 API를 통해 사실상 모든 플랫폼이나 서비스와 함께 작업
: 핵심 OpenTofu 워크플로는 세 단계로 구성
1) Write 쓰기 : 여러 클라우드 공급자와 서비스에 걸쳐 있을 수 있는 리소스를 정의(보안 그룹과 로드 밸런서가 있는 VPC 네트워크의 가상 머신에 애플리케이션을 배포하는 구성 만들 수 있음)
2) Plan 계획 : 기존 인프라와 구성에 따라 생성, 업데이트 또는 파괴할 인프라를 설명하는 실행 계획 생성
3) Apply 적용 : 승인 시 OpenTofu는 모든 리소스 종속성을 존중하여 올바른 순서로 제안된 작업을 수행(VPC의 속성을 업데이트하고 해당 VPC의 가상 머신 수를 변경하는 경우 OpenTofu는 가상 머신을 확장하기 전에 VPC를 다시 생성)
★FAQ
▶ OpenTofu와 Terraform의 차이점????
- 기술적인 측면에서 OpenTofu 1.6.x는 Terraform 1.6.x와 기능적으로 매우 유사
- OpenTofu는 오픈 소소라는 점이 주요 차이점. 그 목표는 단일 회사가 로드맵을 지시할 수 없는 협력적인 방식으로 추진되는 것
▶ Terraform의 드롭인 대체품으로 OpenTofu를 사용할 수 있나? OpenTofu는 프로덕션 사용에 적합한가?
- 지금 당장, OpenTofu는 Terraform 버전 1.5.x 및 대부분 1.6.x와 호환되므로 Terraform의 드롭인 대체품.
호환성을 보장하기 위해 코드를 변경할 필요가 없음
▶ OpenTofu가 기존 상태 파일과 호환되나요?
- OpenTofu는 Terraform 버전 1.5.x로 생성된 파일까지 기존 상태 파일을 지원
▶ OpenTofu는 Terraform이 협력하는 모든 공급업체와 호환됩니까?
- OpenTofu는 자체 공급자가 없다. Terraform 공급자는 라이선스를 변경하지 않았으며 그러한 변경 가능성은 사실상 0
- OpenTofu는 현재 Terraform 공급자와 함께 작동하지만 별도의 레지스트리 사용
★ OpenTofu 설치
* WSL Ubuntu 환경 사용
1. Enable snapd
sudo apt update
sudo apt install snapd
2. Install tenv
sudo snap install tenv
(옵션) Install shell completion
tenv completion zsh > ~/.tenv.completion.zsh
echo "source '~/.tenv.completion.zsh'" >> ~/.zshrc
2. Tofu 설치 및 확인
sudo snap install opentofu --classic
★ OpenTofu 1.7.0
▶ Provider-defined functions
- Functions 종류 : Built-in Function, Provider-defined Functions
- OpenTofu iterates through the rquired_providers block and queries the specified providers for any functions they wish to register.
- Functions are added to the current module's context under provider::<provider_name>::<function_name>.
- Provider aliases are also supported under provider::<provider_name>::<provider_alias>::<function_name>
- Functions are scoped to the module that requires the provider and are not inherited by child modules. - 새로운 Terraform 플러그인 SDK added support for provider-defined functions that you can use directly in OpenTofu. This is a significant improvement over using data sources as provider-defined functions don't increase the size of your state file and require less code to write.
terraform {
required_providers {
corefunc = {
source = "northwood-labs/corefunc"
version = "1.4.0"
}
}
}
provider "corefunc" {
}
output "test" {
value = provider::corefunc::str_snake("Hello world!")
# Prints: hello_world
}
: source가 user가 직접 만든 function provider
: user가 선언한 function에 의해서 필요한 기능 제공
★ 실습 따라하기
[ Provider-defined functions ]
[ Loopable import blocks ]
[ State file encryption - Local ]
- State and Plan Encryption
: State 파일을 암호화하여 저장하는 것이 매우 중요(필요할 때만 복호화해서 사용)
: State 파일 암호화 뿐만이 아니라 Plan 파일도 암호화 가능
: OpenTofu는 로컬 스토리지와 백엔드를 사용할 때 모두 휴먼 상태 및 계획 파일을 암호화는 것을 지원. 또한 terraform_remote_state 데이터 소스와 함께 암호화를 사용
: fallback - 문제가 있을 경우 이전으로 복구하는 기능 - Key providers : PBKDS2, AWS KMS, GCP KMS, OpenBao(experimental)
- PBKDS2 : 로컬에 있는 파일 암호화, PBKDF2 키 제공자는 AES-GCM과 같은 암호화 방법에 대한 키를 생성하기 위해 긴 패스프레이즈를 사용 가능 (The PKBDF2 key provider allows you to use a long passphrase as to generate a key for an encryption method such as AES-GCM.) - AWS : AWS 키 제공자는 AWS KMS로 키 생성
: kms_key_id - Key ID for AWS KMS
: key_spec - Key spec for AWS KMS. Adapt this to your encryption method (e.g. AES_256)
terraform {
encryption {
key_provider "aws_kms" "basic" {
kms_key_id = "a4f791e1-0d46-4c8e-b489-917e0bec05ef"
region = "us-east-1"
key_spec = "AES_256"
}
}
}
* 실습 따라하기
- backend.tf 파일 작성
: state 파일이 암호화되어 cat으로 terraform.tfstate 파일 확인 시 확인 불가
: tofu show에서는 tfstate 파일을 복호화하여 내용을 보여주므로 tofu show를 통해 내용 확인 가능
* Rolling back encryption : 암호화 -> 평문으로 마이그레이션
- backend.tf 파일 수정
[ State file encryption - AWS KMS ]
- AWS S3 버킷 생성 : Backend State 저장 용도
- AWS KMS 소개
- 암호화는 키를 사용해 평문을 암호문으로 변환하는 프로세스
- 동일한 키를 사용해 암호문을 평문으로 변환할 수 있는데, 이를 복호화라고 함
- AWS 키 관리 서비스 KMS는 공유 하드웨어 보안 모듈HSM을 사용하면서 암호화키를 생성하고 관리할 수 있게 도와준다
- CloudHSM은 AWS 내에서 암호화키를 관리할 수 있지만 보안 강화를 위해 전용 HSM을 사용할 수 있는 서비스
- 용어 변경 : Customer Master Key (CMK) -> AWS KMS key 혹은 KMS key로 변경 - 대칭 키 생성 후 평문 파일을 암호화 및 복호화
- Backend.tf 파일 수정
[ Removed block ]
- The removed block lets you remove a resource from the state file but keep it on the infrastructure
- 실습
: main.tf 파일에 아래 resource 부분 추가
resource "aws_ssm_parameter" "this" {
count = length(var.instance_tags)
name = var.instance_tags[count.index]
type = "String"
value = aws_instance.this[count.index].id
}
* 실습 목적 - 파라미터 스토어 리소스만 tfstate에서 제거하고 aws 상에는 유지하게 설정 (main.tf 파일 수정)
# resource "aws_ssm_parameter" "this" {
# count = length(var.instance_tags)
# name = var.instance_tags[count.index]
# type = "String"
# value = aws_instance.this[count.index].id
# }
removed {
from = aws_ssm_parameter.this
}
[ Test ]
- The tofu test command lets you test your OpenTofu configuration by creating real infrastructure and checking that the required conditions (assertions) are met. Once the test is complete, OpenTofu destorys the resources it created.
- Usage : tofu test [options]
- This command will execute all *.tftest.hcl files in the current directory or in a direcotry called test.
- You can customize this behavior using the options below.
: Consider the followiing simple example which creates a test.txt file from main.tf and then checks that the main code has successfully performed its job from main.tftest.hcl.
: Tofu now reads the .tfvars file from the tests folder.
[ CLI changes ]
- tofu init now supports the json flag for JSON output
- tofu plan now has a concise flag to shorten the plan output
- tofu console now works on Solaris and AIX
- The CLI now supports the XDG directory specificaition.
- Aliases for
: state list -> state ls
: state mv -> state move
: state rm -> state remove
[ 실습 리소스 삭제 ]
1. AWS EC2 삭제 : 8.2 디렉터리 이동 후 삭제
2. SSM 파라미터 삭제
3. S3 버킷 삭제
4. KMS 키 비활성화 및 삭제 예약
★ Migration to OpenTofu 1.7.x from Terraform
- Tenv로 Terraform 설치 : 1.8.5 -> 마이그레이션 시, 최소 1.8.2 이상 Terrform 버전 사용 권고
[ 마이그레이션 ]
1. 현재 최신 상태 여부 확인
terraform plan
2. state file과 tf code 파일 백업
cp terraform.tfstate terraform.tfstate.t101
# tf code 파일 백업 : skip
3. 코드 변경
* S3 backend : If you are using the S3 backend, please change your code as follows :
1) If you are using the skip_s3_checksum option on the S3 backend, remove this option as OpenTofu does not need it.
2) If you are using the endpoints -> sso option or the AWS_ENDPOINT_URL environment variable, remove this option and verify if your code still works as intended after the migration.
* Remove block : The OpenTofu removed block works differently from the Terraform variant.
Please review the documentation and make the following changes:
1) Remove the lifecycle block. If you used the lifecycle -> destroy = true setting, remove the entire removed block. Verify that the code still works as intended after the migration.
* Testing changes : If you are using the Terraform test feature, you will need to perform the following changes :
1) If you are using mock_provider, restructure your tests to work without this feature (see OpenTofu issue #1155).
2) If you are using override_resource, override_data, or override_module, restructure your tests to work without these features (see OpenTofu issue #1204).
4. OpenTofu 초기화 및 Plan
(Warning) Should any of the following steps fail, please do not proceed and follow the rollback instructions below instead. If you suspect the failure may be the result of a bug in OpenTofu, please help us by opening an issue. |
★ OpenTofu 1.8.0
- Variables adn Locals allowed in module sources and backend configurations
- Added support to new .tofu extensions to allow tofu-specific overrides of .tf files
- Added support for override_resource, override_data and override_module blocks in testing framework.
- Added support for mock_provider, mock_resource and mock_data blocks in testing framework.
- Deprecation : use_legacy_workflow has been removed from the S3 backend-backend
▶ 1.8.0 설정
#
tenv tofu list
tenv tofu list-remote
# 설치
tenv tofu install 1.8.0
tenv tofu list
tenv tofu use 1.8.0
tenv tofu detect
# tofu 확인
tofu -h
tofu version
▶ Early variable/locals evaluation : 변수 variable를 'Backend, Module Sources, Encryption Configuration' 사용 가능
- terraform.backend에 variable 변수 사용 불가 <- init 과정에서 백엔드가 초기화 되어야 하기 때문
- 모듈 소스에도 variable 변수 사용 불가(다수의 모듈 소스의 참조 주소를 변수로 사용 불가)
- 변수 variable를 'Backend, Module Sources, Encryption Configuration' 사용 가능!
▶ 실습 따라하기
- AWS S3 버킷 생성 : Backend State 저장 용도
- main.tf 파일 작성
- 실행 및 확인
1) terraform init 시 error 발생 -> variable 변수 사용으로 인한 error
2) tofu init > 성공
3) tofu apply > s3에 terraform.tfstate 확
'스터디 > Terraform' 카테고리의 다른 글
[Terraform T101 4기 스터디] - 테라폼으로 AWS EKS 배포 (0) | 2024.07.22 |
---|---|
[Terraform T101 4기 스터디] - Module & Runner (0) | 2024.07.08 |
[Terraform T101 4기 스터디] - Provider & State (2) (1) | 2024.07.02 |
[Terraform T101 4기 스터디] - Provider & State (0) | 2024.07.01 |
[Terraform T101 4기 스터디] - 기본 사용 (3)_2 (0) | 2024.06.24 |