如何将子网ID列表传递给模块中的IAM策略模板?

如何解决如何将子网ID列表传递给模块中的IAM策略模板?

我希望通过terraform模块在IAM策略中创建以下语句:

{
    "Effect": "Allow","Action": [
        "ec2:CreateNetworkInterfacePermission"
    ],"Resource": "arn:aws:ec2:us-east-1:<acc-id>:network-interface/*","Condition": {
        "StringEquals": {
            "ec2:Subnet": [
                "subnet-id1","subnet-id2"
            ],"ec2:AuthorizedService": "codebuild.amazonaws.com"
        }
    }
}

我面临的问题是我无法弄清楚哪个插值会得到我[“ subnet1”,“ subnet2”]。

这里有一点背景。我用TF模块(pubic_subnets)创建了子网,输出代码是这样的:

   output "subnet_ids" { value = "${join(",",aws_subnet.public.*.id)}" }

,其结果是类似“ subnet-1,subnet-2,subnet-3”的字符串。这是我从中获取子网ID的地方,我想将其传递给另一个模块。

我还有另一个用于IAM策略的模块(下面的代码)。我试图从上方获取subnet_ids并将其传递给iam-policy模块,以便可以将它们放入我的语句中,但是,我不知道如何使用TF中的任何插值。我尝试了大约十二种不同的插值,但是没有运气。 我能够将子网ID传递到IAM策略的唯一方法是从字符串(0,1)中提取项目并将它们作为单独的变量传递。 这不是完美的,因为我想包括所有子网ID,有时我会有3个或更多子网。

有人成功做到了这种魔术吗?如何更新代码,以便所有子网ID均以[“ subnet1”,“ subnet2”,“ subnet3”]格式传递?

这是我在2个文件中的iam-policy模块的代码:

  1. main.tf
    data "template_file" "policy" {
       template = "${file("${var.policy_document}")}"
    
       vars = {
          account_id           = "${var.account_id}"
          role_name            = "${var.role_name}"
          log_group            = "${var.log_group}"
          repository_arn       = "${var.repository_arn}"
          website_s3_bucket    = "${var.website_s3_bucket}"
          pipeline_s3_bucket   = "${var.pipeline_s3_bucket}"
          subnet1              = "${var.subnet1}"
          subnet2              = "${var.subnet1}"
       }
    }
    
    resource "aws_iam_policy" "policy" {
    
       name        = "${var.policy_name}"
       description = "${var.description}"
       path        = "${var.path}"
       policy      = "${data.template_file.policy.rendered}"
    }
  1. variables.tf
variable "policy_name"     { default = "" }
variable "description"     { }
variable "path"            { default = "" }
variable "policy_document" {
   type  = "string"
   default = ""
}
# variables for policy
variable "log_group"          { }
variable "account_id"         { }
variable "role_name"          { }
variable "repository_arn"     { }
variable "website_s3_bucket"  { }
variable "pipeline_s3_bucket" { }
variable "subnet1"            { }
variable "subnet2"            { }

在我的项目文件(project.tf)中,我有:

module "iam_policy_for_codebuild_service_role" {
   source = "../aws-policy.local"

   policy_name        = "${var.name}CodeBuildServiceRolePolicy1${lookup(var.environment,var.region)}"
   description        = "Policy for codebuild service role."
   path               = "/"
   policy_document    = "./policies/policy1.json"
   account_id         = "${module.account_id.id}"
   log_group          = "${var.name}Build${lookup(var.environment,var.region)}logGroup"
   role_name          = "${var.name}CodeBuildServiceRole${lookup(var.environment,var.region)}"
   repository_arn     = "${aws_codecommit_repository.ce_repo.arn}"
   website_s3_bucket  = "${aws_s3_bucket.website_bucket.arn}"
   pipeline_s3_bucket = "${aws_s3_bucket.codepipeline_bucket.arn}"

   subnet1             = "${element(split(",module.public_subnet.subnet_ids),0)}"
   subnet2             = "${element(split(",1)}"

}

这是我的./policies/policy1.json文件中的内容:

        {
            "Effect": "Allow","Action": [
                "ec2:CreateNetworkInterfacePermission"
            ],"Resource": "arn:aws:ec2:us-east-1:${account_id}:network-interface/*","Condition": {
                "StringEquals": {
                    "ec2:Subnet": ["${subnet1}","${subnet2}"],"ec2:AuthorizedService": "codebuild.amazonaws.com"
                }
            }
        }

我开始认为这是不可能的,因为IAM策略在“ ec2:Subnet”之后必须有[]。

如果那里有一个可以执行此法术的法师,请分享使该法术在Terraform 11x版中起作用的要素。 :)

谢谢

解决方法

您可以将它们作为字符串或只是列表而不是各个子网subnet1subnet2等传递给它们。

例如,在您的variables.tf中,您可以使用变量代替单个子条目:

variable "subnet_ids"            { }

然后在project.tf

subnet_ids             = "${module.public_subnet.subnet_ids}"

将生成subnet_ids="subnet1,subnet2"。然后,您通过jsonencode将此变量传递到文件模板中,这将导致字符串["subnet1","subnet2"]

    data "template_file" "policy" {
       template = "${file("${var.policy_document}")}"
    
       vars = {
          account_id           = "${var.account_id}"
          role_name            = "${var.role_name}"
          log_group            = "${var.log_group}"
          repository_arn       = "${var.repository_arn}"
          website_s3_bucket    = "${var.website_s3_bucket}"
          pipeline_s3_bucket   = "${var.pipeline_s3_bucket}"
          subnet_ids           = "${jsonencode(split(",",{var.subnet_ids)}"
       }
    }

最后,在./policies/policy1.json

"ec2:Subnet": ${subnet_ids},

应扩展为:

"ec2:Subnet": ["subnet1","subnet2"],

尚未验证上述内容,因此可能需要进行一些更改才能使其完全正常运行。但是至少应该清楚如何解决问题的核心思想。

,

在进行插值处理之后,我开始使用它,这是我的解决方案。希望它将对将来的人有所帮助。

其核心是使用replace函数进行字符串操作:

    ${replace(replace(replace(module.public_subnet.subnet_ids,"\","),"subnet","\"arn:aws:ec2:${var.region}:${module.account_id.id}:subnet"),"/$/","\"")}

这是我的模块现在的样子:

module "iam_policy" {
   source = "../aws-policy.local"

   policy_name        = "${var.name}CodeBuildServiceRolePolicy1${lookup(var.environment,var.region)}"
   description        = "Policy for codebuild service role."
   path               = "/"
   policy_document    = "./policies/policy1.json"
   account_id         = "${module.account_id.id}"
   log_group          = "${var.name}Build${lookup(var.environment,var.region)}logGroup"
   role_name          = "${var.name}CodeBuildServiceRole${lookup(var.environment,var.region)}"
   repository_arn     = "${aws_codecommit_repository.ce_repo.arn}"
   website_s3_bucket  = "${aws_s3_bucket.website_bucket.arn}"
   pipeline_s3_bucket = "${aws_s3_bucket.codepipeline_bucket.arn}"
   subnets             = "${replace(replace(replace(module.public_subnet.subnet_ids,"\"")}"
}

但是我将尝试从上面的注释中实现jsonencode,以缩短此代码,因为它看起来很丑陋。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-