我有一些 terraform 代码,可以创建 dynamodb 表并将一项插入到该表中。当我运行
terraform apply
时,出现以下错误。看起来它将在 dynamodb 表完全创建之前插入该项目(状态 - 活动)。
module "dynamodb_table" {
source = "terraform-aws-modules/dynamodb-table/aws"
name = "${var.aws.region}-${var.config.dynamodb.table_name}"
hash_key = var.config.dynamodb.hash_key
attributes = [
{
name = var.config.dynamodb.hash_key
type = "S"
}
]
billing_mode = "PAY_PER_REQUEST"
table_class = "STANDARD"
}
resource "random_string" "random" {
length = 16
special = false
}
resource "aws_dynamodb_table_item" "table_item" {
table_name = "${var.aws.region}-${var.config.dynamodb.table_name}"
hash_key = var.config.dynamodb.hash_key
item = <<ITEM
{
"${var.config.dynamodb.hash_key}": {"S": "${random_string.random.result}"},
"collections": {"M": {}}
}
ITEM
}
错误信息:
Error: creating DynamoDB Table Item: ResourceNotFoundException: Requested resource not found
depends_on
应该就足够了:
module "dynamodb_table" {
source = "terraform-aws-modules/dynamodb-table/aws"
name = "${var.aws.region}-${var.config.dynamodb.table_name}"
hash_key = var.config.dynamodb.hash_key
attributes = [
{
name = var.config.dynamodb.hash_key
type = "S"
}
]
billing_mode = "PAY_PER_REQUEST"
table_class = "STANDARD"
}
resource "random_string" "random" {
length = 16
special = false
}
resource "aws_dynamodb_table_item" "table_item" {
table_name = "${var.aws.region}-${var.config.dynamodb.table_name}"
depends_on = "dynamodb_table"
hash_key = var.config.dynamodb.hash_key
item = <<ITEM
{
"${var.config.dynamodb.hash_key}": {"S": "${random_string.random.result}"},
"collections": {"M": {}}
}
ITEM
}
Terraform 可能会首先尝试在表中创建项目(由于并行性),因为表和项目之间不存在隐式依赖关系。隐式依赖关系是通过引用资源的属性或模块的输出来创建的。该模块不提供有用的输出。在这种情况下,您可以尝试使用
depends_on
元参数,以便告诉 terraform 在尝试创建项目之前创建表。例如,您将执行以下操作:
module "dynamodb_table" {
source = "terraform-aws-modules/dynamodb-table/aws"
name = "${var.aws.region}-${var.config.dynamodb.table_name}"
hash_key = var.config.dynamodb.hash_key
attributes = [
{
name = var.config.dynamodb.hash_key
type = "S"
}
]
billing_mode = "PAY_PER_REQUEST"
table_class = "STANDARD"
}
resource "random_string" "random" {
length = 16
special = false
}
resource "aws_dynamodb_table_item" "table_item" {
depends_on = [module.dynamodb_table]
table_name = "${var.aws.region}-${var.config.dynamodb.table_name}"
hash_key = var.config.dynamodb.hash_key
item = <<ITEM
{
"${var.config.dynamodb.hash_key}": {"S": "${random_string.random.result}"},
"collections": {"M": {}}
}
ITEM
}