Bootstrap FreeKB - Terraform - Run a local command (local-exec)
Terraform - Run a local command (local-exec)

Updated:   |  Terraform articles

Let's say you want to run a command on your Terraform system or on a remote system. There are two provisioners that can be used, local-exec and remote-exec. As an example, let's say you want to create the /tmp/foo.txt file on your Terraform system. In this scenario, you would use local-exec. 

AVOID TROUBLE

The local-exec provisioner must be within a resource block.

Let's say you have the following files on your Terraform server.

├── locals.tf
├── modules.tf
├── outputs.tf
├── provider.tf
├── terraform.tfstate
├── variables.tf
├── child (directory, child module)
│   ├── data.tf
│   ├── outputs.tf
│   ├── resources.tf

 

Let's say providers.tf has the following.

terraform {
  required_providers {
    docker = {
      source  = "kreuzwerker/docker"
    }
  }
}

provider "docker" {}

 

Let's say modules.tf has the following.

module "child" {
  source = "./child"
}

 

And perhaps resources.tf in your child module has the following to create an Nginx image on Docker.. Notice that the local-exec provisioner is within the resource block, and the local-exec command will create the /tmp/foo.txt file on the Terraform system.

resource "docker_image" "nginx" {
  name         = "nginx:latest"
  keep_locally = false

  provisioner "local-exec" {
    command = "touch /tmp/foo.txt"
  }
}

 

When the terraform apply command is run, the output should contain something like this.

docker_image.nginx: Provisioning with 'local-exec'...
docker_image.nginx (local-exec): Executing: ["/bin/sh" "-c" "touch /tmp/foo.txt"]

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter a048f8 in the box below so that we can be sure you are a human.