Ubuntu 22.04|20.04 |18.04에 Terraform을 설치하는 방법
이 가이드는 Ubuntu 22.04|20.04 |18.04에 Terraform을 설치하는 데 도움이 됩니다. Terraform은 버전별 방식으로 클라우드 리소스를 쉽게 관리할 수 있는 코드형 인프라 도구입니다. Terraform을 사용하여 인기 있는 서비스 제공업체에 배포된 인프라를 구축, 변경 및 버전 관리합니다. 이 도구는 클라우드에 구애받지 않으며 맞춤형 사내 솔루션을 지원합니다.
Terraform을 사용하면 간단한 선언적 프로그래밍 언어를 사용하여 클라우드 컴퓨팅, 네트워킹, 로드 밸런서, DNS 등을 관리할 수 있습니다. Terraform 제공업체의 전체 목록을 확인하세요. 최소한의 인간 상호 작용으로 인프라에 복잡한 변경 세트를 적용할 수 있습니다.
Ubuntu 22.04|20.04 |18.04에 Terraform 설치
Terraform은 Github에 tarball로 배포됩니다. 아래를 다운로드하기 전에 Terraform 릴리스 페이지에서 최신 릴리스를 확인하세요. Ubuntu에 Terraform을 설치할 수 있는 방법에는 두 가지가 있습니다.
방법 1: APT 저장소에서 Terraform 설치
Terraform 팀은 Debian 기반 Linux용 패키지 저장소를 제공합니다. 이를 통해 적절한 패키지 관리 도구 또는 기타 APT 프런트엔드를 사용하여 Terraform을 설치할 수 있습니다.
먼저 저장소 추가 종속성을 설치합니다.
sudo apt update
sudo apt install software-properties-common gnupg2 curl
이제 저장소 GPG 키를 가져옵니다.
curl https://apt.releases.hashicorp.com/gpg | gpg --dearmor > hashicorp.gpg
sudo install -o root -g root -m 644 hashicorp.gpg /etc/apt/trusted.gpg.d/이제 가져온 키를 사용하여 Hashicorp 저장소를 Ubuntu 시스템에 추가하십시오.
sudo apt-add-repository "deb [arch=$(dpkg --print-architecture)] https://apt.releases.hashicorp.com $(lsb_release -cs) main"예상 실행 출력:
Repository: 'deb [arch=amd64] https://apt.releases.hashicorp.com jammy main'
Description:
Archive for codename: jammy components: main
More info: https://apt.releases.hashicorp.com
Adding repository.
Press [ENTER] to continue or Ctrl-c to cancel.
Adding deb entry to /etc/apt/sources.list.d/archive_uri-https_apt_releases_hashicorp_com-jammy.list
Adding disabled deb-src entry to /etc/apt/sources.list.d/archive_uri-https_apt_releases_hashicorp_com-jammy.list
Hit:1 https://mirror.hetzner.com/ubuntu/packages jammy InRelease
Hit:2 https://mirror.hetzner.com/ubuntu/packages jammy-updates InRelease
Hit:3 https://mirror.hetzner.com/ubuntu/packages jammy-backports InRelease
Hit:4 https://mirror.hetzner.com/ubuntu/security jammy-security InRelease
Get:5 https://apt.releases.hashicorp.com jammy InRelease [12.0 kB]
Get:6 https://apt.releases.hashicorp.com jammy/main amd64 Packages [74.4 kB]
Fetched 86.4 kB in 1s (84.6 kB/s)
Reading package lists... Done이제 Ubuntu Linux 시스템에 Terraform을 설치하십시오.
sudo apt install terraform시스템에 설치된 Terraform 버전을 확인하세요.
$ terraform --version
Terraform v1.5.5
on linux_amd64방법 2: Terraform을 수동으로 설치
Terraform의 기본 배포 패키지는 시스템 어디에서나 추출할 수 있는 단일 실행 파일이 포함된 .zip 아카이브입니다.
Ubuntu 시스템에 wget 및 unzip 패키지가 설치되어 있는지 확인하세요.
sudo apt install wget unzip -y그런 다음 최신 Terraform 아카이브를 다운로드하세요.
TER_VER=$(curl -s https://api.github.com/repos/hashicorp/terraform/releases/latest | grep tag_name | cut -d: -f2 | tr -d \"\,\v | awk '{$1=$1};1')
wget https://releases.hashicorp.com/terraform/${TER_VER}/terraform_${TER_VER}_linux_amd64.zip다운로드한 후 아카이브를 추출합니다.
$ unzip terraform_${TER_VER}_linux_amd64.zip
Archive: terraform_1.5.5_linux_amd64.zip
inflating: terraform그러면 작업 디렉터리에 Terraform 바이너리 파일이 생성됩니다. 이 파일을 /usr/local/bin 디렉터리로 이동하세요.
sudo mv terraform /usr/local/bin/
이렇게 하면 모든 사용자 계정에서 도구에 액세스할 수 있습니다.
$ which terraform
/usr/local/bin/terraform설치된 버전 확인
$ terraform version
Terraform v1.5.5
on linux_amd64도구가 작동하는지 확인합니다.
$ terraform
Usage: terraform [global options] <subcommand> [args]
The available commands for execution are listed below.
The primary workflow commands are given first, followed by
less common or more advanced commands.
Main commands:
init Prepare your working directory for other commands
validate Check whether the configuration is valid
plan Show changes required by the current configuration
apply Create or update infrastructure
destroy Destroy previously-created infrastructure
All other commands:
console Try Terraform expressions at an interactive command prompt
fmt Reformat your configuration in the standard style
force-unlock Release a stuck lock on the current workspace
get Install or upgrade remote Terraform modules
graph Generate a Graphviz graph of the steps in an operation
import Associate existing infrastructure with a Terraform resource
login Obtain and save credentials for a remote host
logout Remove locally-stored credentials for a remote host
output Show output values from your root module
providers Show the providers required for this configuration
refresh Update the state to match remote systems
show Show the current state or a saved plan
state Advanced state management
taint Mark a resource instance as not fully functional
test Experimental support for module integration testing
untaint Remove the 'tainted' state from a resource instance
version Show the current Terraform version
workspace Workspace management
Global options (use these before the subcommand, if any):
-chdir=DIR Switch to a different working directory before executing the
given subcommand.
-help Show this help output, or the help for a specified subcommand.
-version An alias for the "version" subcommand.Terraform을 사용하여 인프라 관리
이제 Terraform이 설치되었으므로 테스트 프로젝트를 만들어 보겠습니다.
mkdir projects
cd projectsTerraform 기본 구성 파일을 만듭니다.
touch main.tf저는 AWS 제공업체를 통해 테스트를 진행하고 있지만 귀하의 프로젝트에 다른 제공업체를 사용해도 됩니다. 내 Terraform 구성 공급자 섹션은 다음과 같습니다.
$ vim main.tf
# Provider
provider "aws" {
access_key = ""
secret_key = ""
region = "us-west-1"
}AWS 액세스 키와 비밀 키를 access_key 및 secret_key 섹션에 각각 붙여넣습니다. AWS CLI 도구를 사용하여 AWS 액세스 자격 증명을 구성할 수도 있습니다.
완료되면 terraform init를 실행하여 Terraform 작업 디렉터리를 초기화합니다.
$ terraform init
Initializing the backend...
Initializing provider plugins...
- Finding latest version of hashicorp/aws...
- Installing hashicorp/aws v5.12.0...
- Installed hashicorp/aws v5.12.0 (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은 .terraform 디렉터리에 구성된 공급자를 자동으로 다운로드합니다.
이제 main.tf 파일을 편집하여 AWS VPC 및 서브넷 리소스를 생성하는 리소스 섹션을 추가해 보겠습니다.
# Provider
provider "aws" {
access_key = ""
secret_key = ""
region = ""
}
# Retrieve the AZ where we want to create network resources
data "aws_availability_zones" "available" {}
# VPC Resource
resource "aws_vpc" "main" {
cidr_block = "10.11.0.0/16"
enable_dns_support = true
enable_dns_hostnames = true
tags {
Name = "Test-VPC"
}
tags {
Environment = "Test"
}
}
# AWS subnet resource
resource "aws_subnet" "test" {
vpc_id = "${aws_vpc.main.id}"
cidr_block = "10.11.1.0/24"
availability_zone = "${data.aws_availability_zones.available.names[0]}"
map_public_ip_on_launch = "false"
tags {
Name = "Test_subnet1"
}
}
리소스 정의를 추가하고 AWS 변수를 설정한 후 파일을 저장한 후 실행 계획을 생성하고 표시합니다.
$ 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.
data.aws_availability_zones.available: Refreshing state...
------------------------------------------------------------------------
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:
+ aws_subnet.test
id: <computed>
arn: <computed>
assign_ipv6_address_on_creation: "false"
availability_zone: "us-east-1a"
availability_zone_id: <computed>
cidr_block: "10.11.1.0/24"
ipv6_cidr_block: <computed>
ipv6_cidr_block_association_id: <computed>
map_public_ip_on_launch: "false"
owner_id: <computed>
tags.%: "1"
tags.Name: "Test_subnet1"
vpc_id: "${aws_vpc.main.id}"
+ aws_vpc.main
id: <computed>
arn: <computed>
assign_generated_ipv6_cidr_block: "false"
cidr_block: "10.11.0.0/16"
default_network_acl_id: <computed>
default_route_table_id: <computed>
default_security_group_id: <computed>
dhcp_options_id: <computed>
enable_classiclink: <computed>
enable_classiclink_dns_support: <computed>
enable_dns_hostnames: "true"
enable_dns_support: "true"
instance_tenancy: "default"
ipv6_association_id: <computed>
ipv6_cidr_block: <computed>
main_route_table_id: <computed>
owner_id: <computed>
tags.%: "2"
tags.Environment: "Test"
tags.Name: "Test-VPC"
Plan: 2 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.
마지막으로 terraform Apply를 사용하여 Terraform으로 인프라를 구축하세요.
$ terraform apply
data.aws_availability_zones.available: Refreshing state...
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:
+ aws_subnet.test
id: <computed>
arn: <computed>
assign_ipv6_address_on_creation: "false"
availability_zone: "us-east-1a"
availability_zone_id: <computed>
cidr_block: "10.11.1.0/24"
ipv6_cidr_block: <computed>
ipv6_cidr_block_association_id: <computed>
map_public_ip_on_launch: "false"
owner_id: <computed>
tags.%: "1"
tags.Name: "Test_subnet1"
vpc_id: "${aws_vpc.main.id}"
...........................변경 사항을 확인하고 “yes”를 입력하여 수정을 시작합니다.
Plan: 2 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성공적인 Terraform 실행은 끝에 성공 메시지를 인쇄해야 합니다.
Terraform 상태는 ./terraform.tfstate에 저장되지만 백엔드는 변경될 수 있습니다. AWS 콘솔에서 인프라 변경 사항을 확인할 수 있습니다.
Terraform 인프라 파괴
Ubuntu에 Terraform 설치가 예상대로 작동하는 것을 확인했습니다. terraform destroy 명령을 실행하여 Terraform 관리 인프라를 파괴합니다.
$ terraform destroy
aws_vpc.main: Refreshing state... (ID: vpc-0e94a7d72c02dab2b)
data.aws_availability_zones.available: Refreshing state...
aws_subnet.test: Refreshing state... (ID: subnet-0ad06c2e86542ddc1)
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
- destroy
Terraform will perform the following actions:
- aws_subnet.test
- aws_vpc.main
Plan: 0 to add, 0 to change, 2 to destroy.
Do you really want to destroy all resources?
Terraform will destroy all your managed infrastructure, as shown above.
There is no undo. Only 'yes' will be accepted to confirm.
Enter a value: yes확인 메시지를 원하지 않으면 다음을 사용하십시오.
terraform destroy -auto-approve다른 시스템에 Terraform 설치:
- Fedora에 Terraform을 설치하는 방법
- Windows/Windows Server에 Terraform 설치 및 사용
다음 단계
이제 Terraform을 설치하고 테스트했으므로 최소한의 Terraform 구성 파일을 사용하여 인프라를 구축할 차례입니다. Terraform 사용 사례는 신규 사용자가 읽을 수 있는 흥미로운 페이지입니다.
당신은 또한 다음 사항에 관심이 있을 수 있습니다:
- Terraform을 사용하여 KVM에서 VM을 프로비저닝하는 방법
- Terraform을 사용하여 Hetzner Cloud에 VM 인스턴스 배포
- Packer 및 Ansible을 사용하여 AWS EC2 머신 이미지(AMI) 구축

