terraform Provisioners:
local-exec: Run command on the running terraform (not the resource)
remote-exec: run command on vm (ssh/winrm)
- connection
file: copy files/directories to remote server
examples:
provisioner "local-exec" {
when = create
command = "echo ${self.public_ip} >> public_ips.txt"
}
provisioner "file" {
when = create
source = "C:\\Users\\ramja\\.ssh\\id_ed25519.pub"
destination = "/home/ubuntu/.ssh/authorized_keys"
}
provisioner "remote-exec" {
when = create
inline = [
"sudo apt-get update -y",
"sudo apt-get install apache2 -y",
"sudo systemctl enable apache2",
"sudo systemctl start apache2",
"sudo systemctl status apache2"
]
}
provisioner "local-exec" {
when = destroy
command = "echo destory vm >> destory.txt"
}
create windows server and add file and remote provisioner
- ami – windows server
- remote – install dotnet (user choco)
## refer below example
resource "aws_instance" "winserver" {
ami = "ami-0b2f6494ff0b07a0e" # Example Windows Server 2022 AMI, update for your region
instance_type = "t3.medium"
key_name = "my-keypair"
vpc_security_group_ids = [aws_security_group.allow_winrm.id]
subnet_id = aws_subnet.my_subnet.id
tags = {
Name = "WindowsServerWithApache"
}
provisioner "remote-exec" {
inline = [
# Install Chocolatey
"Set-ExecutionPolicy Bypass -Scope Process -Force",
"[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072",
"iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))",
# Refresh environment
"refreshenv",
# Install Apache HTTP Server
"choco install apache-httpd -y",
# Ensure Apache service starts
"Start-Service Apache2.4"
]
connection {
type = "winrm"
user = "Administrator"
password = "YourAdminPassword123!"
host = self.public_ip
}
}
}
resource "aws_security_group" "allow_winrm" {
name = "allow_winrm"
description = "Allow WinRM access"
vpc_id = aws_vpc.my_vpc.id
ingress {
from_port = 5986
to_port = 5986
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"]
}
}