Terraform how to define a variable to let user choose existing resource or create new one

Viewed 215

I am new to Terraform. I am having this question, would like to ask here.

So I am creating a azurerm_storage_account with all these input variables

#ie: 

resource "azurerm_storage_account" "example" {
  name                     = "storageaccountname"
  resource_group_name      = azurerm_resource_group.example.name
  location                 = azurerm_resource_group.example.location
  account_tier             = "Standard"
  account_replication_type = "GRS"

  tags = {
    environment = "staging"
  }
}

How to define a variable can allow user to choose the existing storage account or creating a new one.

I am thinking to do this:

variable "choice" {
  description = "Allow user to choose the existing storage account or creating a new one"
  type = string
  default = "create" 
}

Then I don't know where to use this variable to work with the azurerm_storage_account resource.

Any pointer would be appreciate!

Thank you.

1 Answers

You can use count for that. Thus if your variable is "create", a new resource is going to be created. If its not, then a azurerm_storage_account data source will be used to query for details of the existing resource.

resource "azurerm_storage_account" "example" {

  count                    = var.choice == "create" ? 1 : 0

  name                     = "storageaccountname"
  resource_group_name      = azurerm_resource_group.example.name
  location                 = azurerm_resource_group.example.location
  account_tier             = "Standard"
  account_replication_type = "GRS"

  tags = {
    environment = "staging"
  }
}

data "azurerm_storage_account" "example" {

 count                    = var.choice == "create" ? 0 : 1
 
 #...

}

Related