티스토리 뷰

T101 study

[1주차] 기본 사용 1/3

haru224 2024. 6. 13. 06:06

CloudNet@ 가시다님이 진행하는 Terraform 101 Study 4기 스터디 내용 참고.

스터디 교재 : ‘테라폼으로 시작하는 IaC’ (한빛 미디어, 김민수 외 지금) 책의 내용 참고

 -. https://www.aladin.co.kr/m/mproduct.aspx?ItemId=317519064

 

 

1. 테라폼이란


하시코프 사에서 공개한 IaC 도구.

하시코스사는 빠르고 효율적으로 강력한 어플리케이션을 만들고 제공할 수 있도록 인프라 관리에서 가장 어렵고 가장 중요한 문제를 해결한다는 목표로 2012년 설립되었고 2014년 테라폼을 처음 출시하였고, 2021년 1.0 버전을 출시



2. 테라폼의 가장 중요한 세가지 철학


  1) 워크플로에 집중: 어떤 기술이 사용되더라도 워크플로를 통해 환경변화에 구애받지 않도록 설계.

  2) 코드형 인프라(IaC): 구현/구성이 코드로 표현되어 문서화된 실행 가능한 텍스트, 기록 관리 가능

  3) 실용주의: 새로운 아이디어와 접근방식, 기술을 다시 평가하여 적응할 수 있는 실용주의을 바탕으로 혁신 실현

 

 

3.  실행환경 구성


  1) wsl (windows sub linux) 설치 및 ssh 접속

  2) terraform 설치:

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

terraform version

 

설치참고 link

 

Install | Terraform | HashiCorp Developer

Explore Terraform product documentation, tutorials, and examples.

developer.hashicorp.com

 

 

4. terraform 기본 명령어


  1) terraform init

     테라폼 구성 파일이 있는 작업 디렉터리를 초기화 하는데 사용. 테라폼에서 사용되는 프로바이더, 모듈등의 지정된 버전에 맞춰 루트 모듈을 구성하는 역할

   2) terraform validate

     디렉터리에 있는 테라폼 구성 파일의 유효성을 확인. 대상이 되는 인프라와 서비스의 상태를 확인하기 위한 원격 작업이나 API 작업은 발생하지 않고, 코드적인 유효성만 검토

   3) terraform plan

     테라폼으로 적용할 인프라의 변경 사항에 관한 실행 계획을 생성. 출력되는 결과를 확인하여 어떤 변경이 적용될지 사용자가 미리 검토하고 이해하는 도움

   4) terraform apply

       계획을 기반으로 작업을 실행

    5) terraform destroy

       모든 리소스를 삭제

mkdir 03.lifecycle
cd 03.lifecycle

main.tf

terraform {
  required_version = ">= 1.0.0"
  required_providers {
    local = {
      source  = "hashicorp/local"
      version = ">=2.0.0"
    }
  }
}

resource "local_file" "abc" {
  content  = "123!"
  filename = "${path.module}/abc.txt"

}



terraform init
terraform plan
terraform apply
terraform destroy

 

 

 

 

* 테라폼 작업 시 VSCODE 를 사용하면 파일편집, 터미널창에서 명령어 실행, 다양한 확장프로그램을 사용 가능

  설치 참고 Link

 

Visual Studio Code - Code Editing. Redefined

Visual Studio Code is a code editor redefined and optimized for building and debugging modern web and cloud applications.  Visual Studio Code is free and available on your favorite platform - Linux, macOS, and Windows.

code.visualstudio.com

 

 

5. terraform으로 AWS EC2 생성


  * aws cli 설치 Link / aws 접속을 위한 자격증명 Link

 

mkdir t101-1week-ec2
cd t101-1week-ec2


#최신 ami 가져오기
AL2ID=`aws ec2 describe-images --owners amazon --filters "Name=name,Values=amzn2-ami-hvm-2.0.*-x86_64-gp2" "Name=state,Values=available" --query 'Images|sort_by(@, &CreationDate)[-1].[ImageId]' --output text` echo $AL2ID

main.tf

provider "aws" {
  region = "ap-northeast-2"
}

resource "aws_instance" "example" {
  ami           = "$AL2ID"
  instance_type = "t2.micro"
}



# 초기화
terraform init

# plan 확인
terraform plan

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

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



# ec2 삭제
terraform destroy

 

 

 

 

 

 

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 삭제

 

 

6. terraform으로 AWS EC2 web 서버 생성 [도전과제1]


terraform data block 참조 Link

 

Provision infrastructure with Cloud-Init | Terraform | HashiCorp Developer

Deploy preconfigured infrastructure with Terraform using the Cloud-Init tool.

developer.hashicorp.com

 

user_data.sh

#!/bin/bash
apt update
apt install -y apache2
systemctl start apache2
systemctl enable apache2
echo "Hello, I am haru" | tee /var/www/html/index.html

main.tf

provider "aws" {
  region = "ap-northeast-2"
}

resource "aws_instance" "apache" {
  ami           = "ami-0bcdae8006538619a"
  instance_type = "t2.micro"
  vpc_security_group_ids = [aws_security_group.apache.id]

  user_data = data.template_file.user_data.rendered

  tags = {
    Name = "terraform-Study-101"
  }
}

data "template_file" "user_data" {
  template = file("./user_data.sh")
}

resource "aws_security_group" "apache" {
  name = var.security_group_name

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 65535
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

variable "security_group_name" {
  description = "The name of the security group"
  type        = string
  default     = "terraform-apache-instance"
}

output "public_ip" {
  value       = aws_instance.apache.public_ip
  description = "The public IP of the Instance"
}

 

해당 서버에서 web 서버 정상접속 -> 닉네임 출력

 

 

'T101 study' 카테고리의 다른 글

[7주차] 테라폼으로 AWS EKS 배포  (0) 2024.07.27
[5주차] Module & Runner  (0) 2024.07.13
[4주차] Provider & State  (0) 2024.06.30
[3주차] 기본 사용 3/3  (0) 2024.06.29
[2주차] 기본 사용 2/3  (0) 2024.06.22
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/05   »
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 31
글 보관함