You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform中如何为安全组v4_cidr_blocks添加子网掩码

解决方案

不需要额外把数据源赋值给变量,直接用Terraform的字符串拼接功能就能搞定,两种常用方式:

  1. 使用format函数(可读性更好,推荐)
resource "yandex_compute_security_group" "instance_access_sg" {
  name        = "allow-instance1-access"
  description = "允许来自instance1的流量"

  ingress {
    protocol       = "TCP"
    port           = 22 # 示例端口,可根据实际需求修改
    v4_cidr_blocks = [format("%s/32", data.yandex_compute_instance.instance1.network_interface.0.ip_address)]
  }
}
  1. 直接用字符串插值语法
resource "yandex_compute_security_group" "instance_access_sg" {
  name        = "allow-instance1-access"
  description = "允许来自instance1的流量"

  ingress {
    protocol       = "TCP"
    port           = 22
    v4_cidr_blocks = ["${data.yandex_compute_instance.instance1.network_interface.0.ip_address}/32"]
  }
}

如果这个实例IP需要在配置的多个地方重复使用,那可以先把它赋值给本地变量,方便后续维护:

locals {
  instance1_ip = data.yandex_compute_instance.instance1.network_interface.0.ip_address
}

resource "yandex_compute_security_group" "instance_access_sg" {
  name        = "allow-instance1-access"
  description = "允许来自instance1的流量"

  ingress {
    protocol       = "TCP"
    port           = 22
    v4_cidr_blocks = [format("%s/32", local.instance1_ip)]
  }
}

总结:单一处使用的话,直接拼接最省事;多处复用的话,用本地变量更方便。

内容的提问来源于stack exchange,提问作者Иван Иванов

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 09:33:15