728x90
반응형
Terraform의 프로비저너(provisioner)는 리소스가 생성된 후 추가 작업을 자동으로 수행할 수 있게 합니다.
이번 포스트에서는 local-exec, remote-exec 프로비저너와 함께 file 프로비저너를 사용하여 파일 전송을 자동화하는 방법을 설명하겠습니다.
1. local-exec 프로비저너
local-exec 프로비저너는 테라폼이 실행되는 환경(local)에서 명령을 실행합니다.
예를 들어 다음과 같이 수행할 커맨드를 정의할 수 있습니다.
resource "null_resource" "example" {
provisioner "local-exec" {
command = "echo The server's IP address is ${self.private_ip}"
}
}
2. local-exec 프로비저너
remote-exec 프로비저너는 원격지 환경(원격 서버)에서 명령을 실행합니다.
예를 들어 다음과 같이 SSH를 통해 서버에 접속하여 명령을 실행할 커맨드와 스크립트를 정의할 수 있습니다.
resource "null_resource" "example" {
provisioner "remote-exec" {
inline = [
"sudo apt-get update",
"sudo apt-get install -y nginx"
]
}
connection {
type = "ssh"
user = "ubuntu"
private_key = file("~/.ssh/id_rsa")
host = self.public_ip
}
}
3. file 프로비저너
file 프로비저너는 테라폼을 실행하는 시스템에서 연결 대상으로 파일 또는 디렉토리를 복사하는데 사용합니다.
file 프로비저너를 사용하여 로컬 파일을 원격 서버로 전송하여 구성파일이나 스크립트를 쉽게 배포할 수 있습니다.
resource "null_resource" "example" {
provisioner "file" {
source = "localfile.txt"
destination = "/remote/path/remote.txt"
}
connection {
type = "ssh"
user = "ubuntu"
private_key = file("~/.ssh/id_rsa")
host = self.public_ip
}
}
4. remote-exec와 file 프로비저너 활용 예시
1. AWS EC2 배포시 remote-exec/file 프로비저너를 활용하는 코드를 작성
resource "aws_instance" "apache" {
ami = data.aws_ami.latest_amazon_linux_2.id
instance_type = "t2.micro"
vpc_security_group_ids = [aws_security_group.apache_sg.id]
key_name = var.key_pair_name
tags = { Name = "${var.name}-apache-instance" }
}
resource "null_resource" "file" {
connection {
type = "ssh"
user = "ec2-user"
private_key = file("${path.module}/test.pem")
host = aws_instance.apache.public_ip
}
provisioner "file" {
source = "setup_apache.sh"
destination = "setup_apache.sh"
}
provisioner "remote-exec" {
inline = [
"chmod +x setup_apache.sh",
"./setup_apache.sh"
]
}
}
2. 코드 설명
- remote-exec와 file 프로비저너를 사용하기 위해 ec2에 연결할 connection 정보를 정의합니다.
connection {
type = "ssh"
user = "ec2-user"
private_key = file("${path.module}/test.pem")
host = aws_instance.apache.public_ip
}
- file 프로비저너를 사용하여 테라폼을 실행하는 환경(Mac)에서 생성한 ec2에 apache 설치 및 index.html파일 정의하는 shell script파일을 복사합니다.
provisioner "file" {
source = "setup_apache.sh"
destination = "setup_apache.sh"
}
- remote-exec 프로비저너를 사용하여 ec2내에서 shell script파일의 실행권한을 주고 실행하는 명령어 정의합니다.
provisioner "remote-exec" {
inline = [
"chmod +x setup_apache.sh",
"./setup_apache.sh"
]
}
728x90
반응형
'Terraform' 카테고리의 다른 글
AWS 트래픽 스파이크 처리 - Amazon Aurora와 Route 53 가중치 기반 라우팅 활용 (1) | 2024.11.03 |
---|---|
[Terraform] Import Block & Module 활용 & 개인적 생각 정리 (5) | 2024.10.20 |
[Terraform] terraform_data 리소스 (null_resource 비교) (0) | 2024.05.26 |
[Terraform] Moved Block을 통한 코드 리팩터링 & Provider alias (0) | 2024.05.26 |
[Terraform] count, for_each 등 실습예제 (0) | 2024.05.12 |