Anbu
Anbu

Reputation: 35

How to run a powershell script in terraform?

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"]
}

Upvotes: 1

Views: 10604

Answers (1)

ydaetskcoR
ydaetskcoR

Reputation: 56877

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"]
  }
}

Upvotes: 2

Related Questions