Terraform outputs 'Error: Variables not allowed' when doing a plan - terraform

I've got a variable declared in my variables.tf like this:
variable "MyAmi" {
type = map(string)
}
but when I do:
terraform plan -var 'MyAmi=xxxx'
I get:
Error: Variables not allowed
on <value for var.MyAmi> line 1:
(source code not available)
Variables may not be used here.
Minimal code example:
test.tf
provider "aws" {
}
# S3
module "my-s3" {
source = "terraform-aws-modules/s3-bucket/aws"
bucket = "${var.MyAmi}-bucket"
}
variables.tf
variable "MyAmi" {
type = map(string)
}
terraform plan -var 'MyAmi=test'
Error: Variables not allowed
on <value for var.MyAmi> line 1:
(source code not available)
Variables may not be used here.
Any suggestions?

This error can also occurs when trying to setup a variable's value from a dynamic resource (e.g: an output from a child module):
variable "some_arn" {
description = "Some description"
default = module.some_module.some_output # <--- Error: Variables not allowed
}
Using locals block instead of the variable will solve this issue:
locals {
some_arn = module.some_module.some_output
}

I had the same error, but in my case I forgot to enclose variable values inside quotes (" ") in my terraform.tfvars file.
This is logged as an issue on the official terraform repository here:
https://github.com/hashicorp/terraform/issues/24391

I see two things that could be causing the error you are seeing. Link to terraform plan documentation.
When running terraform plan, it will automatically load any .tfvars files in the current directory. If your .tfvars file is in another directory you must provide it as a -var-file parameter. You say in your question that your variables are in a file variables.tf which means the terraform plan command will not automatically load that file. FIX: rename variables.tf to variables.tfvars
When using the -var parameter, you should ensure that what you are passing into it will be properly interpreted by HCL. If the variable you are trying to pass in is a map, then it needs to be parse-able as a map.
Instead of terraform plan -var 'MyAmi=xxxx' I would expect something more like terraform plan -var 'MyAmi={"us-east-1":"ami-123", "us-east-2":"ami-456"}'.
See this documentation for more on declaring variables and specifically passing them in via the command line.

I had the same issue, but my problem was the missing quotes around default value of the variable
variable "environment_name" {
description = "Enter Environment name"
default= test
}
This is how I resolved this issues,
variable "environment_name" {
description = "Enter Environment name"
default= "test"
}

Check the terraform version.
I had something similar , the module was written on version 1.0 and I was using terraform version 0.12.

I had this error on Terraform when trying to pass a list into the module including my Data source:
The given value is not suitable for module. ...
In my case I was passing the wrong thing to the module:
security_groups_allow_to_msk_on_port_2181 = concat(var.security_groups_allow_to_msk_2181, [data.aws_security_group.client-vpn-sg])
It expected the id only and not the whole object. So instead this worked for me:
security_groups_allow_to_msk_on_port_2181 = concat(var.security_groups_allow_to_msk_2181, [data.aws_security_group.client-vpn-sg.id])
Also be sure what type of object you are receiving: is it a list? watch out for the types. I had the same error message when the first argument was also enclosed in [] (brackets), since it already was a list.

Related

Terraform variable from gitlab CI/CD variables

