amazon linux 테라폼 설치 sudo yum install -y yum-utils sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/AmazonLinux/hashicorp.repo sudo yum -y install terraform terraform version --------------------------- Terraform v1.5.2 on linux_amd64 10 install.txt 2) mac 사용자 https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli?in=terraform%2Faws-get-started # tfenv 설치 brew install tfenv # 설치 가능 버전 리스트 확인 tfenv list-remote # 테라폼 1.5.1 버전 설치 tfenv install 1.5.1 # 테라폼 1.5.1 버전 사용 설정 tfenv use 1.5.1 # tfenv로 설치한 버전 확인 tfenv list # 테라폼 버전 정보 확인 terraform version # 자동완성 terraform -install-autocomplete ## 참고 .zshrc 에 아래 추가됨 cat ~/.zshrc autoload -U +X bashcompinit && bashcompinit complete -o nospace -C /usr/local/bin/terraform terraform 3) windows / linux https://developer.hashicorp.com/terraform/downloads # centos terraform install sudo yum install -y yum-utils sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo sudo yum -y install terraform terraform version yum -y install tree jq git htop go # jq download curl -L https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64 -o /usr/local/bin/jq chmod a+x /usr/local/bin/jq jq -V 4) # 우분트 linux에서 설치 wget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list sudo apt update && sudo apt install terraform 5) # 테라폼 버전 정보 확인 terraform version 6) (선택) mac 사용자 코드 작성을 위해 Vs code설치 https://code.visualstudio.com/ 7) Vs code에서 확장 프로그램 설치 좌측 [Extentions] 아이콘을 클릭 HashiCorp에서 릴리즈한 HashiCorp HCL 을 검색 후 설치 HashiCorp HCL https://marketplace.visualstudio.com/items?itemName=HashiCorp.HCL HashiCorp Terraform https://marketplace.visualstudio.com/items?itemName=HashiCorp.terraform VS code 왼편 아래 Extension 아이콘 8) (권장) 자동저장 설정 : 설정 → 일반적으로 사용되는 설정 ⇒ Files: Auto Save 값을 afterDelay 선택 3 access-key , secret-key 생성 ? AWS 서울리전 iam > 사용자 생성 > admin 권한. access-key , secret-key 생성 4 AWS CLI 설치 ? 아마존 리눅스는 이미 설치되어 있음 aws cli 2.x 대 설치 필요. (centos 경우) curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" unzip awscliv2.zip sudo ./aws/install 버킷 조회해 잘 되는지 확인? aws s3 ls 권한이 없으므로 안됨. 5 권한 부여 ? aws configure AWS Access Key ID [None]: aws s3 ls 또는 환경 변수로 설정. <4> 테라폼으로 EC2 1대 만들어 보기 1 aws의 디폴트 vpc로 사용함. 삭제 하지 않았다면 디폴트 VPC는 있습니다. 2 디폴트 vpc 없다면? AWS 콘솔에서 디폴트 vpc 생성가능함. AWS CLI 로 디폴트 vpc 생성. 콘솔에서 생성법 ? aws 콘솔 로그인 https://console.aws.amazon.com/ VPC > Your VPCs > 오른쪽위 ACTION > CREATE DEFAULT VPC 3 cli로 디폴트 vpc 생성 ? # 디폴트 vpc 있는지 확인 aws ec2 describe-vpcs --filter 'Name=isDefault,Values=true' | jq aws ec2 describe-vpcs --filter 'Name=isDefault,Values=true' | jq '.Vpcs[0].VpcId' # default vpc 없다면 생성 aws ec2 create-default-vpc aws ec2 describe-vpcs --filter 'Name=isDefault,Values=true' | jq '.Vpcs[0].VpcId' 4 EC2 로그인 ? 작업 디렉터리 하나 만들기 mkdir seo cd seo 5 ami id를 알아야 테라폼으로 생성가능. 서버 이미지 id로 만듭니다. aws ec2 describe-images --owners self amazon --query 'Images[*].[ImageId]' --output text aws ssm get-parameters-by-path --path /aws/service/ami-amazon-linux-latest --query "Parameters[].Value" ami-0a0064415cdedc552 콘솔상에서도 확인가능 6 서버 생성을 모니터링 하기위해 , 별도 터미널로 ec2 생성 모니터링 # 별도 [터미널1] EC2 생성 모니터링 export AWS_PAGER="" while true; do aws ec2 describe-instances --query "Reservations[*].Instances[*].{PublicIPAdd:PublicIpAddress,InstanceName:Tags[?Key=='Name']|[0].Value,Status:State.Name}" --filters Name=instance-state-name,Values=running --output text ; echo "------------------------------" ; sleep 2; done 7 테라폼으로 EC2 1대 생성해 보자. cat < main.tf provider "aws" { region = "ap-northeast-2" } resource "aws_instance" "example" { ami = "ami-0a0064415cdedc552" instance_type = "t2.micro" } EOT 5 terraform init #초기화 , 각종 라이블러리를 불러옴. terraform plan #계획 terraform apply # 실행 Enter a value: yes 6 모니터링 터미널에서 ec2 생성 확인 ? cli로 확인 aws ec2 describe-instances --output table 콘솔에서도 ec2 확인 7 ec2 정보 수정? 서버 이름을 넣어보자. 태그 정보로 넣는다. cat < main.tf provider "aws" { region = "ap-northeast-2" } resource "aws_instance" "example" { ami = "ami-0a0064415cdedc552" instance_type = "t2.micro" tags = { Name = "t101-study" } } EOT terraform plan #계획 +는 신규 생성 - 는 삭제. terraform apply # 실행 Enter a value: yes 8 삭제 ? 삭제 자동 승인 terraform destroy -auto-approve aws 콘솔에서 ec2 삭제 확인 9 참고 이미지 이름을 몰라도, 데이터 소스로 가져와서 사용할수도 있다. # 방법1 data "aws_ssm_parameter" "amzn2_latest" { name = "/aws/service/ami-amazon-linux-latest/amzn2-ami-kernel-5.10-hvm-x86_64-gp2" } # 방법2 data "aws_ami" "linux" { owners = ["amazon"] most_recent = true filter { name = "name" values = ["amzn2-ami-hvm*"] } } resource "aws_instance" "aaaaaaaa" { ami = data.aws_ami.amazonlinux2.id //... lifecycle { ignore_changes = [ami] } } # 방법3 data "aws_ami" "ubuntu" { most_recent = true filter { name = "name" values = ["ubuntu/images/hvm-ssd/ubuntu-*-*-amd64-server-*"] } filter { name = "virtualization-type" values = ["hvm"] } owners = ["099720109477"] # Canonical } https://www.andreagrandi.it/2017/08/25/getting-latest-ubuntu-ami-with-terraform/ Getting latest Ubuntu AMI with Terraform When we need to create an EC2 resource on AWS using Terraform, we need to specify the AMI id to get the correct image. The id is not easy to memorise and it changes depending on the zone we are working one. On every new release the id changes again. So, ho www.andreagrandi.it <5> 테라폼 기본 사용법 (linux 사용자) 1 cd mkdir workspace cd workspace [root@myeks2-bastion-EC2 workspace]# vi main.tf resource "local_file" "abc" { content = "abc!" filename = "${path.module}/abc.txt" } # abc.txt 파일을 만들자. # abc.txt 파일 안에 내용에 abc! 를 넣자. 2 (선택) mac 사용자 vs code 사용하자. mkdir wokrspace 파일 > 폴더 열기에서 열자. 터미널 새 터미널에서 모니터링 vscode에서 폴더 만들기 파일 만들기 main.tf 3 시작해보자~ terraform plan [root@myeks2-bastion-EC2 workspace]# terraform plan ╷ │ Error: Inconsistent dependency lock file │ │ The following dependency selections recorded in the lock file are inconsistent with the current configuration: │ - provider registry.terraform.io/hashicorp/local: required by this configuration but no version is selected │ │ To make the initial dependency selections that will initialize the dependency lock file, run: │ terraform init ╵ 4 # 초기화 terraform init ls -al tree. teraform 5 terraform plan 배포하기 전에 계획. 어떤 것을 생성할지 검토해 주는 단계. 실제 반영은 하지 않는다. 설명 중 +는 create이다. 파일과 디렉터리 퍼미션도 기본으로 추가된다. 6 terraform apply yes [root@myeks2-bastion-EC2 workspace]# ls abc.txt main.tf terraform.tfstate [root@myeks2-bastion-EC2 workspace]# more abc.txt abc! 7 실습 2 [root@myeks2-bastion-EC2 workspace]# vi main.tf resource "local_file" "abc" { content = "abc!" filename = "${path.module}/abc.txt" } resource "local_file" "dev" { content = "def!" filename = "${path.module}/def.txt" } 8 terraform apply yes # def.txt 파일을 만들어 준다. [root@myeks2-bastion-EC2 workspace]# ls abc.txt def.txt main.tf terraform.tfstate terraform.tfstate.backup 9 def.txt 파일을 지우도 싶으면 ? main.tf 에서 코드를 지우면 된다. [root@myeks2-bastion-EC2 workspace]# more main.tf resource "local_file" "abc" { content = "abc!" filename = "${path.module}/abc.txt" } terraform apply [root@myeks2-bastion-EC2 workspace]# ls abc.txt main.tf terraform.tfstate terraform.tfstate.backup 11 terraform destroy yes 모든 개체를 제거하는 명령어이다. 일부 리소스만 제거 하지 않는다. terraform state list ls *.txt 12 테라폼 파일을 포맷팅 (정렬)해주는 명령어. terraform fmt [root@myeks2-bastion-EC2 workspace]# more main.tf resource "local_file" "abc" { content = "abc!" filename = "${path.module}/abc.txt" } [root@myeks2-bastion-EC2 workspace]# terraform fmt main.tf [root@myeks2-bastion-EC2 workspace]# more main.tf resource "local_file" "abc" { content = "abc!" filename = "${path.module}/abc.txt" }