Terraform can be used for deployment of Windows service by combination of provisioner together with PowerShell cmdlets.
Following Terraform code placed in main.tf
file can be used to install and uninstall of Windows service:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | variable "binary_path" { type = string description = "Binary path" } variable "service_name" { type = string description = "Service name" } resource "null_resource" "win_service" { triggers = { service_name = var.service_name } provisioner "local-exec" { when = create command = "New-Service -BinaryPathName ${var.binary_path} -Name ${var.service_name} -StartupType Automatic; Start-Service -Name ${var.service_name}" interpreter = [ "PowerShell" , "-Command" ] } provisioner "local-exec" { when = destroy command = "Stop-Service -Name ${self.triggers.service_name}; (Get-WmiObject -Class Win32_Service -Filter \"Name='${self.triggers.service_name}'\").Delete()" interpreter = [ "PowerShell" , "-Command" ] } } |
Install Windows service using:
1 | terraform apply -var 'binary_path={binary_path}' -var 'service_name={service_name}' -auto -approve |
Uninstall Windows service using:
1 | terraform destroy -var 'binary_path={binary_path}' -var 'service_name={service_name}' -auto -approve |
Before running this commands replace variables {binary_path}
and {service_name}
with required values.