Use provider alias from a module


I actually use a custom terraform module for deploy my openstack servers. In this module I defined multiple openstack context with alias. Example (in my module):

provider "openstack" {
  alias       = "project1"
  user_name   = data.vault_kv_secret_v2.openstack["project1"].data["username"]
  tenant_name = data.vault_kv_secret_v2.openstack["project1"].data["tenant_name"]
  password    = data.vault_kv_secret_v2.openstack["project1"].data["password"]
  auth_url    = "xxxx"
  region      = element(var.regions["project1"], 0)

Then I use my module

module "mymodule" {
  source      = "XXXX"
  servers     = var.servers
  environment = var.environment

But in some case I would like to create specific resources which doesn’t exist on my module. LIke that:

resource "openstack_blockstorage_volume_v3" "srv" {
  for_each = var.servers
  name     = "srv"
  size     = 1
  provider  = openstack.project1

resource "openstack_blockstorage_volume_attach_v3" "srv" {
  for_each  = var.servers
  volume_id = openstack_blockstorage_volume_v3.srv[each.key].id
  device    = "/dev/vdc"
  host_name = module.mymodule.openstack_compute_instance_v2.project1[each.key].name
  provider  = openstack.project1

The provider reference doesn’t work. It’s possible to get my provider alias build in my module ? I’ve see Providers Within Modules - Configuration Language | Terraform | HashiCorp Developer but it’s seems to be the other way around


The element function is usually not used in modern Terraform.

It’s clearer to write

  region      = var.regions["project1"][0]

In modern Terraform, all providers should be defined in the root module of the Terraform configuration - not within a child module brought in via a module block.

The ability to define providers inside child modules still exists, for the sake of compatibility with older configurations, but using it disables the ability to use for_each, count or depends_on at the module level, and can make future changes to the configuration that remove the module harder.

It is not possible to access a provider defined inside a child module, from the root module.


Ty for your reply and the advice about the array reference.

That why I thinking about declare provider in a module, but my module is mostly for simplify the provider declaration of my multiple openstack cluster. But maybe I need to find another workflow