terraform provisioner local_exec , variable input example - unix1998/technical_notes GitHub Wiki

To use a variable for the input string and echo it in the local-exec provisioner, need modify the Terraform file to define a variable and then reference it in the command. Here's how you can do it:

  1. Define the Variable: Define the variable in the Terraform configuration.
  2. Prompt for Variable Input: Set the variable input to prompt manually.
  3. Use the Variable in the local-exec Command: Reference the variable in the local-exec command.

Here is the modified Terraform file:

# Define the variable
variable "echo_message" {
  description = "The message to be echoed"
  type        = string
}

# Use the variable in the null_resource
resource "null_resource" "example" {
  provisioner "local-exec" {
    command = "echo ${var.echo_message}"
  }
}

Steps to Use the Modified Terraform File

  1. Create the Terraform File: Create a file named main.tf and copy the above configuration into it.

    touch main.tf
    nano main.tf
    

    Paste the above configuration into the main.tf file and save it.

  2. Initialize the Directory: Initialize the Terraform working directory.

    terraform init
    
  3. Apply the Configuration: Apply the configuration. Terraform will prompt you to input the value for the echo_message variable.

    terraform apply
    

    When prompted, enter the message you want to be echoed.

    var.echo_message
      The message to be echoed
      Enter a value: Hello from Terraform!
    

Full Example

For a complete example, assuming the message "Hello from Terraform!" is to be echoed:

  1. Create the Directory: Create a directory for your Terraform configuration files.

    mkdir terraform-echo
    cd terraform-echo
    
  2. Create the Terraform File: Create and edit the main.tf file.

    touch main.tf
    nano main.tf
    

    Add the following content to the main.tf file:

    variable "echo_message" {
      description = "The message to be echoed"
      type        = string
    }
    
    resource "null_resource" "example" {
      provisioner "local-exec" {
        command = "echo ${var.echo_message}"
      }
    }
    
  3. Initialize Terraform:

    terraform init
    
  4. Apply the Configuration:

    terraform apply
    

    When prompted, enter the desired message:

    var.echo_message
      The message to be echoed
      Enter a value: Hello from Terraform!
    

This will output:

local-exec provisioner: Hello from Terraform!