简体   繁体   中英

Manage multiple workspaces from a single configuration file in terraform

I want to create two different workspaces on Terraform Cloud: One for DEV environment, the other for PROD environment.

I am trying to create them hust using a single configuration file. The infrastructure will be the same just in two different Azure subscriptions with different credentials.

Here the code I am trying:

terraform {
  required_version = ">= 1.1.0"
  
  required_providers {
    #https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~> 3.40.0"
    }
  }
  
  cloud {
    organization = "mycompany"
    
    workspaces {
      tags = ["dev", "prod"]
    }
  }
}

I am watching the documentantion . It seems like inside the cloud -> workspace command I just can use either name or tags attributes. It is required I have at least one of them in my configuration.

Now in my Terraform Cloud account, I have two workspaces: 1 with the tag prod and one with the tag dev .

I set the envinroment variable:

$Env:TF_WORKSPACE="mycompany-infrastructure-dev"

And I try to initialize Terraform Cloud:

terraform init

But I get this error:

Error: Invalid workspace selection Terraform failed to find workspace "mycompany-infrastructure-dev" with the tags specified in your configuration: │ [dev, prod]

How can I create one configuration that I can use with different environment/workspaces?

Thank you

First, I ran the similar code as yours in my environment and received an error shown below: It prompted me to use terraform login to generate a token for accessing the organization on Terraform Cloud .

The login was successful, and the browser generated an API token.

在此处输入图像描述

Token received and entered.

Logged into Terraform cloud as shown:

在此处输入图像描述

In Terraform Cloud -> Organizations , I created a new organization :

在此处输入图像描述

Script for creating different workspaces from a single configuration file:

cloud {
    organization = "mycompanyone"
    
    workspaces {
      tags = ["dev", "prod"]
      }
      }

Taken your script and made a few changes as seen below:

在此处输入图像描述

Terraform will prompt for basic concerns while initializing, as shown here.

在此处输入图像描述

Now run terraform init or terraform init -upgrade .

terraform initialized successfully:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM