如何使提供程序配置可选并基于 terraform 中的条件

How to make the provider configuration optional and based on the condition in terraform

这是我的提供商配置:

provider "azurerm" {

  features {}

        subscription_id = "${var.azure.AzureSubscriptionId}"

        client_id       = "${var.azure.AzureClientId}"

        client_secret   = "${var.azure.AzureClientSecret}"

        tenant_id       = "${var.azure.AzureTenantId}"

        skip_provider_registration = true

}

provider "aws" {

        region     = "${var.aws.AwsRegion}"

        access_key = "${var.aws.AwsAccessKey}"

        secret_key = "${var.aws.AwsSecretKey}"

}

我的根模块是这样配置的:

module "aws_bootstrap_vm" {

      count = var.CloudProvider == "aws" ? 1 : 0
      source = "./modules/aws/bootstrap_vm"
}

module "azure_bootstrap_vm" {

      count = var.CloudProvider == "azure" ? 1 : 0
      source = "./modules/azure/bootstrap_vm"
}

目前我需要为 aws 和 azure 提供凭据才能使其正常工作,否则当我只想使用 AWS 模块时会出现此错误:

 Error: building AzureRM Client: 1 error occurred:
│       * A Subscription ID must be configured when authenticating as a Service Principal using a Client Secret.
│

我的文件夹结构如下所示:

├───modules
│   ├───aws
│   │   ├───prepare_cloud
│   │   │   ├───config
│   │   │   └───templates
│   │   ├───virtual_network
│   └───azure
│       ├───prepare_cloud
│       │   └───config
│       ├───virtual_network
└───main

正如 Martin Atkins 在评论中提到的那样,不可能暂时在 terraform 中动态配置提供程序。

作为解决方法,如果您使用的是要求用户输入的输入变量,您可以单独调用模块配置文件 .例如,将有 两个配置文件夹,一个用于 AWS,一个用于 Azure.

AWS
├───modules
│   ├───aws
│   │   ├───prepare_cloud
│   │   │   ├───config
│   │   │   └───templates
│   │   ├───virtual_network
└───main

Azure
├───modules
|   |───azure
│   |   ├───prepare_cloud
│   |   │   └───config
│   |   ├───virtual_network
└───main

如果您提供provider.tf中使用的所有变量的值,那么您可以使用您的配置。因此,当您使用 时,两个提供程序都将被初始化 但根据您的要求 只有所需模块将 运行.