1

I'm trying to run a PowerShell script inside a terraform script. I tried to use the local-exec function but it throws the following error.

Error: Unknown root level key: provisioner

I have included the script below.

I would be glad if someone could provide me with a solution.

provisioner "local-exec" {
  inline = ["powershell.exe -File C:\\Users\\Boopathi Kumar\\Downloads\\poscript1.ps1"]
}

1 Answer 1

2

Provisioners must be ran as part of a resource rather than a top level resource.

Normally this would be ran against an instance such as with the examples given in the above linked docs:

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

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

Which writes the IP address of the instance to a file local to wherever Terraform is being ran.

If you don't have any link to a resource at all (you just want something to happen regardless of any resources changing) you can use the null_resource which is designed for this purpose.

As mentioned in the local-exec docs you can use it like this:

resource "null_resource" "example2" {
  provisioner "local-exec" {
    command = "Get-Date > completed.txt"
    interpreter = ["PowerShell", "-Command"]
  }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your solution. Can you help me to use the PowerShell script inside the provisioner rather than using the "command" option.
Just replace -Command with -File like you would when running it not in Terraform.
I gave the file path inside command parameter and replaced the -Command with -File and it worked just fine.
How to pass parameters to the script while calling them inside the provisioner.
That's probably worth a separate question. It's also one I don't know the answer to as I don't use Powershell.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.