Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform conditional argument block

I have created a module in order deploy the below azurerm_automation_schedule resource:

resource "azurerm_automation_schedule" "example" {
  name                    = var.aaname
  resource_group_name     = azurerm_resource_group.example.name
  automation_account_name = azurerm_automation_account.example.name
  frequency               = var.frequency              
  interval                = var.interval
  timezone                = "Australia/Perth"
  start_time              = "2014-04-15T18:00:15+02:00"
  description             = "This is an example schedule"

  monthly_occurrence {
                      day = monthly_occurrence.value.day
                      occurrence = monthly_occurrence.value.occurrence
                  }
 }

The existence of monthly_occurrence block argument must be conditional as it is only needed when the frequency is "Month" otherwise it throws error.

Is there a way to create this monthly_occurrence block argument conditionally? I am using terraform 0.13.5 and azurerm 2.38.0

I have tried with for_each but i couldn't find the solution. Is there any way to do it?

like image 875
MoonHorse Avatar asked Oct 19 '25 04:10

MoonHorse


2 Answers

You can use dynamic block to make monthly_occurrence conditional. For example:

resource "azurerm_automation_schedule" "example" {
  name                    = var.aaname
  resource_group_name     = azurerm_resource_group.example.name
  automation_account_name = azurerm_automation_account.example.name
  frequency               = var.frequency              
  interval                = var.interval
  timezone                = "Australia/Perth"
  start_time              = "2014-04-15T18:00:15+02:00"
  description             = "This is an example schedule"

  dynamic "monthly_occurrence" {
    for_each = var.frequency == "Month" ? [1] : []
    content {
       day = monthly_occurrence.value.day
       occurrence = monthly_occurrence.value.occurrence
    }
  }
}
like image 72
Marcin Avatar answered Oct 21 '25 18:10

Marcin


You can do this by combining the conditional expressions with dynamic blocks in order to create a conditional dynamic block for the monthly occurence.

You'll have something like this:

  dynamic "monthly_occurrence" {
    for_each = var.frequency == Month ? 1 : 0
    content {
       day = monthly_occurrence.value.day
       occurrence = monthly_occurrence.value.occurrence
    }
  }
like image 39
Nick Avatar answered Oct 21 '25 17:10

Nick



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!