在下面的代码块中,我尝试将服务器名称数组传递给attribute_json块:
resource "aws_instance" "consul-server" {
ami = var.consul-server
instance_type = "t2.nano"
key_name = var.aws_key_name
iam_instance_profile = "dna_inst_mgmt"
vpc_security_group_ids = [
"${aws_security_group.yutani_consul.id}",
"${aws_security_group.yutani_ssh.id}"
]
subnet_id = "${aws_subnet.public_1_subnet_us_east_1c.id}"
associate_public_ip_address = true
tags = {
Name = "consul-server${count.index}"
}
root_block_device {
volume_size = "30"
delete_on_termination = "true"
}
connection {
type = "ssh"
user = "chef"
private_key = "${file("${var.aws_key_path}")}"
timeout = "2m"
agent = false
host = self.public_ip
}
count = var.consul-server_count
provisioner "chef" {
attributes_json = <<-EOF
{
"consul": {
"servers": ["${split(",",aws_instance.consul-server[count.index].id)}"]
}
}
EOF
use_policyfile = true
policy_name = "consul_server"
policy_group = "aws_stage_enc"
node_name = "consul-server${count.index}"
server_url = var.chef_server_url
recreate_client = true
skip_install = true
user_name = var.chef_username
user_key = "${file("${var.chef_user_key}")}"
version = "14"
}
}
运行此命令会给我一个错误:
Error: Cycle: aws_instance.consul-server[1], aws_instance.consul-server[0]
(这是在var.consul-server_count变量中声明为2的计数之后)
谁能告诉我这样做的正确方法是什么?
答案 0 :(得分:0)
这里有两个问题:(1)如何在JSON字符串中插入以逗号分隔的列表; (2)导致循环依赖性错误的原因。
最干净的方法是完全不使用Heredoc,而仅使用jsonencode
函数。
您可以这样做:
locals {
arr = ["host1", "host2", "host3"]
}
output "test" {
value = jsonencode(
{
"consul" = {
"servers" = local.arr
}
})
}
这产生了输出:
Outputs:
test = {"consul":{"servers":["host1","host2","host3"]}}
Chef提供者的文档建议对JSON字符串使用heredoc,因此您也可以这样做:
locals {
arr = ["host1", "host2", "host3"]
sep = "\", \""
}
output "test" {
value = <<-EOF
{
"consul": {
"servers": ["${join(local.sep, local.arr)}"]
}
}
EOF
}
如果我这样做:
Outputs:
test = {
"consul": {
"servers": ["host1", "host2", "host3"]
}
}
这里要注意一些事情:
您正在尝试加入主机,以使它们在JSON数组的上下文中成为有效的JSON。您需要加入","
,而不仅仅是逗号。这就是为什么我定义了局部变量sep = "\", \""
。
您似乎在似乎显然需要split
的情况下尝试join
。
错误消息的原因:
Error: Cycle: aws_instance.consul-server[1], aws_instance.consul-server[0]
是您具有循环依赖性。考虑以下简化示例:
resource "aws_instance" "example" {
count = 3
ami = "ami-08589eca6dcc9b39c"
instance_type = "t2.micro"
user_data = <<-EOF
hosts="${join(",", aws_instance.example[count.index].id)}"
EOF
}
或者您也可以在其中使用splat表示相同的结果,即aws_instance.example.*.id
。
Terraform计划会产生:
▶ terraform012 plan
...
Error: Cycle: aws_instance.example[2], aws_instance.example[1], aws_instance.example[0]
因此那里会出现循环错误,因为aws_instance.example.*.id
取决于所创建的aws_instance.example
,因此资源取决于自身。换句话说,您不能在资源本身内部使用资源导出的值。
我对Consul知之甚少,但同样,我有点困惑为什么您想要servers
字段中的EC2实例ID。 Consul配置不会在那儿获取IP地址或主机名吗?
无论如何,您可能需要自己在此资源之外计算主机名,既可以作为静态输入参数,也可以通过某种方式进行计算。而且我想您最终会得到类似的东西:
variable "host_names" {
type = list
default = ["myhost1"]
}
resource "aws_instance" "consul_server" {
...
provisioner "chef" {
attributes_json = jsonencode(
{
"consul" = {
"servers" = var.host_names
}
})
}
}