File Provisioner in Terraform: What It Is and How It Works
file provisioner in Terraform copies files or folders from your local machine to a remote resource during deployment. It helps transfer configuration files, scripts, or other data to servers as part of infrastructure setup.How It Works
The file provisioner acts like a delivery person who takes files from your computer and places them on a remote machine you are setting up. When Terraform creates or updates a resource like a virtual machine, the provisioner connects to that machine using SSH or WinRM and copies the specified files.
This process happens after the resource is created but before Terraform finishes the deployment. It ensures the remote machine has the necessary files to run software or configure itself properly. Think of it as packing your suitcase (local files) and handing it to a hotel clerk (provisioner) who puts it in your hotel room (remote machine).
Example
aws_instance.example and SSH access set up.resource "aws_instance" "example" { ami = "ami-0c55b159cbfafe1f0" instance_type = "t2.micro" provisioner "file" { source = "setup.sh" destination = "/home/ec2-user/setup.sh" connection { type = "ssh" user = "ec2-user" private_key = file("~/.ssh/id_rsa") host = self.public_ip } } }
When to Use
Use the file provisioner when you need to send files from your computer to a remote machine during infrastructure setup. This is useful for:
- Uploading configuration files or scripts to servers
- Deploying application code or certificates
- Preparing remote machines with necessary resources before running commands
However, it is best for small, simple file transfers. For complex deployments, consider using configuration management tools or cloud-init scripts.
Key Points
- The
fileprovisioner copies files from local to remote machines during deployment. - It requires a connection block to access the remote resource (SSH or WinRM).
- Runs after resource creation but before Terraform finishes.
- Best for simple file transfers, not large or complex deployments.