AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题

问题[terraform](coding)

Martin Hope
N-CODER
Asked: 2025-04-28 12:27:31 +0800 CST

如何使 terraform 模板文件忽略默认的 bash 变量?

  • 6

这是我的 Bash 脚本:

#!/bin/bash

#Colors for terminal

#RED
R="\e[31m"

#GREEN
G="\e[32m"

#YELLOW
Y="\e[33m"

#NORMAL
N="\e[0m"

validation(){

    if [ $1 -eq 0 ];
    then 
        echo -e "${G}$2 is successful${N}"
    else 
        echo -e "${R}$2 has Failed${N}"
        exit 1;
    fi
}

echo -e "${Y}Configuring Cart Service${N}"

cart_config="/etc/systemd/system/cart.service"

cat << EOF >$cart_config

Environment=REDIS_HOST="${redis_ip}" #I want TF to only substitute these
Environment=CATALOGUE_HOST="${app_lb_dns}"

Environment=CATALOGUE_PORT=8082

EOF

validation $? "Configuring Cart Service"

Terraform 创建 Redis-Ip 地址和负载均衡器 DNS 后,我会收到它们,我想将替换这些值的 Bash 脚本作为用户数据传递。问题是 Terraform 试图替换${}Bash 脚本中的每个变量,但我只想将${redis_ip}和替换${app_lb_dns}为用户数据。我尝试使用\${}和转义所有变量,$${}但没用。

错误:

20:user_data = base64encode(templatefile(“../userdata/cart.sh”,{redis_ip = data.aws_ssm_parameter.redis_ip.value,app_lb_dns = data.aws_ssm_parameter.app_lb_dns.value}))在调用templatefile(path,vars)时“vars”参数的值无效:vars映射不包含键“G”,在../userdata/cart.sh:16,21-22处引用。

根据错误,TF 正在尝试替换与 bash 脚本相关的变量。

这是我的 Terraform 代码:

user_data = base64encode(templatefile("../userdata/cart.sh", { redis_ip = data.aws_ssm_parameter.redis_ip.value, app_lb_dns = data.aws_ssm_parameter.app_lb_dns.value }))
terraform
  • 2 个回答
  • 47 Views
Martin Hope
Brian G
Asked: 2025-04-24 23:18:10 +0800 CST

使用 Terraform 如何将字符串映射转换为对象映射

  • 7

我在模块根目录中有一个 Terraform Variables.tf,其内容类似于以下内容:

variable "parameters" {
  description = "Parameter Store key/values"
  type = map(string)
  default = {
    "/customer1/prod/keycloak/password" = "password123"
    "/customer1/prod/keycloak/realm" = "default"
    "/customer1/prod/keycloak/url" = "https://customer1-sso.app.something.cloud/auth"
    "/customer1/prod/keycloak/userid" = "f:48c1ce1f:monitoring"
    "/customer1/uat/keycloak/password" = "password123"
    "/customer1/uat/keycloak/realm" = "uat"
    "/customer1/uat/keycloak/url" = "https://customer1-sso.npr.app.something.cloud/auth"
    "/customer1/uat/keycloak/userid" = "f:d48d4452:monitoring"
    "/customer1/uat2/keycloak/password" = "password123"
    "/customer1/uat2/keycloak/realm" = "uat2"
    "/customer1/uat2/keycloak/url" = "https://customer1-sso.npr.app.something.cloud/auth"
    "/customer1/uat2/keycloak/userid" = "f:5fe762fd:monitoring"
    "/customer2/prod/keycloak/password" = "password123"
    "/customer2/prod/keycloak/realm" = "default"
    "/customer2/prod/keycloak/url" = "https://customer2-sso.app.something.cloud/auth"
    "/customer2/prod/keycloak/userid" = "f:a053a488:monitoring"
    "/customer2/uat/keycloak/password" = "password123"
    "/customer2/uat/keycloak/realm" = "uat"
    "/customer2/uat/keycloak/url" = "https://customer2-sso.npr.app.something.cloud/auth"
    "/customer2/uat/keycloak/userid" = "f:225118c6:monitoring"
    "/customer2/uat2/keycloak/password" = "password123"
    "/customer2/uat2/keycloak/realm" = "uat2"
    "/customer2/uat2/keycloak/url" = "https://customer2-sso.npr.app.something.cloud/auth"
    "/customer2/uat2/keycloak/userid" = "f:9d8b2d30:monitoring
 }
}

