Terraform: вывод модуля

Oct 30 2020

У нас есть три рабочих пространства в app.terraform.io,

  • КОНТРОЛЬНАЯ РАБОТА
  • DEV
  • PRO

В этих рабочих областях есть переменные.

Я получаю значение этих переменных с помощью ...

variable "environment" {}

Я хочу использовать эту переменную, чтобы выбрать, какие ресурсы или модули загружать.

resource "aws_directory_service_directory" "ds" {
  count = "${var.environment == "TEST" ? 0 : 1}"
  
  name       = "example.com"
  short_name = "example"
  password   = "******"
  type       = "MicrosoftAD"
}

Это работает, но ...

Обычный вывод для этого ресурса ...

output id {
  description = "The ID of the directory"
  value       = aws_directory_service_directory.ds.id
}

output access_url {
  description = "The access URL for the directory"
  value       = aws_directory_service_directory.ds.access_url
}

output dns_ip_addresses {
  description = "A list of IP addresses of the DNS servers for the directory or connector"
  value       = aws_directory_service_directory.ds.dns_ip_addresses
}

output security_group_id {
  description = "The ID of the security group created by the directory"
  value       = aws_directory_service_directory.ds.security_group_id
}

Но если я использую атрибут count, вывод hte не выполняется с ...

Because aws_directory_service_directory.ds has "count" set, its attributes
must be accessed on specific instances.

For example, to correlate with indices of a referring resource, use:
    aws_directory_service_directory.ds[count.index]

mixture of literal strings and interpolations. This deprecation applies only
to templates that consist entirely of a single interpolation sequence.


Error: Missing resource instance key

  on outputs.tf line 51, in output "security_group_id":
  51:   value       = aws_directory_service_directory.ds.security_group_id

Because aws_directory_service_directory.ds has "count" set, its attributes
must be accessed on specific instances.

For example, to correlate with indices of a referring resource, use:
    aws_directory_service_directory.ds[count.index]

Что будет на выходе?

Я старался:

output id {
  description = "The ID of the directory"
  value       = aws_directory_service_directory.ds[0].id
}

и:

output id {
  description = "The ID of the directory"
  value       = aws_directory_service_directory.ds[1].id
}

Но не работает (тоже)

  on outputs.tf line 36, in output "id":
  36:   value       = aws_directory_service_directory.ds[0].id
    |----------------
    | aws_directory_service_directory.ds is empty tuple

The given key does not identify an element in this collection value.

Error: Invalid index

  on outputs.tf line 36, in output "id":
  36:   value       = aws_directory_service_directory.ds[1].id
    |----------------
    | aws_directory_service_directory.ds is tuple with 1 element

The given key does not identify an element in this collection value.

Я пытался посмотреть, как это делается, например, https://github.com/terraform-aws-modules/terraform-aws-vpc

output "vpc_id" {
  description = "The ID of the VPC"
  value       = concat(aws_vpc.this.*.id, [""])[0]
}

так ...

output id {
  description = "The ID of the directory"
  value       = concat(aws_directory_service_directory.*.id, [""])[0]
}

но ...

Error: Invalid reference

  on outputs.tf line 36, in output "id":
  36:   value       = concat(aws_directory_service_directory.*.id, [""])[0]

A reference to a resource type must be followed by at least one attribute
access, specifying the resource name.

Ответы

3 BinaryMonster Oct 30 2020 at 09:49

Что ж, ничего сложного, просто вывод ищет ресурс, который не создан, поскольку terraform все еще ссылается на этот ресурс, из-за которого он выдает ошибку.

Хотя есть несколько способов решить эту проблему, один из них - объединить все ресурсы в виде списка за один шаг и получить один элемент с помощью встроенных функций terraform.

Ваш результат должен быть примерно таким, если вы используете счетчик в качестве условия для создания ресурсов. Если ресурс создан, выводом будет идентификатор ресурса. Когда счетчик равен нулю, вывод будет пустым без ошибок.

output id {
  description = "The ID of the directory"
  value       = element(concat(aws_directory_service_directory.ds.*.id, list("")), 0)
}