Provisioning
After we define our providers and resources to establish our environment, we use provisioners to deploy and execute code in that environment. You can deploy things like scripts and then use remote-exec
to execute them. This is accomplished via SSH, and you can override the connection details as well.
hcl
resource "aws_key_pair" "mykey" {
key_name = "mykey"
public_key = file(var.PATH_TO_PUBLIC_KEY)
}
resource "aws_instance" "example1" {
ami = ${lookup(var.AMIS, var.AWS_REGION)}
instance_type = "t2.micro"
key_name = aws_key_pair.mykey.key_name
provisioner "file" {
source = "deploy.sh"
destination = "/etc/deploy.sh"
}
provisioner "remote-exec" {
inline = [
"chmod +x /tmp/script.sh",
"sudo sed -i -e 's/\r$//' /tmp/script.sh", # Remove the spurious CR characters.
"sudo /tmp/script.sh",
]
}
connection {
user = var.instance_user
password = var.instance_password
}
# or use keys
connection {
host = coalesce(self.public_ip, self.private_ip)
type = "ssh"
user = var.instance_user
private_key = file(var.PATH_TO_PRIVATE_KEY)
}
}