Why doesn't this for_each work?

I can’t use the below for foreach TFEcloud gives the below error:

Error: Error creating env variable AWS_ACCESS_KEY_ID: resource not found

on main.tf line 37, in resource “tfe_variable” “awsenv_vars”:
37: resource “tfe_variable” “awsenv_vars” {

Error: Error creating env variable AWS_SECRET_ACCESS_KEY: resource not found

on main.tf line 37, in resource “tfe_variable” “awsenv_vars”:
37: resource “tfe_variable” “awsenv_vars” {

variable "aws_access_key" { default = "blah"}
variable "aws_secret_key" { default = "blah"}

locals {
  env_var = {
    AWS_ACCESS_KEY_ID = "var.aws_access_key"
    AWS_SECRET_ACCESS_KEY = "var.aws_secret_key"
  }
}

resource "tfe_variable" "awsenv_vars" {
  for_each     = local.env_var
  key          = each.key
  value        = each.value
  category     = "env"
  workspace_id = "${var.tfe_org}/net-vpc-dev"
}

I have defined both aws_access_key and aws_secret_key in Terraform cloud on the workspace variables.

Thanks,
Balnazarr

Hi Balnazarr,

Your Terraform configuration looks valid, so I think this is a Terraform Cloud error. There are a couple of reasons you might see “resource not found”:

  • Does your configured organization have a net-vpc-dev workspace? If it’s not there, this would cause the error.
  • If the token you’re using doesn’t have permissions to create variables for the workspace, you’ll again see this “resource not found” error.

Thanks alisdair,

I’ll look into this, yes I have a net-vpc-dev workspace, I’m just not sure if I need to assign the workspace_id value as ${var.tfe_org}/net-vpc-dev, or does it need to be an actual workspaceID instead of name?

Most likely the user token doesn’t have permission to create these TFE resources, do I need to add the particular user to the Org owners, or do I make sure a user is able to create TFEresources in TFE cloud?

Thanks,
Balnazarr

Hi alisdair,

I’ve also figured this out, this is what I needed to use: workspace_id = element(values(data.tfe_workspace_ids.all.ids), count.index) since the data.tfe_workspace_ids.all.ids is a map of strings.

Please mark this thread resolved as well.

Cheers,
Balnazarr