I am creating some resources via Terraform that look like this:
resource "aws_ecs_task_definition" "xx" {
family = "xx"
network_mode = "awsvpc"
requires_compatibilities = ["FARGATE", "EC2"]
container_definitions = <<TASK_DEFINITION
[
{
"name": "primary",
"image": "xx",
"environment": [
{"PORT": "80", "CONTAINER_CONFIG": var.CONTAINER_CONFIG}}
],
}
]
TASK_DEFINITION
}
I do not want to push the hardocded value of a variable (eg CONTAINER_CONFIG) to Github. I don't run terraform apply locally. Terraform is only applied when code is pushed and Github actions run.
How can I use enviornment variables to ensure that the github actions can use the actual variable value without actually pushing the value?
I already created a Github secret and added it to my to Github action .yml file like this:
- name: Terraform apply
if: steps.plan.outputs.exitcode == 2
run: terraform apply tfplan
env:
TF_VAR_CONTAINER_CONFIG: ${{ secrets.GTM_CONTAINER_CONFIG }}
and put this in my vars.tf file:
variable "CONTAINER_CONFIG" {
type = string
default = var.TF_VAR_CONTAINER_CONFIG
sensitive = true
}
With this setup, I get this error on terraform init:
Error: Variables not allowed
│
│ On variables.tf line 3: Variables may not be used here.
If I remove the following part
default = var.TF_VAR_CONTAINER_CONFIG
I would still get this error:
Error: ECS Task Definition container_definitions is invalid: Error decoding JSON: invalid character 'v' looking for beginning of value
│
│ with aws_ecs_task_definition.xx,
│ on gtm.tf line 53, in resource "aws_ecs_task_definition" "xx":
│ 53: container_definitions = <<TASK_DEFINITION
│ 54: [
│ 55: {
│ 56: "name": "preview",
│ 57: "image": "gcr.io/xxx",
│ 58: "environment": [
│ 59: {"PORT": "80", "CONTAINER_CONFIG": var.CONTAINER_CONFIG}
The environment variable TF_VAR_CONTAINER_CONGIF
will automatically be picked up by Terraform, and used to fill the value of the CONTAINER_CONFIG
variable defined in your Terraform code.
The syntax you are trying to use here is incorrect:
variable "CONTAINER_CONFIG" {
type = string
default = var.TF_VAR_CONTAINER_CONFIG
sensitive = true
}
The syntax is trying to tell Terraform to use another variable as the default value for this variable. That's invalid because you can't have variables reference other variables. What you are actually trying to do is tell Terraform to pull in an Environment variable here, but this isn't the correct syntax for that either.
Just delete the entire default = var.TF_VAR_CONTAINER_CONFIG
line, and you will get past this error.