Last active
February 11, 2026 15:38
-
-
Save atheiman/380cacd57e0f1fde8ec41ba1710390d1 to your computer and use it in GitHub Desktop.
Terraform to detect OS and run local commands appropriately based on OS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| terraform { | |
| required_providers { | |
| external = { | |
| source = "hashicorp/external" | |
| version = "~> 2.3.3" | |
| } | |
| } | |
| } | |
| locals { | |
| # Windows paths will start with a drive letter (C:/), Linux paths will start with "/" | |
| os_family = startswith(abspath(path.module), "/") ? "linux" : "windows" | |
| username = local.os_family == "linux" ? data.external.user_linux[0].result.user : data.external.user_windows[0].result.user | |
| } | |
| data "external" "user_linux" { | |
| count = local.os_family == "linux" ? 1 : 0 | |
| program = [ | |
| "sh", | |
| "-c", | |
| <<-EOF | |
| echo "{\"user\":\"$USER\"}" | |
| EOF | |
| ] | |
| } | |
| data "external" "user_windows" { | |
| count = local.os_family == "windows" ? 1 : 0 | |
| program = [ | |
| "powershell", | |
| "-c", | |
| <<-EOF | |
| Write-Output "{`"user`":`"$env:USERNAME`"}" | |
| EOF | |
| ] | |
| } | |
| output "os_family" { | |
| value = local.os_family | |
| } | |
| output "username" { | |
| value = local.username | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment