Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add multiple azure sql firewall rules in terraform

I have the following code that adds one firewall rule

resource "azurerm_sql_firewall_rule" "main" {
    name                        = "${azurerm_sql_server.main.name}-firewall"
    resource_group_name         = var.resource_group_name
    server_name                 = azurerm_sql_server.main.name
    start_ip_address            = "0.0.0.0"
    end_ip_address              = "0.0.0.0"
}

I have a number of rules I need to add, how would I do this in terraform and could the values come from a config file?

like image 521
dagda1 Avatar asked May 20 '26 11:05

dagda1


1 Answers

As I know, there are two ways to create a number of rules in the same code.

One is that use the count property in the resource. In this way, you can use the count.index to name the rules and use the list to store the start_ip_address and end_ip_address like below:

resource "azurerm_sql_firewall_rule" "main" {
    count                       = "${var.rule_number}"

    name                        = "${azurerm_sql_server.main.name}-firewall-${count.index}"
    resource_group_name         = var.resource_group_name
    server_name                 = azurerm_sql_server.main.name
    start_ip_address            = "${element(var.start_ip_address, count.index)}"
    end_ip_address              = "${element(var.end_ip_address, count.index)}"
}

This is the way that I recommend you, it's simple and suitable.

The other way is that use the for and for_each loop in your resource. Take a look at the document to learn about it. It's a little difficult, but I think it's not a problem for you.

like image 73
Charles Xu Avatar answered May 25 '26 10:05

Charles Xu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!