variable "instance_security_group_name" { description = "The name of the security group for the EC2 Instances" type = string default = "terraform-example-instance" }
variable "http_port" { description = "The port the server will use for HTTP requests" type = number default = 80 }
variable "ssh_port" { description = "The port the server will use for SSH requests" type = number default = 22 }
variable "alb_name" { description = "The name of the ALB" type = string default = "terraform-asg-example" }
variable "alb_security_group_name" { description = "The name of the security group for the ALB" type = string default = "terraform-example-alb" }
# vi main.tf
provider "aws" { => provider 정보는 main 파일에만 넣어주기, provider 정보가 중복되면 애러 발생 region = "ap-northeast-2" }
- new-vpc -
resource "aws_vpc" "new_vpc" { => 자원의 이름(Terraform이 지정한 이름 : "aws_vpc", 내가 정하는 자원의 이름 : "new_vpc") cidr_block = "192.168.0.0/16" enable_dns_hostnames = true enable_dns_support = true enable_dns_support = true : resolver를 설정하는 코드, 루트 DNS와 트래픽 송수신 instance_tenancy = "default"
tags = { Name = "NEW-VPC" } }
data "aws_availability_zones" "available" { => data : aws가 이미 가지고 있는 정보를 가져올 때 data 사용 state = "available" }
resource "aws_subnet" "new_public_subnet_2a" { vpc_id = aws_vpc.new_vpc.id cidr_block = "192.168.0.0/20" map_public_ip_on_launch = true => 퍼블릭 IP 활성화 : default는 false availability_zone = data.aws_availability_zones.available.names[0] => names : ap-northeast-2a = [0], 2b = [1], 2c = [2], 2d = [3]와 같은 AZ의 이름 tags = { Name = "NEW-PUBLIC-SUBNET-2A" => defalut 서브넷과 구분하기 위해 tag 달기 } }
resource "aws_security_group" "instance" { name = var.instance_security_group_name => 여기서 name은 tag와 구분됨 => var : 어딘가에 variable을 정의 해놓고 그 값을 활용함(variable은 해당 라인의 전, 후 어디 있어도 관계 없음) => instance_security_group_name : 변수명(해당 변수값에 정의된 default 정보를 가져오게 됨) vpc_id = aws_vpc.new_vpc.id => 전에 만들어 놓은 vpc의 id를 참조함
resource "aws_launch_configuration" "example" { => 실습 시에 시작 템플릿(lunch template)을 ASG에 적용 시켰음, 여기서는 시작 구성(launch configuration)이용 => 시작 구성은 버전 관리 불가능 image_id = "ami-0fd0765afb77bcca7" instance_type = "t2.micro" security_groups = [aws_security_group.instance.id] key_name = "new-key" user_data = file("user-data.sh") => user-data.sh 파일을 만들어 놓고, 해당 파일의 정보를 읽어서 사용 user-data.sh 파일 : ec2를 만든 시간을 echo로 넣는 것(로드밸런싱 되고 있는 것을 확인하기 위함), sleep으로 10후 부하 # Required when using a launch configuration with an auto scaling group. lifecycle { create_before_destroy = true => 만들어진 후에 제거해라 } }
target_group_arns = [aws_lb_target_group.asg.arn] => 로드 밸런서를 이용할 것이기에 타깃 그룹도 설정 => arn(amazon resource number) : 타깃 그룹 자원의 넘버 health_check_type = "ELB" => 원래 ALB가 타깃 그룹의 EC2 헬스 체크(단순히 서버가 다운 되지 않았는지 확인) => 거기에 더해 ASG가 ELB에 헬스체크(메모리나 자원의 부족 확인 가능)
min_size = 2 => 아무리 사용량이 없어도, 단일 장애 지점(SPOF)을 회피하기 위해 2개 이상의 서버를 유지 => SPOF : 동작 하지 않으면 전체 시스템이 중단되게 만드는 요소 => min_size는 desired_capacity 이하의 사이즈로 셋팅해야 함 desired_capacity = 2 max_size = 4
tag { key = "Name" value = "terraform-asg-example" propagate_at_launch = true => true : terraform-asg-example이라는 태그의 이름을 늘어 나는 ec2에서도 사용하겠다는 의미 => false : 나중에 생기는 ec2는 태그가 없는 상태로 생성됨 } }
resource "aws_lb" "example" {
name = var.alb_name
load_balancer_type = "application" => ALB를 만들 것이라서 type을 application으로 지정, NLB를 만들 것이라면 network로 지정 subnets = [ aws_subnet.new_public_subnet_2a.id, aws_subnet.new_public_subnet_2b.id, aws_subnet.new_public_subnet_2c.id, aws_subnet.new_public_subnet_2d.id ] => 로드 밸런서 밑에 넣어 줄 서브넷들, 실습에서는 t2.micro를 사용해서 2a와 2c에만 인스턴스가 생성될 것 security_groups = [aws_security_group.alb.id] }
# Allow all outbound requests egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] } } resource "aws_autoscaling_policy" "scale_in" { name = "ScaleInPolicy" autoscaling_group_name = aws_autoscaling_group.example.name adjustment_type = "ChangeInCapacity" => desired capacity 수의 변화, 스케일링 될 때 우선 desired capacity가 변화하고 인스턴스가 늘어나거나 줄어듦 scaling_adjustment = -1 => 인스턴스를 한개 지우겠다는 의미 cooldown = 300 => cooldown : 연속적으로 스케일링 되어야 하는 상황에서 중간에 간격을 두어 오동작을 방지 }
resource "aws_cloudwatch_metric_alarm" "scale_in" { => 클라우드 와치의 알람이 scale in의 트리거 역할 alarm_description = "Monitors CPU utilization for Terramino ASG" alarm_actions = [aws_autoscaling_policy.scale_in.arn] => arn : 액션 부분인 오토 스케일링 policy와 트리거인 클라우드 와치의 알람을 연결 alarm_name = "ScaleInAlarm" comparison_operator = "LessThanOrEqualToThreshold" => CPU 사용률 임계값인 30% 이하 namespace = "AWS/EC2" => 지표에서 EC2 인스턴스를 대상으로 측정 metric_name = "CPUUtilization" threshold = "30" evaluation_periods = "1" => 단 한 번이라도 period = "300" => 5분 마다 한 번씩 측정치를 체크함 statistic = "Average" => 5분 동안의 평균 => 단 한 번이라도 5분 평균 값이 30% 이하로 떨어지면, scale in 알람 발생
dimensions = { AutoScalingGroupName = aws_autoscaling_group.example.name } => dimensions : 알람을 오토스케일링 그룹 내에 있는 오토 스케일링 policy와 연관해서 사용할 것 => cf.) scale in을 scale down이라고 표현하기도 함, 원래 scale down은 scale up의 반대 개념이지만 scale in의 반대로도 쓰임. 또한 scale out을 scale up으로 표현하기도 함.( = 수직적, 수평적 확장 축소와 관계 없이 용어를 사용하기도 함) 테라폼 레지스트리에서도 sacle in을 scale down으로 표현하고, scale out을 scale up으로 표현함 } resource "aws_autoscaling_policy" "scale_out" { name = "ScaleOutPolicy" autoscaling_group_name = aws_autoscaling_group.example.name adjustment_type = "ChangeInCapacity" scaling_adjustment = 1 cooldown = 300 }
# vi outputs.tf => 파일의 이름은 임의로 지정 가능 output "alb_dns_name" { => 출력될 이름 alb_dns_name 역시 임의로 정해도 됨 value = aws_lb.example.dns_name description = "The domain name of the load balancer" }
# yum install -y azure-cli => 위에서 정의한 저장소에서 최신의 CLI 도구를 내려 받음 # az upgrade # az --version # az login # resourceGroup=VMTutorialResources # location=koreacentral # az group create --name $resourceGroup --location $location # vnetName=TutorialVNet1 # subnetName=TutorialSubnet1 # vnetAddressPrefix=10.133.0.0/16 # subnetAddressPrefix=10.133.0.0/24 # az network vnet create \ --name $vnetName \ --resource-group $resourceGroup \ --address-prefixes $vnetAddressPrefix \ --subnet-name $subnetName \ --subnet-prefixes $subnetAddressPrefix
# az network vnet list # az vm image list # vmName=TutorialVM1 # vi httpd.txt #!/bin/bash apt update apt install -y apache2 echo "<h1>Hello Azure CLI</h1>" > /var/www/html/index.html
# az vm open-port -n $vmName -g $resourceGroup --port 443 --priority 999 => 포트 번호를 오픈하는 방법 2 => 앞에서 priority 900을 셋팅했으므로 여기서는 999로 설정, priority는 기본이 900 # az vm list-ip-addresses # ssh -i .ssh/id_rsa azureuser@20.214.201.208 VM에 접속 # az vm delete --resource-group $resourceGroup --name $vmName --yes => 특정 vm만 지우고 싶을 때 사용 # az group delete -n $resourceGroup # az group delete -n NetworkWatcherRG
--- azure_set ---
# git clone https://github.com/hali-linux/azure_set.git # vi variables.tf variable "resource_group_name_prefix" { default = "rg" description = "Prefix of the resource group name that's combined with a random ID so name is unique in your Azure subscription." }
variable "resource_group_location" { default = "koreacentral" description = "Location of the resource group." }
# vi main.tf provider "azurerm" { features {} }
resource "random_pet" "rg-name" { => random_pet : 리소스 그룹의 이름을 랜덤으로 만들어주는 기능 prefix = var.resource_group_name_prefix }
resource "azurerm_resource_group" "rg" { => 리소스 그룹을 만드는 리소스 name = random_pet.rg-name.id location = var.resource_group_location }
# Connect the security group to the network interface resource "azurerm_network_interface_security_group_association" "example" { network_interface_id = azurerm_network_interface.myterraformnic.id network_security_group_id = azurerm_network_security_group.myterraformnsg.id }