如何在地形脚本中多次使用random_password。 例如:
resource "random_password" "password" {
length = 16
special = true
override_special = "_%@"
}
resource "aws_db_instance" "example" {
instance_class = "db.t3.micro"
allocated_storage = 64
engine = "mysql"
username = "someone"
password = random_password.password.result
}
这将工作一次。 如果我需要创建怎么办
resource "random_password" "password" {
length = 16
special = true
override_special = "_%@"
}
resource "aws_db_instance" "example1" {
instance_class = "db.t3.micro"
allocated_storage = 64
engine = "mysql"
username = "someone"
password = random_password.password.result
}
resource "aws_db_instance" "example2" {
instance_class = "db.t2.small"
allocated_storage = 64
engine = "mysql"
username = "anyone"
password = random_password.password.result
}
现在我需要创建 2 个随机密码。我可以在随机密码中使用计数吗?
您可以使用计数或for_each循环。
resource "random_password" "password" {
count = 2
length = 16
special = true
override_special = "_%@"
}
resource "aws_db_instance" "example" {
for_each = random_password.password
instance_class = "db.t3.micro"
allocated_storage = 64
engine = "mysql"
username = "someone"
password = each.value.result
}
这将导致
结果值random_password.password[0].result
和random_password.password[1].result
(当使用for_each或计数进行递归时,没有索引的random_password.password
将被视为与terraform中的任何其他地图一样(。我在示例中将计数设置为 2,但这可以是任何
int.andaws_db_instance.example[0]
和aws_db_instance.example[1]
,由for_each
循环根据random_password.password
对象的数量创建。在循环中,您将资源引用为each.value
(因此,each.value.result
等同于random_password.password.result
(
有关for_each
的更多信息,请单击此处
编辑:重要说明...这只是一个计数/for_each工作原理的示例。根据您创建的密码数量来计算实例数量真的很尴尬(想想看......您需要采取更大的图片视图并考虑您实际想要如何扩展您的项目,然后将计数/for_each逻辑基于此。
EDIT2(因为我没有足够的业力来评论(:没有理由输出不应该工作。您使用的是哪个版本的 tf?
此外,要获取结果列表,您可以执行以下操作:
output "passwords" {
value = random_password.password[*].result
}
如果您生成的每个密码的密码要求相同(可能是您的情况(,请使用count
:
resource "random_password" "passwords" {
count = 2
length = 16
special = true
}
resource "aws_db_instance" "db_instance_1" {
...
password = random_password.passwords[0].result
}
resource "aws_db_instance" "db_instance_2" {
...
password = random_password.passwords[1].result
}
output "db_instance_1_password" {
value = random_password.passwords[0].result
}
output "db_instance_2_password" {
value = random_password.passwords[1].result
}
如果密码要求不同,请定义多个random_password
资源:
resource "random_password" "password_1" {
length = 16
special = true
}
resource "random_password" "password_2" {
length = 16
special = false
min_upper = 1
min_lower = 1
min_numeric = 1
}
resource "aws_db_instance" "db_instance_1" {
...
password = random_password.password_1.result
}
resource "aws_db_instance" "db_instance_2" {
...
password = random_password.password_2.result
}
output "db_instance_1_password" {
value = random_password.password_1.result
}
output "db_instance_2_password" {
value = random_password.password_2.result
}
在这两种情况下,请考虑在输出中设置sensitive = true
以隐藏 Terraform 命令输出中的原始密码。