只是让您知道,如果您尝试将资源的输出放入 SSM 参数中,则需要运行两次“应用”。
这就是 Terraform 的运行方式,它首先将您的资源记录到输出中,然后您可以在第一次应用后使用它们。
但也许这个简单的解决方案对你有用?
resource "aws_security_group" "allow_tls" {
name = "allow_tls"
description = "Allow TLS inbound traffic"
vpc_id = "vpc-xxxxxxxxxxxxx"
ingress {
description = "TLS from VPC"
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["10.1.0.0/16"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
ipv6_cidr_blocks = ["::/0"]
}
tags = {
Name = "allow_tls"
}
}
resource "aws_ssm_parameter" "sg" {
name = "/test/tls-sg-id"
description = "Allow TLS Security Group ID"
type = "String"
value = aws_security_group.allow_tls.id
tags = {
environment = "Testing"
}
}
然后,当您申请时,Terraform 会计算依赖关系并相应地应用:
20:47 $ terraform apply
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the
following symbols:
+ create
Terraform will perform the following actions:
# aws_security_group.allow_tls will be created
+ resource "aws_security_group" "allow_tls" {
+ arn = (known after apply)
+ description = "Allow TLS inbound traffic"
+ egress = [
+ {
+ cidr_blocks = [
+ "0.0.0.0/0",
]
+ description = ""
+ from_port = 0
+ ipv6_cidr_blocks = [
+ "::/0",
]
+ prefix_list_ids = []
+ protocol = "-1"
+ security_groups = []
+ self = false
+ to_port = 0
},
]
+ id = (known after apply)
+ ingress = [
+ {
+ cidr_blocks = [
+ "10.1.0.0/16",
]
+ description = "TLS from VPC"
+ from_port = 443
+ ipv6_cidr_blocks = []
+ prefix_list_ids = []
+ protocol = "tcp"
+ security_groups = []
+ self = false
+ to_port = 443
},
]
+ name = "allow_tls"
+ name_prefix = (known after apply)
+ owner_id = (known after apply)
+ revoke_rules_on_delete = false
+ tags = {
+ "Name" = "allow_tls"
}
+ tags_all = {
+ "Name" = "allow_tls"
}
+ vpc_id = "vpc-xxxxxxxxxxx"
}
# aws_ssm_parameter.sg will be created
+ resource "aws_ssm_parameter" "sg" {
+ arn = (known after apply)
+ data_type = (known after apply)
+ description = "Allow TLS Security Group ID"
+ id = (known after apply)
+ key_id = (known after apply)
+ name = "/test/tls-sg-id"
+ tags = {
+ "environment" = "Testing"
}
+ tags_all = {
+ "environment" = "Testing"
}
+ tier = "Standard"
+ type = "String"
+ value = (sensitive value)
+ version = (known after apply)
}
然后我在 SSM Parameter 中得到了这个值:
20:48 $ aws ssm describe-parameters --parameter-filters "Key=Name,Values=/test/tls-sg-id"
{
"Parameters": [
{
"Name": "/test/tls-sg-id",
"DataType": "text",
"LastModifiedDate": 1628020084.521,
"Version": 1,
"LastModifiedUser": "arn:aws:iam:::user/oli",
"Policies": [],
"Tier": "Standard",
"Type": "String",
"Description": "Allow TLS Security Group ID"
}
]
}