терраформная вложенная интерполяция со счетчиком - PullRequest
0 голосов
/ 09 июля 2019

Используя terraform, я хочу сослаться на содержимое списка файлов (в конечном итоге я хочу сжать их с помощью провайдера archive_file, но в контексте этого поста это не важно).Все эти файлы находятся в одном и том же каталоге, поэтому у меня есть две переменные:

variable "source_root_dir" {
  type        = "string"
  description = "Directory containing all the files"
}

variable "source_files" {
  type        = "list"
  description = "List of files to be added to the cloud function. Locations are relative to source_root_dir"
}

Я хочу использовать поставщик данных шаблона для ссылки на содержимое файлов.Учитывая, что число файлов в source_files может варьироваться, мне нужно использовать count для выполнения одинаковых операций на всех из них.

Благодаря информации, предоставленной в https://stackoverflow.com/a/43195932/201657 Я знаючто я могу ссылаться на содержимое одного файла следующим образом:

provider "template" {
  version = "1.0.0"
}

variable "source_root_dir" {
  type        = "string"
}

variable "source_file" {
  type        = "string"
}

data "template_file" "t_file" {
  template = "${file("${var.source_root_dir}/${var.source_file}")}"
}

output "myoutput" {
  value = "${data.template_file.t_file.rendered}"
}

Обратите внимание, что он содержит вложенные строковые интерполяции.Если я запускаю:

terraform init && terraform apply -var source_file="foo" -var source_root_dir="./mydir"

после создания файла mydir / foo, конечно, , то это вывод: enter image description here

Успех!

Теперь я хочу объединить этот синтаксис интерполяции вложенных строк с моим count.Следовательно, мой проект terraform теперь выглядит так:

provider "template" {
  version = "1.0.0"
}

variable "source_root_dir" {
  type        = "string"
  description = "Directory containing all the files"
}

variable "source_files" {
  type        = "list"
  description = "List of files to be added to the cloud function. Locations are relative to source_root_dir"
}

data "template_file" "t_file" {
  count    = "${length(var.source_files)}"
  template = "${file("${"${var.source_root_dir}"/"${element("${var.source_files}", count.index)}"}")}"
}

output "myoutput" {
  value = "${data.template_file.t_file.*.rendered}"
}

да, это выглядит сложно, но синтаксически, правильно (по крайней мере, я так думаю).Однако, если я запускаю init и применяю:
terraform init && terraform apply -var source_files='["foo", "bar"]' -var source_root_dir='mydir'

Я получаю ошибки:

Ошибка: data.template_file.t_file: 2 произошла ошибка (и):
* data.template_file.t_file [0]: __builtin_StringToInt: strconv.ParseInt: синтаксический анализ «mydir»: неверный синтаксис в:
$ {file («$ {" $ {var.source_root_dir} "/" $ {element("$ {var.source_files}", count.index)} "}")}
* data.template_file.t_file 1 : __builtin_StringToInt: strconv.ParseInt: синтаксический анализ "mydir": неверный синтаксисв:
$ {file ("$ {" $ {var.source_root_dir} "/" $ {element ("$ {var.source_files}", count.index)} "}")}

enter image description here

Мое лучшее предположение состоит в том, что он интерпретирует / как операцию деления, следовательно, он пытается проанализировать значение mydir in source_root_dir как int.

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

1 Ответ

0 голосов
/ 09 июля 2019

ОК, думаю, я понял это.formatlist на помощь

provider "template" {
  version = "1.0.0"
}

variable "source_root_dir" {
  type        = "string"
  description = "Directory containing all the files"
}

variable "source_files" {
  type        = "list"
  description = "List of files to be added to the cloud function. Locations are relative to source_root_dir"
}

locals {
  fully_qualified_source_files = "${formatlist("%s/%s", var.source_root_dir, var.source_files)}"
}

data "template_file" "t_file" {
  count    = "${length(var.source_files)}"
  template = "${file(element("${local.fully_qualified_source_files}", count.index))}"
}

output "myoutput" {
  value = "${data.template_file.t_file.*.rendered}"
}

при применении:

terraform init && terraform apply -var source_files='["foo", "bar"]' -var source_root_dir='mydir'

выходы:

Подать заявку полностью!Ресурсы: 0 добавлено, 0 изменено, 0 уничтожено.

Выходы:

myoutput = [Это содержимое foo
,
Это содержимое бара

]

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...