How can I use 3rd party providers without declaring them in all the modules

Hi

I’m using a layered structure to manage TencentCloud resources for different environment. The project structure looks like following:

.
├── live
│   ├── credential.tf
│   ├── main.tf
│   ├── dev
│   │   ├── main.tf
│   │   └── network
│   │       ├── _inventory.tf
│   │       ├── _provider.tf
│   │       └── vpc.tf
│   └── prod
│        ├── main.tf
│        └── network
│             ├── _inventory.tf
│             ├── _provider.tf
│             └── vpc_tencentcloud.tf
└── modules
    └── tencentcloud
        └── vpc

I declared providers in the root module and pass them to child modules by using the “providers” directive. See the example below:

terraform {
  required_providers {
    tencentcloud = {
      source = "tencentcloudstack/tencentcloud"
      version = ">= 1.53.3"
    }
  }
}

# Shanghai
provider "tencentcloud" {
  alias      = "cnsh"
  region     = "ap-shanghai"
  secret_id  = local.TENCENTCLOUD_SECRET_ID
  secret_key = local.TENCENTCLOUD_SECRET_KEY
}

# Beijing
provider "tencentcloud" {
  alias      = "cnbj"
  region     = "ap-beijing"
  secret_id  = local.TENCENTCLOUD_SECRET_ID
  secret_key = local.TENCENTCLOUD_SECRET_KEY
}

module "env_dev" {
  source    = "./dev"
  providers = {
    tencentcloud.cnsh = tencentcloud.cnsh
    tencentcloud.cnbj = tencentcloud.cnbj
  }
}

module "env_prod" {
  source    = "./prod"
  providers = {
    tencentcloud.cnsh = tencentcloud.cnsh
    tencentcloud.cnbj = tencentcloud.cnbj
  }
}

Then in child modules, I have to declare those providers again over again to let Terraform search from tencentcloudstack/tencentcloud rather than hashicorp/tencentcloud.

terraform {
  required_providers {
    tencentcloud = {
      source = "tencentcloudstack/tencentcloud"
      version = ">= 1.53.3"
    }
  }
}

provider tencentcloud {
  alias = "cnsh"
}

provider tencentcloud {
  alias = "cnbj"
}

Do we have a nicer way to prevent such redundant code? Any suggestions will be appreciated. :grinning: