首页 > 解决方案 > 具有资源策略的 aws api 网关的 terraform 循环依赖

问题描述

问题陈述 我正在尝试使用 terraform follwing 自动化 aws api 网关是我的代码的一部分

用于 api 网关

resource "aws_api_gateway_rest_api" "rest_api" {
  #some code
policy = "${data.template_file.init.rendered}"
}

output "id" {
  value = "${aws_api_gateway_rest_api.rest_api.id}"
}

output "execution_arn" {
  value = "${aws_api_gateway_rest_api.rest_api.execution_arn}"
}

output "arn" {
  value = "${aws_api_gateway_rest_api.rest_api.arn}"
}

对于资源策略, 请注意我想在 json 策略文档中自动插入 api id

data "aws_region" "current" {}
data "aws_caller_identity" "current" {}
data "template_file" "init" {
  template = "${file("${path.root}/${var.policy_file_location}")}"
  vars = {
    current_region      = "${data.aws_region.current.name}"
    current_aws_account = "${data.aws_caller_identity.current.account_id}"
    current_api_id              = "${aws_api_gateway_rest_api.rest_api.id}"
  }
}

json 策略

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "execute-api:Invoke",
            "Resource": "arn:aws:execute-api:${current_region}:${current_aws_account}:${current_api_id}/*"
        }
    ]
}

当我尝试提供类似于以下的资源策略时,我得到

错误:循环:module.simple-api-gw.data.template_file.init、module.simple-api-gw.aws_api_gateway_rest_api.rest_api

我该如何解决这个错误?我想在 json 文件中动态提供 api id。

标签: amazon-web-servicesterraformaws-api-gateway

解决方案


您正在生成的策略适合分配给 IAM 角色或 IAM 用户,以允许他们调用 API。将该特定策略直接分配给 API Gateway 没有意义。本质上,您是在说“任何有权调用 API 的人都可以有权调用 API”,这是一个循环语句。

适合分配给 API 网关的策略会执行诸如限制对特定委托人或特定 IP 地址的请求之类的操作。

请参阅我上面链接的文档。它概述了通过 IAM 权限或通过资源策略控制对 API 网关的访问的两种不同方法。您正在尝试将 IAM 权限分配为资源策略,但这是行不通的。


推荐阅读