需求:有多个security group,需给每个security group建立一样的security group rules
subnet=["10.0.0.0/24","10.0.1.0/24","10.0.2.0/24"] //3 subnets
sg_name=["SG-A","SG-B","SG-C"] //3 names of security group
sr_name=["allow-1","allow-2",...,"allow-100"] // 100 names of security group rule
st_access=["allow","allow",..."allow"] //100 times allow for the action
sr_protocol=["TCP","UDP",..."TCP"] // 100 times protocol
*各种创建security group rule的参数皆可定义成list
以下为实现代码:
resource "azurerm_network_security_rule" "sg" {
count = "${length(var.sr_name)*length(var.sg_name)}"
#一共循环100*3次
name = "${var.sr_name[count.index % length(var.sr_name)]}"
#index第一次为0,余数为0,可取sr_name[0]; index 第二次为1,余数为1,取sr_name[1],以此类推
priority

本文介绍如何通过Terraform利用多重循环动态创建Azure上的Security Group Rules。针对多个不同的security groups,每个group都需要配置相同数量的规则,如allow-1到allow-100。通过定义subnet、sg_name、sr_name、st_access和sr_protocol等变量,实现规则的自动化部署。代码中利用count属性和list索引来确保正确分配rule名称、优先级、访问类型、协议和其他相关参数。
最低0.47元/天 解锁文章
1182