I understand that CI/CD variables can be used in HCL by counting on the fact that having them declared them with a TF_VAR_ prefix in the environment will enable me to look them up as input variables, then use them in the .tf file where I need them.
I did:
set my variable via the UI in the GitLab project, as TF_VAR_ibm_api_key, then masked it.
write a variable block for it in main.tf
call it where I need it in the same file main.tf
tried including the variable in variables.tf, same result
read the documentation from gitlab and from terraform, but I'm not getting this right.
This is my main.tf file:
variable ibm_api_key {
}
terraform {
required_version = ">= 0.13"
required_providers {
ibm = {
source = "IBM-Cloud/ibm"
}
}
}
provider "ibm" {
ibmcloud_api_key = var.ibm_api_key
}
Expected behavior: the variable is passed from the CI/CD and added to the HCL code.
Current behavior: during ´plan´, the job falls with error code 1
$ terraform plan
var.ibm_api_key
Enter a value: ╷
│ Error: No value for required variable
│
│ on main.tf line 1:
│ 1: variable ibm_api_key {
│
│ The root module input variable "ibm_api_key" is not set, and has no default
│ value. Use a -var or -var-file command line argument to provide a value for
│ this variable.
╵
although logically it can't seem to be the issue, I tried formatting the variable call as string interpolation, like:
provider "ibm" {
ibmcloud_api_key = "${var.ibm_api_key}"
}
naturally to no avail.
although logically it can't seem to be the issue, I tried defining a type for the variable:
variable ibm_api_key {
type = string
}
naturally to no avail.
In order to check if variables are passed from the CI/CD settings to the gitlab runner's environment, I added a variable that is neither protected nor masked, and assigned string inserted a double check:
echo ${output_check}
echo ${TF_VAR_ibm_api_key}
which does not result in an error, but are not being printed either. Only the "echo" commands appear in the output.
$ echo ${output_check}
$ echo ${TF_VAR_ibm_api_key}
Cleaning up project directory and file based variables 00:01
Job succeeded
Providers typically have intrinsic environment variables configured in their schema and/or associated bindings for authentication. This situation is, according to the provider authentication documentation, no different. You can authenticate the provider with an IBM API key from the GitlabCI project environment variables settings with:
IAAS_CLASSIC_API_KEY="iaas_classic_api_key"
The error was in the CI/CD settings.
The variables were set to be exclusively passed to protected branches. I was pushing my code to an unprotected one, which prevented variables being passed. When merging the code to a protected branch, the variables showed up correctly. Variables are also correctly imported to Terraform, with the expected exclusion of the TF_VAR_ prefix.
TL;DR If you're having this issue in GitLab's CI/CD check your CICD variables' setting for protected branches, and if the branch you're pushing to corresponds to that setting.

Unknown token IDENT aws_region

I have just run Terraform upgrade. My code was updated but now it shows some errors. The first was:
variable "s3_bucket_name" {
type = list(string)
default = [
"some_bucket_name",
"other_bucket_name",
...
]
}
It doesn't like list(string). I went back to square one and redid the entire Getting Started tutorial. It said that I could either explicitly state type = list or I could implicitly state it by leaving out type and just using the [square brackets].
I saw here: unknown token IDENT list error for IP address variable that I could use "list" (quotes) but I can't find any information on list(string).
So I commented out my list(string) which moved the error along to the next part.
provider "aws" {
region = var.aws_region
}
The tutorial indicates that this is the correct way to create a region tag (there's actually part of the tutorial with that exact code).
Can anyone help me to understand what Unknown token IDENT means as it's throughout my code but it's not helping me to understand what I should do to fix it.
This error appears when you execute terraform 0.12upgrade and your code syntax is already in Terraform 0.12x or obviously a mix of syntax versions <= 0.11x and 0.12x. Also the Unknown token IDENT error can happen when your installed version on your local machine (or in the remote CI/CD server) is 0.11x and your code syntax is on 0.12x and you run a terraform command such as terraform init
variable "var1" {
type = "list"
...
}
This a Terraform 0.11x syntax the alternative 12x is type = list(string)
To reproduce your error, I have a Terraform code 0.12x, I executed terraform 0.12upgrade then the unknown token: IDENT showed up!
In sum, I thought that your first code iteration is already in the correct syntax so there’s no need to upgrade.
To avoid this kind of errors you can add a new version.tf file in your code with this content:
terraform {
required_version = ">= 0.12"
}
Upgrading tips:
Don’t mix the syntaxes in the same Terraform code, if so, downgrade manually your code to 0.11x
Put all your Terraform code syntax in 0.11x
Then run: terraform 0.12upgrade

Terraform unquoted resource for Terraform 0.11

I am using terraform 0.11 for a custom module implementation of terraform-aws-provider. Inside the module there are a lot of unquoted resource value assignments that make me confused since they are not working.
This is the sample module code that I am using
resource "aws_iam_policy" "example" {
name = example_policy
policy = data.aws_iam_policy_document.example.json
}
In the official terraform documentation, it was given with interpolation around the value to become
resource "aws_iam_policy" "example" {
name = "example_policy"
policy = "${data.aws_iam_policy_document.example.json}"
}
from: https://www.terraform.io/docs/providers/aws/d/iam_policy_document.html
When I tried to do terraform get the following error message came up: Unknown token: 39:24 IDENT data.aws_iam_policy_document.example.json, and when I tried to use terraform 0.12, it managed to fetch it correctly.
Is this unquoted resource value exclusive to terraform > v0.12?
Yes. Terraform 0.11 requires that all references look like string interpolations (like your second example). Terraform 0.12 added support for first-class expressions which let you reference variables outside of strings (like your first example).
The docs also include an example of the newer, cleaner syntax:
# Old 0.11 example
tags = "${merge(map("Name", "example"), var.common_tags)}"
# Updated 0.12 example
tags = merge({ Name = "example" }, var.common_tags)

terraform error message line numbers

Is there any way to get the line number causing terraform errors? For example:
$ terraform plan
module root: module foo: bar is not a valid parameter
$
Ideally the error message would give me file paths and line numbers corresponding to the error, e.g.
$ terraform plan
File "maint.tf", line 120:
bar = "123"
InvalidParameterError: "bar" is not a valid parameter of module foo
$
I understand not being a procedural language may make this more difficult but not containing a single file path nor line number seems excessive.
Unfortunately, no, there isn't currently a way to make terraform output the error file or line location
This is a known usability issue with terraform, and the maintainers are updating error messages on a case-by-case basis. (see https://github.com/hashicorp/terraform/issues/1758).
Per mitchellh, "error messages are improving," but for now it seems that humans will have to find the errors.
Due to how terraform state is managed, there aren't always line numbers for an error to map to. Syntactical errors should result in a line number, but there are some scenarios where you'll error because of the terraform state (on disk, on in s3, etc).
For example, the following is a valid main.tf file:
terraform { }
So running terraform apply on the above should work right? Yes, unless the terraform state is tracking a resource which still requires a provider.
Let's say your terraform state matches the following main.tf file.
terraform {
required_providers {
foo_provider { ..source and version }
}
}
provider "foo_provider" {
domain = "this is be a required field"
}
resource "foo_resource" {
name = "bar"
}
If you remove everything foo*, the terraform state is still tracking the the foo_resoruce, so you can't just run terraform apply against an empty main.tf file.
Let's say you do anyway. Run terraform apply against the empty main.tf
terraform { }
You will probably get an error like the following The argument "domain" is required, but was not set. ..and there will be no line number! The error can be super generic and have no mention of the resource or provider causing it. It comes from your terraform tracked state, not syntax. You have to remove the resource from terraform's tracked state before removing the provider (and it's required arguments).

Referring to resources named with variables in Terraform

I'm trying to create a module in Terraform that can be instantiated multiple times with different variable inputs. Within the module, how do I reference resources when their names depend on an input variable? I'm trying to do it via the bracket syntax ("${aws_ecs_task_definition[var.name].arn}") but I just guessed at that.
(Caveat: I might be going about this in completely the wrong way)
Here's my module's (simplified) main.tf file:
variable "name" {}
resource "aws_ecs_service" "${var.name}" {
name = "${var.name}_service"
cluster = ""
task_definition = "${aws_ecs_task_definition[var.name].arn}"
desired_count = 1
}
resource "aws_ecs_task_definition" "${var.name}" {
family = "ecs-family-${var.name}"
container_definitions = "${template_file[var.name].rendered}"
}
resource "template_file" "${var.name}_task" {
template = "${file("task-definition.json")}"
vars {
name = "${var.name}"
}
}
I'm getting the following error:
Error loading Terraform: Error downloading modules: module foo: Error loading .terraform/modules/af13a92c4edda294822b341862422ba5/main.tf: Error reading config for aws_ecs_service[${var.name}]: parse error: syntax error
I was fundamentally misunderstanding how modules worked.
Terraform does not support interpolation in resource names (see the relevant issues), but that doesn't matter in my case, because the resources of each instance of a module are in the instance's namespace. I was worried about resource names colliding, but the module system already handles that.
The picture below shows what is going on.
The terraform documentation does not make their use of "NAME" clear versus the "name" values that are used for the actual resources created by the infrastructure vender (like, AWS or Google Cloud).
Additionally, it isn't always "name=, but sometimes, say, "endpoint= or even "resource_group_name= or whatever.
And there are a couple of ways to generate multiple "name" values -- using count, variables, etc., or inside tfvar files and running terraform apply -var-file=foo.tfvars

Resources