Reputation: 17
I'm trying to create an Azure public IP prefix (/30) then assign a public IP from the prefix (4 times) then assign them as outputs to use in a separate module later. I would like to assign one of the IPs in the NIC listed, then "save" the other 3 as an output for later use. I am however getting the following error:
│ The "count" object can only be used in "module", "resource", and "data"
│ blocks, and only when the "count" argument is set.
I am also struggling with the syntax in how to reference each IP as an output (I've included the outputs.tf below but know the syntax is wrong):
main.tf
resource "azurerm_public_ip_prefix" "ipprefix" {
name = "tempprefixname"
location = var.rglocation
resource_group_name = var.rgname
prefix_length = 30
}
resource "azurerm_public_ip" "publicip" {
count = 4
name = "${var.publicipname}-${count.index}"
location = var.rglocation
resource_group_name = var.rgname
allocation_method = "Static"
sku = "Basic"
public_ip_prefix_id = azurerm_public_ip_prefix.ipprefix.id
}
resource "azurerm_network_interface" "nic" {
name = var.nicname
location = var.rglocation
resource_group_name = var.rgname
ip_configuration {
name = var.ipconfigname
subnet_id = azurerm_subnet.subnet.id
private_ip_address_allocation = "Dynamic"
public_ip_address_id = azurerm_public_ip.publicip[count.index].id
}
}
outputs.tf
output "publicipoutput1" {
value = azurerm_public_ip.publicip.ip_address[count.1]
}
output "publicipoutput2" {
value = azurerm_public_ip.publicip.ip_address[count.2]
}
output "publicipoutput3" {
value = azurerm_public_ip.publicip.ip_address[count.3]
}
output "publicipoutput4" {
value = azurerm_public_ip.publicip.ip_address[count.4]
}
Upvotes: 0
Views: 1173
Reputation: 18213
When you start using count
, you have to use it in all places where you reference any other resource created with count
[1]. So, if you used count
in azurerm_public_ip
, you have to use count
in azurerm_network_interface
as well and not just count.index
:
resource "azurerm_network_interface" "nic" {
count = 4
name = var.nicname
location = var.rglocation
resource_group_name = var.rgname
ip_configuration {
name = var.ipconfigname
subnet_id = azurerm_subnet.subnet.id
private_ip_address_allocation = "Dynamic"
public_ip_address_id = azurerm_public_ip.publicip[count.index].id
}
}
As you can see from the error, output
cannot use count
, but you can select all of the values by using the splat expression [2]:
output "public_ip_addresses" {
value = [ azurerm_public_ip.publicip[*].ip_address ]
}
[1] https://www.terraform.io/language/meta-arguments/count
[2] https://www.terraform.io/language/expressions/splat
Upvotes: 2