Introduction
- Run PowerShell from Terraform the first time only
- Run PowerShell from Terraform every time
- Run PowerShell from Terraform on a trigger
To run PowerShell, we’ll be using the null_resource in Terraform. You can find out more about it here. Using the null_resource, we’ll be calling the local_exec provisioner which specifies that the PowerShell script will be run on the machine running the Terraform configuration. More info on that is here.
Run PowerShell from Terraform the first time only
Our configuration is pretty simple for this one. Basically, we’re calling the null_resource and the local_exec provisioner. We then pass in the path to our PowerShell script and the parameters. Note that you need to dot source your PowerShell script by putting a . before it and you also need to surround it in ” in case the path includes a space.
We can then run terraform init and terraform apply and we see the output below and we can see Terraform ran the PowerShell script (no, you don’t need to run terraform plan).
Run PowerShell from Terraform every time
As for the Terraform configuration, we’re now adding a trigger which causes Terraform to run each time the trigger value changes. To do this, we’re assigning a new UUID each time:
Terraform now runs the PowerShell script every time it runs.
Run PowerShell from Terraform on a defined trigger
Again, our PowerShell script is the same as before in the helpers folder.
To demonstrate this, we can add a variable TriggerValue and specify this in a variables.tf file. Terraform will expect us to pass this variable on the command line or via a TFVARS file.
Our Terraform configuration now needs to look like this. See that the trigger option is set to our TriggerValue variable.
When we run our configuration the first time using terraform apply, we need to specify the value for the variable (terraform apply -var TriggerValue=100) and we see that the script runs:
If we change the value of TriggerValue and run it again, Terraform now runs our PowerShell script:
Conclusion
In this article, we went through how you can run PowerShell scripts from Terraform either running every time, on a trigger or on the first time only.