Unused aws provider/resource failing during plan

I need to conditionally include a module which depends on aws provider. However, when its count=0, the aws provider seams to try to initialize and fails during plan.

Top-level:

$ cat main.tf 
provider "aws" {}

module "mod" {
  count = 0         ## I don't want to execute this module.
  source = "./mod"
}

Module:

$ cat mod/main.tf
terraform {
  required_providers {
    aws = {
      version = ">= 4"
    }
  }
}

data "aws_iam_policy_document" "this" {
  count = 0
}

Error:

$ terraform  version
Terraform v1.3.6
on linux_amd64

$ terraform  plan
╷
│ Error: error configuring Terraform AWS Provider: no valid credential sources for Terraform AWS Provider found.
│ 
│ Please see https://registry.terraform.io/providers/hashicorp/aws
│ for more information about providing credentials.
│ 
│ Error: failed to refresh cached credentials, no EC2 IMDS role found, operation error ec2imds: GetMetadata, request send failed, Get "http://169.254.169.254/latest/meta-data/iam/security-credentials/": dial tcp 169.254.169.254:80: i/o timeout
│ 
│ 
│   with provider["registry.terraform.io/hashicorp/aws"],
│   on main.tf line 1, in provider "aws":
│    1: provider "aws" {}
│ 
╵

There is no aws credentials configured at all. Should aws provider even request for credentials since not a single request is being made to its API? There is any way to explicity tell to a module not to initialize?

What am I missing?

Unfortunately, Terraform doesn’t support conditional providers - it initializes all providers mentioned in the configuration whether they are used or not.

I think you’ll need to handle this condition by generating different .tf file content via your own automation layer before Terraform is called.

1 Like

Hey @maxb, thanks for your reply. I’m afraid that’s the only solution.

Best,
Mateus