我正在尝试使用外部数据源从 Azure 动态获取虚拟机列表并单独显示虚拟机。
以下是 Powershell 脚本:
$rgroup = [Console]::In.ReadLine()
$json = ConvertFrom-Json $rgroup
$name = $json.rg
$vms=(Get-AzVM -ResourceGroupName $name ).name
foreach ($vm in $vms){
$vmname= $vm |convertTo-json
Write-Output "{""Name"" : $vmname}"}
Main.tf
variable "resourcegroup" {}
data "external" "test" {
program = ["Powershell.exe", "./vm.ps1"]
query = {
rg = "${var.resourcegroup}"
}}
output "value" {
value = "${data.external.test.result.name}}
但是,我收到了一个错误:
“命令“Powershell.exe”生成了无效的 JSON:顶级值后的字符“{”无效”
有人能告诉我如何循环遍历虚拟机列表并单独显示它吗?
答案1
我编写了一个 terraform 模块来帮助将 ssh 密钥添加到 gcp 元数据中。它不是对您的问题的直接回答,但它应该对您有所帮助。
variable "ssh_keys" {
type = list(object({
user = string
key = string
}))
default = [
{
user = "terraform"
key = "~/.ssh/google_compute_engine.pub"
},
{
user = "user"
key = "~/.ssh/id_rsa.pub"
}
]
}
resource "google_compute_project_metadata" "default" {
metadata = merge(
{
ssh-keys = join("\n", [for k,v in var.ssh_keys : "${var.ssh_keys[k].user}:${file("${var.ssh_keys[k].key}")}"])
}
)
}