【问题标题】:Get variable from terraform cloud从 terraform 云中获取变量
【发布时间】:2021-02-06 08:04:39
【问题描述】:

我正在尝试https://app.terraform.io/免费计划

我已经在 UI 中设置了一些变量。

现在,我想在我的 terraform 代码中使用这些变量。

首先我设置为后端

terraform {
  required_providers {
    aws = {
      source = "hashicorp/aws"
      version = "~> 2.70"
    }
  }
  backend "remote" {
    organization = "mycompany"

    workspaces {
      name = "DEV"
    }
  }
}

我也设置了数据源

data "terraform_remote_state" "mycompany" {
  backend = "remote"

  config = {
    organization = "mycompany"

    workspaces = {
      name = "DEV"
    }
  }
}

现在我尝试使用这些变量

provider "aws" {
  region     = var.region
  access_key = data.terraform_remote_state.mycomany.aws_access_key 
  secret_key = data.terraform_remote_state.mycomany.aws_secret_key 
}

当我运行 terraform apply 我得到...

Error: Unsupported attribute

  on main.tf line 3, in provider "aws":
   3:   access_key = data.terraform_remote_state.mycomany.aws_access_key

This object has no argument, nested block, or exported attribute named
"aws_access_key"

我已阅读 https://www.terraform.io/docs/cloud/workspaces/variables.htmlhttps://www.hashicorp.com/blog/variable-management-in-terraform-cloud 和更多文档。

我无法理解这个...(来自https://www.terraform.io/docs/cloud/workspaces/variables.html

查找变量名 Terraform Cloud 无法从工作区的 Terraform 代码中自动发现变量名称。您必须通过阅读代码或文档发现必要的变量名称,然后手动输入它们。

如果缺少所需的输入变量,工作空间中的 Terraform 计划将失败并在日志中打印说明。

所以,我的责任是……

如何同时使用 Terraform 云中的普通变量和环境变量?

【问题讨论】:

    标签: terraform


    【解决方案1】:

    我不需要数据源。

    我需要将变量(没有值)注册到,例如 variables.tf

    ############################# 
    # FROM WORKSPACE
    #############################
    variable "aws_access_key" {}
    variable "aws_secret_key" {}
    

    现在,您可以照常使用变量了

    provider "aws" {
      region     = var.region
      access_key = var.aws_access_key 
      secret_key = var.aws_secret_key 
    }
    

    要在工作区之间进行更改(以重用我们的代码),我们可以使用前缀而不是名称来更改远程配置。然后 terraform CLI 向我们询问工作空间,或者您可以使用 terraform workspace select

    选择它
    terraform {
      required_providers {
        aws = {
          source = "hashicorp/aws"
          version = "~> 2.70"
        }
      }
      backend "remote" {
        organization = "mycompany"
    
        workspaces {
          prefix = "mycompany-"
        }
      }
    }
    

    在这种情况下,我的工作区是 mycompany-DEV 和 mycompany-PRO

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-07
      • 1970-01-01
      • 2021-11-26
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      • 1970-01-01
      • 2016-08-06
      相关资源
      最近更新 更多