본문 바로가기

DevOps/Terraform

[T102 1주차] (2) 테라폼 설치

cloudNet@ 팀의 가시다 님이 진행하는 테라폼 102 스터디 1주차 정리입니다.

 

1주차 내용: 

테라폼 설치 >> ec2 배포 

MAC os를 기준으로 작성하였습니다.
  • brew terraform 설치
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
mzc01-kook@MZC01-KOOK ~ % terraform version
Terraform v1.3.2
on darwin_arm64

Your version of Terraform is out of date! The latest version
is 1.5.4. You can update by downloading from https://www.terraform.io/downloads.html
  • aws cli 설치
# macOS 설치 방법
$ brew install awscli

# Linux 설치 방법
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install


# aws cli 버전 확인
aws --version
aws-cli/2.7.31 Python/3.10.7 Darwin/21.6.0 source/x86_64 prompt/off

# aws cli 사용 시도
aws s3 ls

---
# aws configure 로 자격증명 설정 : 방안1
aws configure
... >> 입력

aws configure list
      Name                    Value             Type    Location
      ----                    -----             ----    --------
   profile                <not set>             None    None
access_key     ****************DYFF shared-credentials-file
secret_key     ****************m7Za shared-credentials-file
    region           ap-northeast-2      config-file    ~/.aws/config

# 환경 변수로 자격증명 설정 : 방안2
Linux or macOS
export AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
export AWS_DEFAULT_REGION=us-west-2

# 페이저 사용 비활성화
export AWS_PAGER=""

# aws cli 사용 시도
aws s3 ls
  • 실습에 편리한 툴 들 설치: watch, jq ,tree 등
# macOS
brew install tree jq watch

# Linux
sudo apt install -y tree jq
  • default vpc 확인
aws ec2 describe-vpcs --filter 'Name=isDefault,Values=true' | jq
{
...

aws ec2 describe-vpcs --filter 'Name=isDefault,Values=true' | jq '.Vpcs[0].VpcId'
"vpc-3912a952"


#aws ec2 describe-subnets --filter 'Name=vpc-id,Values=vpc-3912a952' --output table
aws ec2 describe-subnets --filter 'Name=vpc-id,Values=vpc-<자신의VPC ID>' --output table

 

  • 작업 디렉터리 생성 및 이동
# 각자 편한 디렉터리를 생성해주시면 됩니다
mkdir t101-1week-ec2
cd t101-1week-ec2
  • Amazon 최신 ami id 찾기 :  ami-0a0064415cdedc552 → 자주 업데이트가 됨
#aws ec2 describe-images --owners self amazon
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
aws ssm get-parameters-by-path --path /aws/service/ami-amazon-linux-latest --query "Parameters[].Name"
aws ssm get-parameters-by-path --path /aws/service/ami-amazon-linux-latest --query "Parameters[].Value"
  • 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 1; done
  • EC2 생성 
    • provider: Terraform에서는 퍼블릭 클라우드 Provider을 지정 해줘야 함
    • resource: 실제로 생성할 인프라 자원의 지칭값을 지정  해줘야 함
cat <<EOT > main.tf
provider "aws" {
  region = "ap-northeast-2"
}

resource "aws_instance" "example" {
  ami           = "ami-0a0064415cdedc552"
  instance_type = "t2.micro"
}
EOT
# 초기화
terraform init
ls -al
tree .terraform

# plan 확인
terraform plan

# apply 실행
terraform apply
 Enter a value: yes 입력

# ec2 생성 확인 : aws 웹 관리 콘솔에서도 확인 - 서울 리전 선택
export AWS_PAGER=""
aws ec2 describe-instances --output table

 


윤서율님 발표: 

  • 서율님의 테라폼 운영 경험에 대한 이야기를 들을수 있었다. 감사합니다.

 

- 테라폼을 쓰게 된 이유? 

비용때문에 쓰게됨 

AWS Cloud를 사내에서 사용하는데, 비용의 압박이 생겼다!

개발, 스테이징 환경 두가지 환경을 배포해서 사용해야 하기 때문에 : 비용의 압박

비용절감 지침이 내려옴!

내가 필요할때 간편하게 만들고 간편하게 지울수 있을것

안지워진 부분에서 비용이 청구되었을때 당황! 하기 때문에 잘 지울수 있는것도 매력!

 

# Terraformer 

이미 지어진 인프라를 역으로 코드화 해주는 구글에서 개발한 오픈소스 프로젝트

 

vpc

igw

routing table

subnet

 

테라폼 코드로 생성한 후 테라포머로 코드화 할수 있음.

아래는 테라포머 참고 자료

https://github.com/GoogleCloudPlatform/terraformer

 

GitHub - GoogleCloudPlatform/terraformer: CLI tool to generate terraform files from existing infrastructure (reverse Terraform).

CLI tool to generate terraform files from existing infrastructure (reverse Terraform). Infrastructure to Code - GitHub - GoogleCloudPlatform/terraformer: CLI tool to generate terraform files from e...

github.com


테라폼  동작과정?

init -> plan -> apply 순서대로 진행한다.

init시 테라폼 플러그인 폴더가 생성되며,
apply 시 테라폼 상태 파일이 생성된다.

다음장에 다루겠지만 테라폼 상태 파일은 백엔드 블록 부분을 통해 저장위치를 선언하며
필요시에는 외부 공유 스토리지를 통해 팀간의 협업을 고려하여 해당 State file을 관리한다.

terraform init

# terraform init 명령어로 테라폼을 시작하기 위한 준비를 진행합니다. 
# (backend 구성 초기화, 플러그인 설치 등)
# backend로 지정된 구성 설정을 초기화합니다.
# `.terraform` 폴더가 생성되며 관련한 플러그인을 가져옵니다.
# Provider를 기록하기 위해 암호화된 `.terraform.lock.hcl` 파일을 생성합니다.
terraform plan

# terraform plan 명령어로 변경될 인프라 내역을 보여줍니다.
# 선언된 언어가 어떠한 인프라를 생성할 지 예측된 결과를 보여줍니다.
# terraform plan -out [FILE_NAME] 형태로 저장이 가능하며, 
# terraform apply [FILE_NAME] 형태로 지정하여 배포할 수 있습니다.
terraform apply 

# ④ terraform apply 명령어로 인프라를 배포합니다.
# 인프라를 배포하는 명령어로 terraform plan에서 계획된 행위를 수행합니다.
# Provider와 API 연계하여 자원을 생성하며, 상태 정보를 백엔드 영역에 .tfstate 파일로 저장합니다.