Is it possible with import block to a module to use a provider from the module?

Is it possible when importing into a module to use a provider from the module? My goal is to avoid putting things related only to the module in the root config (and also to avoid redundancy).

I have a case where the provider datadog is used, and therefore declared, only in a certain module. I have tried the following with terraform v1.6.1, but it fails:

/main.tf:

import {
  to       = module.logging.datadog_logs_index.main
  id       = "main"
  provider = module.logging.datadog
}

Output:

$ terraform init

Initializing the backend...
Initializing modules...
╷
│ Error: Invalid import provider argument
│ 
│   on main.tf line 75, in import:
│   75:   provider = module.logging.datadog
│ 
│ The provider argument can only be specified in import blocks that will generate
│ configuration.
│ 
│ Use the providers argument within the module block to configure providers for all resources
│ within a module, including imported resources.
╵

╷
│ Error: Invalid provider configuration reference
│ 
│   on main.tf line 75, in import:
│   75:   provider = module.logging.datadog
│ 
│ The provider argument requires a provider type name, optionally followed by a period and
│ then a configuration alias.
╵

I have got it to work by declaring the datadog provider at the root-level, but this seems redundant (but perhaps necessary).

Allow import blocks within child modules · Issue #33474 · hashicorp/terraform · GitHub may help with my situation in the long run, in any case.

Hi @jkburges,

In Terraform as currently implemented, provider configurations only propagate “down” through module calls, from ancestor to descendant. Unfortunately that’s an assumption that runs quite deep in the Terraform runtime and so is unlikely to change.

The issue you linked to, about allowing import blocks in shared modules, is I think the most likely way this would get resolved, so that the import block could live in the child module alongside the provider configuration it uses.

The main constraint would be that it would probably not support the code generation aspect of importing, because Terraform treats all but the root module as read-only since non-root modules are often shared across multiple callers and so tend to need hand-written resource configurations to describe the general rule for the declaration, rather than importing just one specific example from the current configuration’s state.

If I recall correctly, the reason that didn’t make it into the first iteration of the feature is that the first iteration also required hard-coded ids, and was therefore basically impossible to use in any module that is called from more than one place, since the id to import would vary. Subsequent improvements such as allowing the id to be dynamic have been incremental steps toward making the feature flexible enough to make sense to use inside a shared module.