我想将其转换为如下所示的对象图:

{
  "customer1_prod" = {
    customer = "customer1"
    password = "password123"
    realm    = "default"
    url      = "https://customer1-sso.app.something.cloud/auth"
    userid   = "f:48c1ce1f:monitoring"
  }
  ...
}

我已经在根模块(main.tf)代码中尝试过这个:

# Transform flat map of strings into a grouped map of customer-env -> { password, realm, url, userid }
locals {
  # Step 1: Flatten parameters to tuples of [group_key, key_in_object, value]
  parameter_tuples = [
    for full_key, value in var.parameters : {
      group_key = join("_", slice(split("/", full_key), 1, 3))     # e.g. customer1_prod
      key       = split("/", full_key)[3]                          # e.g. password
      value     = value
    }
  ]

  # Step 2: Group by environment and assemble objects with customer field
  customers = {
    for group_key in distinct([for p in local.parameter_tuples : p.group_key]) :
    group_key => merge(
      {
        customer = split("_", group_key)[0]
      },
      merge([
        for p in local.parameter_tuples : {
          for inner in [p] :
          inner.key => inner.value
        } if p.group_key == group_key
      ]...)
    )
  }
}

output "all_customers" {
  value = local.customers
}

module "dd_synthetic_browser" {
  source = "./modules/dd_synthetic_browser"
  customers = local.customers
}

然而,输出显示如下:

