How do I specify all entries but the first with count?

I’m trying to deploy different things on servers, X on 1st, which is master and Y on all the rest, which are slaves.

Master is fine:
host = var.instance_public_dns[0]

I thought slaves may be as follows?
host = element(var.instance_public_dns, count.index + 1)
But no, it also includes the 1st.

Can anyone advise as to correct option for all but 1st?

try
element(var.instance_public_dns, ${count.index + 1})
or
element(var.instance_public_dns, count.index +2) ,element starts from 1 , count from 0

Thank you, but sorry to say that neither worked for me.
I could be on wrong path using element.

If you want to conditionally set the host attribute depending on whether count.index is 0 or not, you can use a conditional expression:

host = count.index > 0 ? var.instance_public_dns[count.index] : null

Ah yes, very good.
One thing though, It doesn’t like null.

host for provisioner cannot be empty

I should have clarified that host is in a connection block.

Yes, if this is a provisioner then host is required, so you will need to decide what the 0 value will be.

May not work as if ‘0’ it should do nothing.

Sorry, I’m not sure what you are trying to convey here. You must assign something, because you need a host for the provisioner’s connection. If the instance configurations are significantly different, it may be easier to have the “master” use a different resource block from the rest. Another possibly simpler option is to create a mapping of instances keys to configuration data, which can then be processed using for_each instead of count.

1 Like

I have 2 resource blocks

resource “null_resource” “setup_master” {

host = var.instance_public_dns[0]

&

resource “null_resource” “setup_slave” {

host = ??? NOT var.instance_public_dns[0]

I was hoping to just set all after index 0 for save but it is proving more difficult that I expected.

It would be nice to resolve this as much for my understanding as anything else.

I decided to split instance creation into separate resources, each with it’s own count, i.e.

master_count = “X”
slave_count = “Y”

I created locals.tf as follows.

locals {
node_count = var.master_count + var.slave_count
all_public_dns = distinct(concat(aws_instance.master[].public_dns, aws_instance.slave[].public_dns))
all_private_ip = distinct(concat(aws_instance.master[].private_ip, aws_instance.slave[].private_ip))
all_names = distinct(concat(aws_instance.master[].tags.Name, aws_instance.slave[].tags.Name))
}

and datasources.tf as follows.

data “template_file” “configure” {
count = local.node_count
template = file(“${path.module}/files/configure.sh”)

vars = {
instance_name = local.all_names[count.index]
all_names = join(" “, aws_instance.master[].tags.Name, aws_instance.slave[].tags.Name)
all_ips = join(” ", aws_instance.master[].private_ip, aws_instance.slave[].private_ip)
}
}