1

Given this block of pseudo code from Terraform:

resource "null_resource" {
    provisioner "local-exec" {
        command = "echo hello"
        interpreter = local.os == "Windows" ? ["PowerShell", "-Command"] : ["bash"]
}

How would I get this to run in Powershell on Windows and bash on Linux?

slightly_toasted
  • 732
  • 3
  • 13

2 Answers2

2

You can examine the path where where your terraform project is running. On Windows it will be something similar to C:/Users/ whereas on linux, the standard path will be /home/xxx.

locals {
  is_linux = length(regexall("/home/", lower(abspath(path.root)))) > 0
}

resource "local_file" "connect_sh" {
  count           = local.is_linux ? 1 : 0
  filename        = "connect.sh"
  file_permission = "0744"
  content         = <<-EOF
#!/bin/bash
ssh -i ${local.vars["key_file"]} -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ServerAliveInterval=120 -o ServerAliveCountMax=2 ec2-user@${data.aws_eip.this.public_ip}
EOF
}

resource "local_file" "connect_bat" {
  count           = local.is_linux ? 0 : 1
  filename        = "connect.bat"
  #file_permission = "0744"
  content         = <<-EOF
@ssh -i ${local.vars["key_file"]} -o StrictHostKeyChecking=no -o UserKnownHostsFile=NUL -o ServerAliveInterval=120 -o ServerAliveCountMax=2 ec2-user@${data.aws_eip.this.public_ip}
EOF
}
0

local-exec usage inherently draws in details of the platform where you are running Terraform, which is one of the reasons why it should be treated as a last resort.

Terraform does not include any built-in way for a module to detect the host operating system. A custom Terraform provider could potentially offer a data source which returns that information, although if one were writing a Terraform provider anyway it may be more appropriate to write one to do whatever operation this provisioner would've been running directly, and thus avoid the need for the Terraform configuration to branch based on operating system.

Martin Atkins
  • 2,188
  • 18
  • 19