+ all_customers             = {
      + customer1_prod = {
          + customer = "customer1"
          + keycloak = "f:48c1ce1f:monitoring"
        }
    ...
    ...

如何修复这个错误的对象映射?有两个错误:

  1. 对象中应该有五项(客户、密码、领域、url 和用户 ID),但实际上只有两项。
  2. 该keycloak = "f:48c1ce1f:monitoring"项目应该是userid = "f:48c1ce1f:monitoring"

此外,我愿意接受有关更好的 Terraform 代码的建议来执行此转换,因为我认为我的代码对于其任务来说太复杂了,并且可能可以用更少的代码行以更简单的方式完成。

terraform
  • 1 个回答
  • 45 Views
Martin Hope
Saurav Padhy
Asked: 2025-04-11 15:57:33 +0800 CST

如何通过 Terraform 在 Grafana 仪表板中动态引用 UID?

  • 6

示例 tf 代码

data "grafana_data_source" "azure_monitor" {
  name = "grafana-azure-monitor-datasource"

resource "grafana_dashboard" "test" {
  folder      = grafana_folder.rule_folder.uid
  config_json = file("${path.module}/VMDASHBOARD.json")
}

但这里的问题是,当我在 json 文件中引用 uid 时

VMDASHBOARD.json

uid: ${data.grafana_data_source.azure_monitor.uid}

它不是动态的,并显示非法的uid

terraform
  • 1 个回答
  • 25 Views
Martin Hope
Elarbe
Asked: 2025-04-08 19:56:44 +0800 CST

在 filesystem_mirror 位置未找到 Terraform v1.11.3 提供程序

  • 5

我正在尝试安装这个“愚蠢的”api 提供程序,以允许我将 Terraform 与当前在注册表中没有可用提供程序的 api 一起使用:

https://github.com/Mastercard/terraform-provider-restapi

我已经下载了最新版本的 .zipcURL并使用提取了可执行文件chmod +x。

按照 Hashicorp 的文档,我~/.terraformrc 通过显式安装方法创建了一个所需的配置文件,其内容如下:

provider_installation {
  filesystem_mirror {
    path    = "/home/lukerb/.terraform.d/plugins/registry.terraform.io/hashicorp/restapi/1.20.0/linux_amd64/"
    include = ["registry.terraform.io/*/*"]
  }
  direct {
    exclude = ["registry.terraform.io/*/*"]
  }
}

该路径存在,并且正是我之前提取的可执行文件所在的位置,但是当terraform init在与 main.tf 相同的目录中执行时,我收到以下错误

 Error: Failed to query available provider packages
│
│ Could not retrieve the list of available versions for provider hashicorp/restiapi: provider registry.terraform.io/hashicorp/restiapi was not found in any of the search
│ locations
│
│   - /home/lukerb/.terraform.d/plugins/registry.terraform.io/hashicorp/restapi/1.20.0/linux_amd64/
╵
╷
│ Error: Failed to query available provider packages
│
│ Could not retrieve the list of available versions for provider hashicorp/restapi: provider registry.terraform.io/hashicorp/restapi was not found in any of the search
│ locations
│
│   - /home/lukerb/.terraform.d/plugins/registry.terraform.io/hashicorp/restapi/1.20.0/linux_amd64/

我的 main.tf 包含

terraform {
  required_providers {
    restapi = {
      source = "hashicorp/restapi"
      version = "1.20.0"
    }
  }
}

我激活了详细日志来尝试了解问题所在,据我所知,当尝试初始化时,检查了位置但没有找到任何东西

[TRACE] Selected provider installation method cliconfig.ProviderInstallationFilesystemMirror("/home/lukerb/.terraform.d/plugins/registry.terraform.io/hashicorp/restapi/1.20.0/linux_amd64/") with includes [registry.terraform.io/*/*] and excludes []
[TRACE] Selected provider installation method cliconfig.ProviderInstallationDirect with includes [] and excludes [registry.terraform.io/*/*]
[INFO]  CLI command args: []string{"init"}
Initializing the backend...
[TRACE] Meta.Backend: no config given or present on disk, so returning nil config
[TRACE] Meta.Backend: backend has not previously been initialized in this working directory
[TRACE] Meta.Backend: using default local state only (no backend configuration, and no existing initialized backend)
[TRACE] Meta.Backend: instantiated backend of type <nil>
[DEBUG] checking for provisioner in "."
[DEBUG] checking for provisioner in "/usr/bin"
[DEBUG] checking for provisioner in "/home/lukerb/.terraform.d/plugins"

有人知道我哪里犯了错误或者问题到底是什么吗?

编辑:

按照@Matthew Schuchard 的建议进行更改后,我收到了类似的错误

2025-04-08T15:33:07.564+0200 [INFO]  Terraform version: 1.11.3
2025-04-08T15:33:07.564+0200 [DEBUG] using github.com/hashicorp/go-tfe v1.70.0
2025-04-08T15:33:07.564+0200 [DEBUG] using github.com/hashicorp/hcl/v2 v2.23.0
2025-04-08T15:33:07.564+0200 [DEBUG] using github.com/hashicorp/terraform-svchost v0.1.1
2025-04-08T15:33:07.564+0200 [DEBUG] using github.com/zclconf/go-cty v1.16.0
2025-04-08T15:33:07.564+0200 [INFO]  Go runtime version: go1.23.3
2025-04-08T15:33:07.564+0200 [INFO]  CLI args: []string{"terraform", "init"}
2025-04-08T15:33:07.564+0200 [TRACE] Stdout is a terminal of width 120
2025-04-08T15:33:07.564+0200 [TRACE] Stderr is a terminal of width 120
2025-04-08T15:33:07.564+0200 [TRACE] Stdin is a terminal
2025-04-08T15:33:07.564+0200 [DEBUG] Attempting to open CLI config file: /home/lukerb/.terraformrc
2025-04-08T15:33:07.564+0200 [INFO]  Loading CLI configuration from /home/lukerb/.terraformrc
2025-04-08T15:33:07.564+0200 [DEBUG] checking for credentials in "/home/lukerb/.terraform.d/plugins"
2025-04-08T15:33:07.564+0200 [DEBUG] Explicit provider installation configuration is set
2025-04-08T15:33:07.564+0200 [TRACE] Selected provider installation method cliconfig.ProviderInstallationFilesystemMirror("/home/lukerb/.terraform.d/plugins/registry.terraform.io/Mastercard/restapi/1.20.0/linux_amd64") with includes [registry.terraform.io/*/*] and excludes []
2025-04-08T15:33:07.565+0200 [INFO]  CLI command args: []string{"init"}
Initializing the backend...
2025-04-08T15:33:07.565+0200 [TRACE] Meta.Backend: no config given or present on disk, so returning nil config
2025-04-08T15:33:07.565+0200 [TRACE] Meta.Backend: backend has not previously been initialized in this working directory
2025-04-08T15:33:07.565+0200 [TRACE] Meta.Backend: using default local state only (no backend configuration, and no existing initialized backend)
2025-04-08T15:33:07.565+0200 [TRACE] Meta.Backend: instantiated backend of type <nil>
2025-04-08T15:33:07.565+0200 [DEBUG] checking for provisioner in "."
2025-04-08T15:33:07.567+0200 [DEBUG] checking for provisioner in "/usr/bin"
2025-04-08T15:33:07.568+0200 [DEBUG] checking for provisioner in "/home/lukerb/.terraform.d/plugins"
2025-04-08T15:33:07.568+0200 [TRACE] Meta.Backend: backend <nil> does not support operations, so wrapping it in a local backend
2025-04-08T15:33:07.568+0200 [TRACE] backend/local: state manager for workspace "default" will:
 - read initial snapshot from terraform.tfstate
 - write new snapshots to terraform.tfstate
 - create any backup at terraform.tfstate.backup
2025-04-08T15:33:07.568+0200 [TRACE] statemgr.Filesystem: reading initial snapshot from terraform.tfstate
2025-04-08T15:33:07.568+0200 [TRACE] statemgr.Filesystem: snapshot file has nil snapshot, but that's okay
2025-04-08T15:33:07.568+0200 [TRACE] statemgr.Filesystem: read nil snapshot
Initializing provider plugins...
- Finding mastercard/restapi versions matching "1.20.0"...
╷
│ Error: Failed to query available provider packages
│
│ Could not retrieve the list of available versions for provider mastercard/restapi: provider
│ registry.terraform.io/mastercard/restapi was not found in any of the search locations
│
│   - /home/lukerb/.terraform.d/plugins/registry.terraform.io/Mastercard/restapi/1.20.0/linux_amd64
terraform
  • 2 个回答
  • 41 Views
Martin Hope
kegham
Asked: 2025-02-07 19:50:21 +0800 CST

Terraform 如何有条件地执行块

  • 5

我正在学习 Terraform 并尝试使用它在 Proxmox 中配置虚拟机,但遇到了一个问题,我只想在计数的第一个索引上添加第二个磁盘。

我尝试添加size = count.index == 0 ? "50G" : null磁盘块,但它不起作用,因为size参数需要一个值。

这是我的代码:

resource "proxmox_vm_qemu" "workers" {
  count       = 2
  name        = "${local.vm_worker_name}-${count.index + 1}"
  target_node = local.target_node
  vmid        = "21${count.index}"

  agent   = 1
  os_type = "linux"
  onboot  = true
  cores   = 4
  sockets = 1
  memory  = 4046
  scsihw  = "virtio-scsi-pci"
  tags    = local.vm_worker_tags

  disks {
    virtio {
      virtio0 {
        disk {
            size    = "15G"
            storage = "local-lvm"
            backup  = true  
        }
      }
      virtio1 {
        disk {
            size    = count.index == 0 ? "50G" : "0"
            storage = "local-lvm"
            backup  = true  
        }
      }      
    }
    ide {
        ide0 {
            cdrom {
                iso = local.talos_linux_iso
            }
        }      
    }
  }  

  network {
    id = 0
    model  = "virtio"
    bridge = "vmbr0"
    tag    = "100"
  }

  ipconfig0 = "ip=dhcp"
}

那么,如何使用 if/else 语句来实现这一点?

terraform
  • 1 个回答
  • 27 Views
Martin Hope
Daan
Asked: 2024-12-31 17:50:39 +0800 CST

为什么我的 terraform init 自动化脚本失败了?

  • 4

我是 Terraform(提供程序)新手,我尝试创建一个开箱即用的脚本,该脚本运行 terraform init 并完成使其运行所需的所有准备工作。例如,应始终避免注册表查找,因为要使用的 Terraform 提供程序只是一个本地二进制文件。

我的脚本失败了(见屏幕截图),我真的不明白为什么。生成了正确的文件(例如 terraformrc)。二进制文件已复制到插件文件夹等。它应该可以正常工作。但我收到错误。查看屏幕截图和脚本。

我希望有人可以帮助我重写我的脚本以terraform init使其正常运行。

#!/usr/bin/env bash

set -e  # Exit on any error

###############################################################################
# VARIABLES
###############################################################################
HOME_DIR=$(eval echo "~$USER")  # Get the full home directory path
PLUGIN_DIR="$HOME_DIR/.terraform.d/plugins/local/flowtrends/1.0.0/linux_amd64"
TERRAFORMRC_PATH="$HOME_DIR/.terraformrc"
BINARY_NAME="terraform-provider-flowtrends_v1.0.0"
LOCAL_BINARY="./$BINARY_NAME"
MAIN_TF="main.tf"

###############################################################################
# STEP 1: FORCEFULLY OVERWRITE ~/.terraformrc WITH ABSOLUTE PATH
###############################################################################
cat << EOF > "$TERRAFORMRC_PATH"
provider_installation {
  dev_overrides {
    "local/flowtrends" = "$HOME_DIR/.terraform.d/plugins"
  }
  direct {
    exclude = []
  }
}
EOF

echo "Created $TERRAFORMRC_PATH with dev overrides for local/flowtrends."

###############################################################################
# STEP 2: CREATE A GUARANTEED VALID main.tf
###############################################################################
cat << EOF > "$MAIN_TF"
terraform {
  required_providers {
    flowtrends = {
      source  = "local/flowtrends"
      version = "1.0.0"
    }
  }
}

provider "flowtrends" {}
EOF

echo "Created $MAIN_TF with source = \"local/flowtrends\"."

###############################################################################
# STEP 3: CREATE THE NECESSARY PLUGIN DIRECTORY STRUCTURE
###############################################################################
mkdir -p "$PLUGIN_DIR"
echo "Created directory structure: $PLUGIN_DIR"

###############################################################################
# STEP 4: COPY THE PROVIDER BINARY TO THE CORRECT LOCATION
###############################################################################
if [[ ! -f "$LOCAL_BINARY" ]]; then
  echo "ERROR: Local provider binary $LOCAL_BINARY not found in the current directory."
  echo "Please place the binary here and rerun the script."
  exit 1
fi

cp "$LOCAL_BINARY" "$PLUGIN_DIR/"
echo "Copied provider binary to $PLUGIN_DIR/"

###############################################################################
# STEP 5: SET EXECUTABLE PERMISSION FOR THE PROVIDER BINARY
###############################################################################
chmod +x "$PLUGIN_DIR/$BINARY_NAME"
echo "Set execute permissions on $PLUGIN_DIR/$BINARY_NAME."

###############################################################################
# STEP 6: CLEAR TERRAFORM CACHE (FORCE CLEAN START)
###############################################################################
echo "Cleaning up Terraform cache..."
rm -rf .terraform/ .terraform.lock.hcl

###############################################################################
# STEP 7: FORCE DISABLE REGISTRY IN main.tf
###############################################################################
cat << EOF >> "$MAIN_TF"

// DISABLING REGISTRY LOOKUP
terraform {
  backend "local" {}
}
EOF

###############################################################################
# STEP 8: RUN `terraform init` AND FORCE REGISTRY BYPASS
###############################################################################
echo "Running terraform init..."
terraform init -input=false

更新

使用filesystem_mirror应该可以工作(参见这个新脚本)但不幸的是出现了同样的错误。

#!/usr/bin/env bash

set -e  # Exit on any error

###############################################################################
# VARIABLES
###############################################################################
HOME_DIR=$(eval echo "~$USER")  # Get the full home directory path
PLUGIN_DIR="$HOME_DIR/.terraform.d/plugins/local/flowtrends/1.0.0/linux_amd64"
TERRAFORMRC_PATH="$HOME_DIR/.terraformrc"
BINARY_NAME="terraform-provider-flowtrends_v1.0.0"
LOCAL_BINARY="./$BINARY_NAME"
MAIN_TF="main.tf"

###############################################################################
# STEP 1: CONFIGURE ~/.terraformrc WITH FILESYSTEM MIRROR
###############################################################################
cat << EOF > "$TERRAFORMRC_PATH"
provider_installation {
  filesystem_mirror {
    path = "$HOME_DIR/.terraform.d/plugins"
  }
  direct {
    exclude = []
  }
}
EOF

echo "Configured $TERRAFORMRC_PATH with filesystem_mirror."

###############################################################################
# STEP 2: CREATE A GUARANTEED VALID main.tf
###############################################################################
cat << EOF > "$MAIN_TF"
terraform {
  required_providers {
    flowtrends = {
      source  = "local/flowtrends"
      version = "1.0.0"
    }
  }
}

provider "flowtrends" {}
EOF

echo "Created $MAIN_TF with source = \"local/flowtrends\"."

###############################################################################
# STEP 3: CREATE THE NECESSARY PLUGIN DIRECTORY STRUCTURE
###############################################################################
mkdir -p "$PLUGIN_DIR"
echo "Created directory structure: $PLUGIN_DIR"

###############################################################################
# STEP 4: COPY THE PROVIDER BINARY TO THE FILESYSTEM MIRROR LOCATION
###############################################################################
if [[ ! -f "$LOCAL_BINARY" ]]; then
  echo "ERROR: Local provider binary $LOCAL_BINARY not found in the current directory."
  echo "Please place the binary here and rerun the script."
  exit 1
fi

cp "$LOCAL_BINARY" "$PLUGIN_DIR/"
echo "Copied provider binary to $PLUGIN_DIR/"

###############################################################################
# STEP 5: SET EXECUTABLE PERMISSION FOR THE PROVIDER BINARY
###############################################################################
chmod +x "$PLUGIN_DIR/$BINARY_NAME"
echo "Set execute permissions on $PLUGIN_DIR/$BINARY_NAME."

###############################################################################
# STEP 6: CLEAR TERRAFORM CACHE (FORCE CLEAN START)
###############################################################################
echo "Cleaning up Terraform cache..."
rm -rf .terraform/ .terraform.lock.hcl

###############################################################################
# STEP 7: RUN `terraform init` AND FORCE FILESYSTEM MIRROR USAGE
###############################################################################
echo "Running terraform init..."
terraform init -input=false

在此处输入图片描述 在此处输入图片描述

terraform
  • 2 个回答
  • 35 Views
Martin Hope
henryn
Asked: 2024-12-24 20:18:28 +0800 CST

Terraform 不接受 Snowflake 帐户名

  • 6

我不断收到这样的信息:

"account_name": all of `account_name,organization_name` must be specified

即使我明确地按照它要求的确切格式提供了我的帐户名和组织名称(我完全放弃尝试将其作为变量工作。

我尝试了所有我能想到的排列组合,但它从不接受任何一种有效组合。我感到很困惑,因为我昨天才在另一个项目上遇到这个问题。

我知道这会被否决,因为它太模糊了,但我真的不知道。

terraform
  • 1 个回答
  • 26 Views
Martin Hope
Marco Caberletti
Asked: 2024-12-03 01:44:22 +0800 CST

Terraform:根据本地值创建 tfvar

  • 5

我有一个如下的数据结构:

locals {
  replication_tasks = {
    track_to_s3_live = {
      replication_task_id       = "track-to-s3"
      migration_type            = "full-load-and-cdc"
      replication_task_settings = file("files/s3_tracking_cdc_settings.json")
      table_mappings            = file("files/s3_tracking_table_mappings.json")
      source_endpoint_key       = "source"
      target_endpoint_key       = "s3_tracking"
    }
  }
}

由此,我尝试编写等效的 .tfvars 文件(用于另一个模块)。类似于:

resource "local_file" "file" {
  content  = <<EOF
replication_tasks = "${local.replication_tasks}"
EOF
  filename = "${path.module}/tasks.auto.tfvars"
}

但是我收到此错误:

Cannot include the given value in a string template: string required.

关于如何实现这一点有什么建议吗?

terraform
  • 1 个回答
  • 26 Views
Martin Hope
Nick Vee
Asked: 2024-11-29 00:48:40 +0800 CST

Terraform 输出:如何从容器中获取第一个项目(如果存在)

  • 5

Terraform 提供程序的文档说我可以通过这种方式从容器中获取值.identity[0],但在某些情况下identity为空。如果容器中至少有一个元素,我该如何获取第一个元素(否则null例如)。

实际情况下由于此原因而遇到的一个错误(以及错误的线路):

Error: Invalid index
  on .../outputs.tf line 21, in output "container_registry_primary_identity_principal_id":
  21:     value = azurerm_container_registry.***.identity[0].principal_id
    ├────────────────
    │ azurerm_container_registry.***.identity is empty list of object
The given key does not identify an element in this collection value: the
collection has no elements.
terraform
  • 1 个回答
  • 16 Views
Martin Hope
codeforester
Asked: 2024-11-13 04:50:47 +0800 CST

将模块对象作为输入变量传递给另一个模块

  • 4

我正在考虑创建一个模块,为随后调用的所有模块设置顶级上下文(一组共享常量)。为了避免每个模块必须创建上下文模块的模块对象,我希望入门级模块创建该对象并将其作为输入变量传递给所有其他模块。

我有这段代码并且它可以工作:

├── main.tf
├── modules
│   ├── mod1
│   │   └── mod1.tf
│   ├── mod2
│   │   └── mod2.tf

主程序:

module mod1 {
    source = "./modules/mod1"
    var1 = "hello"
    var2 = "world"
}

module mod2 {
    source = "./modules/mod2"
    var1 = module.mod1
}

output "mod1" {
    value = module.mod1
}

output "mod2" {
    value = module.mod2
}

模块/mod1/mod1.tf:

variable "var1" {
    type = string
}

variable "var2" {
    type = string
}

output "out1" {
    value = "In module1; got var1 = ${var.var1}"
}

output "out2" {
    value = "In module1; got var2 = ${var.var2}"
}

模块/mod2/mod2.tf:

variable "var1" {
    type = any
}

output "out1" {
    value = "var1 is ${var.var1.out1}, var2 is ${var.var1.out2}"
}

跑步时

$ terraform init && terraform plan

我明白了

Changes to Outputs:
  + mod1 = {
      + out1 = "In module1; got var1 = hello"
      + out2 = "In module1; got var2 = world"
    }
  + mod2 = {
      + out1 = "var1 is In module1; got var1 = hello, var2 is In module1; got var2 = world"
    }

通常会这样做吗?如果不是,这种方法是否存在任何风险,例如 Terraform 在未来版本中不支持该功能?


有关的

  • 可以将资源作为变量传递到模块中吗?
  • 在模块间共享公共变量
  • 我可以自动查看所有子模块的输出变量,而无需在主根模块的 output.tf 变量中重新定义它们吗?
terraform
  • 1 个回答
  • 31 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve