[AWS] IaC, ansible, terraform 실습

김윤섭·2024년 7월 18일
2
post-thumbnail

개요

ansible과 terraform을 실습해보면서 IaC에 대한 이해를 높인다.

IaC (Infrastructure as Code)

인프라스트럭처를 코드로 관리하고 프로비저닝하는 방식

IAM 사용자 권한 설정 및 키 발급

키 경로는 입력 안해도된다. 그냥 test.pem 이면 test로만

aws configure
AWS Access Key ID [None]: 아이디
AWS Secret Access Key [None]: 비번
Default region name [None]: ap-northeast-2
Default output format [None]: json

terraform 실습

terraform : HashiCorp에서 개발한 오픈 소스 IaC 도구

  • 클라우드 중립적 (AWS, Azure, GCP 등 다양한 프로바이더 지원)

  • 선언적 언어 사용 (HCL: HashiCorp Configuration Language)

  • 상태 관리 기능 제공

테라폼 설정파일 작성

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

variable "instance_count" {
  default = 2
}

variable "instance_type" {
  default = "t2.micro"
}

resource "aws_vpc" "main" {
  cidr_block = "192.168.0.0/16"

  tags = {
    Name = "main-vpc"
  }
}

resource "aws_subnet" "main" {
  vpc_id            = aws_vpc.main.id
  cidr_block        = "192.168.1.0/24"
  availability_zone = "ap-northeast-2a"
  map_public_ip_on_launch = true

  tags = {
    Name = "main-subnet"
  }
}

resource "aws_internet_gateway" "main" {
  vpc_id = aws_vpc.main.id

  tags = {
    Name = "main-igw"
  }
}

resource "aws_route_table" "main" {
  vpc_id = aws_vpc.main.id

  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = aws_internet_gateway.main.id
  }

  tags = {
    Name = "main-route-table"
  }
}

resource "aws_route_table_association" "main" {
  subnet_id      = aws_subnet.main.id
  route_table_id = aws_route_table.main.id
}

resource "aws_security_group" "main" {
  vpc_id = aws_vpc.main.id

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

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = {
    Name = "main-sg"
  }
}

resource "aws_instance" "web" {
  count         = var.instance_count
  ami           = "ami-04ea5b2d3c8ceccf8"
  instance_type = var.instance_type
  key_name      = "<ssh 키 이름>"
  subnet_id     = aws_subnet.main.id
  vpc_security_group_ids = [aws_security_group.main.id]

  tags = {
    Name = "WebServer-${count.index}"
  }
}

output "instance_ips" {
  value = aws_instance.web.*.public_ip
}

테라폼 실행

terraform init 
terraform plan 
terraform apply

테라폼이 실행되는 과정

인스턴스가 만들어지고 실행되었다.

vpc, 보안그룹등 거의 모든 aws 리소스를 만들 수 있다.

ansible 실습

ansible : Red Hat에서 개발한 오픈 소스 자동화 도구

  • 에이전트리스 아키텍처 (SSH를 통한 통신)
  • YAML 기반의 플레이북 사용
  • 멱등성 (Idempotency) 보장

Ansible 인벤토리 작성 (hosts.ini)

echo "[webservers]" > hosts.ini
terraform output -json instance_ips | jq -r '.[]' >> hosts.ini

Ansible 설정파일 작성 (ansible.cfg)

[defaults]
inventory = hosts.ini
private_key_file = /Users/zc351/Desktop/kakao-bootcamp/test.pem
host_key_checking = False
remote_user = ec2-user

Playbook 파일 작성 (playbook.yml)

---
- hosts: webservers
  become: yes
  tasks:
    - name: Install Nginx
      yum:
        name: nginx
        state: present
    - name: Start Nginx
      service:
        name: nginx
        state: started
        enabled: true

앤서블 설정이 완료되면 로컬환경에서 다음 명령어로 앤서블을 실행해준다.

ansible-playbook -i hosts.ini playbook.yml

SSH로 인스턴스에 접속

ps -ef | grep nginx

nginx 실행 확인할수 있다.

실습환경 정리

terraform destroy

AWS 리소스가 삭제된 것을 확인 할 수 있다.

결론

테라폼으로 기본 인프라를 구축
앤서블로 해당 인프라에 소프트웨어를 설치하고 구성한다.

그동안은 수동으로 직접 AWS 홈페이지에 접속하여 인프라를 구성했는데 이는 실수할 확률도 높고 그러면 어디서 잘못했는지 추적이 어려워 어려움이 있었다. 이러한 과정들을 전부 코드로 관리해 실수도 줄이고 수정도 용이한 IaC 를 공부해보면서 필요성을 알게 되었다.

0개의 댓글