0

我正在使用 Terraform (v. 12.10) 创建一个 DNS 记录 AWS,并希望获取已经创建的 ALB 的名称(在另一个模块中)。

我已经阅读了文档,但没有找到任何解决方案。有什么办法吗?

resource "aws_route53_record" "dns" {
  provider        = <AWS>
  zone_id         = <ZONE_ID>
  name            = <NAME>
  ttl             = 30
  type            = "CNAME"
  records         = <LB_created_previously>
}
4

2 回答 2

1

模块定义

$ cat module/out.tf
output "somevar" {
value = "somevalue"
}

使用模块:

$ cat main.tf
module "getname" {
source = "./module"
}
resource "aws_sns_topic" "user_updates" {
  name = module.getname.somevar
}


目录结构:

$ tree
.
├── main.tf
├── module
│   └── out.tf
└── terraform.tfstate

terraform apply

$ terraform  apply

..
  + create

Terraform will perform the following actions:

  # aws_sns_topic.user_updates will be created
  + resource "aws_sns_topic" "user_updates" {
      + arn    = (known after apply)
      + id     = (known after apply)
      + name   = "somevalue"
      + policy = (known after apply)
    }

...

  Enter a value: yes

aws_sns_topic.user_updates: Creating...
aws_sns_topic.user_updates: Creation complete after 1s [id=arn:aws:sns:us-east-1:123456789:somevalue]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

模块组成

于 2021-02-02T18:44:38.040 回答
1

你在这里基本上有两个选择。

选项 1 - 如果您的资源创建(在您的情况下是 DNS 记录)和模块创建的 ALB 位于同一个位置(相同的 terraform.tfstate 文件) - 这或多或少由上面的samtoddler回答或与您伪-代码看起来像这样:

resource "aws_route53_record" "dns" {
  provider        = <AWS>
  zone_id         = <ZONE_ID>
  name            = <NAME>
  ttl             = 30
  type            = "CNAME"
  records         = [module.<LB__module_definiton_name>.elb_dns_name]
}

在您的 ELB 模块中,您需要以下内容:

output "elb_dns_name" {
value = aws_elb.<LB_created_previously>.dns_name
}

在选项二中,您必须在模块本身中定义相同的输出。但是,如果您的 DNS 资源代码处于不同的文件夹/terraform 状态,则您需要使用 terraform 远程状态:

data "terraform_remote_state" "elb" {
  backend = "mybackendtype"
  config = {
    ...
  }
}

然后您的代码将如下所示:

resource "aws_route53_record" "dns" {
  provider        = <AWS>
  zone_id         = <ZONE_ID>
  name            = <NAME>
  ttl             = 30
  type            = "CNAME"
  records         = [data.terraform_remote_state.elb.outputs.elb_dns_name]
}

顺便说一句,当您有 ELB 时,最好使用Alias 而不是 CNAME 记录,它基于dns 记录资源的 terraform 文档,您的伪代码将是:

resource "aws_route53_record" "dns" {
  zone_id         = <ZONE_ID>
  name            = <NAME>
  type    = "A"

  alias {
    name                   = module.<LB__module_definiton_name>.elb_dns_name
    zone_id                = module.<LB__module_definiton_name>.elb_zone_id
    evaluate_target_health = true
  }
}
于 2021-02-02T20:39:09.247 回答