output "instance_ip_addr" {
description = "instance ip address"
value = aws_instance.server.private_ip
}
terraform output
locals {
service_name = "forum"
owner = "Community Team"
}
resource "aws_instance" "example" {
# ...
tags = local.service_name
}
var.tf
variable "project_name" {
description = "Project Name"
type = string
default = "My First Project"
}
local.tf
locals{
common_tags = {
Name = "My Terraform"
project_name = var.project_name
}
}
main.tf
tag = local.common_tags
userdata
#인라인 방식
user_dataa = <<-EOF
#!/bin/sh
yum -y install httpd
systemctl enable --now httpd
echo "hello world" > /var/www/html/index.html
EOF
#인라인 방식
resource "aws_instance" "app_web" {
...
user_data = <<-EOF
#!/bin/sh
echo "hello wolrd"
EOF
...
}
cat <<EOF > a.txt
> a
> b
> c
> d
> EOF
resource "aws_instance" "app_web" {
...
user_data = file("userdata.sh")
...
}
userdata.sh
user_dataa = <<-EOF
#!/bin/sh
yum -y install httpd
systemctl enable --now httpd
echo "hello world" > /var/www/html/index.html
EOF
...
resource "aws_instance" "web" {
# ...
provisioner "local-exec" {
command = "echo The server's IP address is ${self.private_ip}"
}
}
프로비저너 종류
resource "aws_instance" "web" {
# ...
# Copies the myapp.conf file to /etc/myapp.conf
provisioner "file" {
source = "conf/myapp.conf"
destination = "/etc/myapp.conf"
}
}
resource "aws_instance" "web" {
# ...
provisioner "local-exec" {
command = "echo ${self.private_ip} >> private_ips.txt"
}
}
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 연결이 필요함
#속해있는 프로비저너에만 커넥션 적용
provisioner "file" {
connection {
type = "ssh"
user = "root"
password = "${var.root_password}"
host = "${var.host}"
}
}
#모든 프로비저너에 공통으로 커넥션적용
provisioner "file" {
}
provisioner "file" {
}
connection {
}
#connection example
connection {
user = "ec2-user"
host = aws_instance.app_server.public_ip
private_key = file("/home/vagrant/.ssh/id_rsa") #ssh-keygen 으로 생성 했으면 미리 생성이 되어 있음
}
curl ifconfig.me 자기 컴퓨터 ip확인
오염되다, 문제있다, 오류
리소스를 생성/변경 하다가 오류가 생기면, 해당 리소스를 Taint 처리
terraform taint <RESOURCE>
terraform untaint <RESOURCE>
Taint 처리된 리소스는 다음 작업시 무조건 재생성
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"
}
module "myvpc" {
source =
...입력 변수...
}
resource "aws_instance" "web" {
subnet_id = module.myvpc.<출력값>
}
모듈 초기화
terraform init