컬쥐네 다락방

Terraform | 프로비저너(Provisioner) 본문

클라우드/Terraform

Terraform | 프로비저너(Provisioner)

코딩하는 갱얼쥐 2022. 4. 26. 16:24

Provisioner

테라폼 프로비저너(provisioner)는 테라폼을 실행할 때 부트스트랩, 구성 관리 또는 정리 작업을 수행하기 위해 로컬 시스템이나 원격 시스템에서 스크립트를 실행하는데 사용된다. 프로비저너에는 로컬 시스템에서 스크립트를 실행하는 local-exec , 원격 리소스에서 스크립트를 실행하는 remote-exec, 원격 리소스에서 셰프 클라이언트를 실행하는 chef 및 원격 리소스로 파일을 복사하는 file 등이 있다.

resource "aws_instance" "web" {
  # ...

  provisioner "local-exec" {
    command = "echo The server's IP address is ${self.private_ip}"
  }
}

프로비저너 종류

  • file: 파일 복사

    resource "aws_instance" "web" {
    # ...
    
    # Copies the myapp.conf file to /etc/myapp.conf
    provisioner "file" {
      source      = "conf/myapp.conf"
      destination = "/etc/myapp.conf"
    }
    }
  • local_exec: 로컬 머신에서 명령 실행

    resource "aws_instance" "web" {
    # ...
    
    provisioner "local-exec" {
      command = "echo ${self.private_ip} >> private_ips.txt"
    }
    }
  • remote_exec: 원격 머신에서 명령 실행

    resource "aws_instance" "web" {
    # ...
    
    # Establishes connection to be used by all
    # generic remote provisioners (i.e. file/remote-exec)
    connection {
      type     = "ssh"
      user     = "root"
      password = var.root_password
      host     = self.public_ip
    }
    
    provisioner "remote-exec" {
      inline = [
        "puppet apply",
        "consul join ${aws_instance.web.private_ip}",
      ]
    }
    }

프로비저너 연결

SSH 연결이 필요함

  • file
  • remote_exec
  provisioner "file" {
      connection {
        type     = "ssh"
        user     = "root"
        password = "${var.root_password}"
        host     = "${var.host}"
      }
  }
  provisioner "file" {
  }

  provisioner "file" {
  }

  connection {
  }

Taint

오염되다, 문제있다, 오류

프로비저너는 terraform apply명령에 대해 생성할 때만 실행되고 그 뒤에 업데이트되거나 하지 않는다. 그래서 provisioner가 실패하면 리소스가 잘못되었다고 판단해 다음 terraform apply할 때 제거하거나 다시 생성한다.

리소스를 생성/변경 하다가 오류가 생기면, 해당 리소스를 Taint 처리
terraform taint <RESOURCE>

terraform untaint <RESOURCE>

Taint 처리된 리소스는 다음 작업시 무조건 재생성

Ansible 실행 방법

  1. AMI 이미지 내에 ansible을 미리 설치
    • file로 플레이북 및 파일 복사
    • remote-exec로 실행
    • ansible-playbook a.yaml -c local
  2. 로컬에서 실행
    • 로컬에 ansible이 설치되어 있어야 함
    • local-exec로 인벤토리 생성
      • self.public_ip
    • local-exec로 ansible-playbook 실행
  connection {
    user        = "ec2-user"
    host        = self.public_ip
    private_key = file("/home/vagrant/.ssh/id_rsa")
    timeout     = "1m"
  }

  provisioner "local-exec" {
    command = "echo ${self.public_ip} ansible_user=ec2-user > inven.ini"
  }

  provisioner "local-exec" {
    command = "ansible-playbook -i inven.ini web_install.yaml -b"
  }
Comments