MoonHorse
MoonHorse

Reputation: 2479

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?

Upvotes: 4

Views: 2250

Answers (2)

Nick
Nick

Reputation: 1273

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
    }
  }

Upvotes: 2

Marcin
Marcin

Reputation: 238081

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
    }
  }
}

Upvotes: 7

Related Questions