1. AWS CLI - Role 설정
EC2에 AWS CLI Access Key or Role이 없는 경우
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, Name]' --output text
2. main.tf 작성
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
# tf 파일 수정
provider "aws" {
region = "ap-northeast-1"
}
resource "aws_vpc" "example" {
cidr_block = "10.100.0.0/16"
}
resource "aws_subnet" "example" {
vpc_id = aws_vpc.example.id
cidr_block = "10.100.1.0/24"
map_public_ip_on_launch = true
}
resource "aws_instance" "example" {
ami = "$AL2ID"
instance_type = "t2.micro"
subnet_id = aws_subnet.example.id
tags = {
Name = "aews-study"
}
}
EOT
3. ssh 새로 열어 watch로 모니터링
# 모니터링
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
4. terraform init, plan, apply
# 초기화
terraform init
ls -al
tree .terraform
# plan 확인
terraform plan
# apply 실행
terraform apply
Enter a value: yes 입력
...
5. terraform destroy
# 리소스 삭제
terraform destroy
# 리소스 삭제 : yes없이
terraform destroy -auto-approve
..