Provision in Terraform
If you need to do some initial setup on your instances, then provisioners let you upload files, run shell scripts, or install and trigger other software like configuration management tools, etc.
Defining a Provisioner
provider "aws" {
access_key = "AXXXXX"
secret_key = "XXXXXX"
region = "us-east-2"
}
resource "aws_instance" "Feenix_test" {
ami = "ami-0cd3dfa4e37921605"
instance_type = "t2.micro"
tags {
name = "feenix_web"
}
provisioner "local-exec" {
command = "echo ${aws_instance.Feenix_test.public_ip} > public-ip.txt"
}
}
This adds a provisioner block within the resource block. Multiple provisioner blocks can be added to define multiple provisioning steps.
Terraform supports multiple provisioners, but for this example, we are using the local-exec provisioner.
Running Provisioners
C:\Users\bnarayan\terraform>terraform apply
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
+ aws_instance.Feenix_test
id: <computed>
ami: "ami-0cd3dfa4e37921605"
arn: <computed>
.
.
aws_instance.Feenix_test: Provisioning with 'local-exec'...
aws_instance.Feenix_test (local-exec): Executing: ["cmd" "/C" "echo 3.19.30.122 > public-ip.txt"]
aws_instance.Feenix_test: Creation complete after 59s (ID: i-01b6a6e957358ecf1)
we can see IP address stored in the file.
C:\Users\bnarayan\terraform>type public-ip.txt 3.19.30.122