TF Series: Provisioners

This blog is the sub-part of "Terraform Associate 003 Series". To navigate back to the main Blog Page and know other topics of this series, click here. Here, we will be covering the Provisioners of Terraform.

What are Provisioners?

Provisioner are built-in components, used to execute scripts or shell commands on a local or remote machine as part of resource creation/deletion.

Terraform Provisioners

Local-exec Provisioner

The local-exec provisioner invokes a local executable after a resource is created. This invokes a process on the machine running Terraform, not on the resource.
Example:

resource "aws_instance" "web" {
  # ...

  provisioner "local-exec" {
    command = "echo ${self.private_ip} >> private_ips.txt"
  }
}

Remote-exec Provisioner

The remote-exec provisioner invokes a script on a remote resource after it is created. This can be used to run a configuration management tool, bootstrap into a cluster, etc.
This has 3 types; we can use only mode at a time.

  • Inline

  • Script

  • Scripts.

File Provisioners

The file provisioner copies files or directories from the machine running Terraform (our local machine) to the newly created resource. The file provisioner supports both ssh and winrm type connections.

Arguments Supported:

  • Source: The local file we want to upload to the remote machine.

  • Content: A file or a Folder.

  • Destination: Where you want to upload the file on the remote machine.

Note: You may require the connection block within the provisioner for authentication.

Connection Block: A Connection block tells a provisioner or resource how to establish a connection.

Null Resources & Terraform Data

  • Null Resources: It is a placeholder for resources that have no specific association to a provider resources.

    We usually use Null Resources to Trigger a resource.

  • Terraform Data: Similar to Null Resource. But the key difference is:
    It does not require or the configuration of a provider. Because, when we install Null resource, it installs the provider as Null.

Example of Null Resource:

resource "null_resource" "main"{
    triggers = {
        version = var.version
    }

Provisioners "local-exec"{
    command = "echo..."}
    }
}

Example of Terraform Data: [Recommended]

resource "terraform_data" "main"{
    triggers_replace = {
        version
    }

Provisioners "local-exec"{
    command = "echo..."}
    }
}