简体   繁体   中英

Cannot replace values in variables.tfvars file with input variables through a python wrapper using module python_terraform

Following are the files I have

  1. Python wrapper
  2. A simple terraform main.tf to spin up a ec2 instance
  3. A variables.tfvars file

PYTHON WRAPPER

from python_terraform import *

variable_a = input()
variable_b = input()
variable_c = input()

tf = Terraform(working_dir='<terraform directory', variables={'variable_a':variable_a, 'variable_b':variable_b, 'variable_c':variable_c})
tf.init()
output = tf.apply(no_color=IsFlagged, refresh=False)
print(output)

main.tf

provider "aws" {
  profile = "default"
  region  = "us-east-1"
}
resource "aws_instance" "example" {
  ami           = "ami-09d19e919d57453f8"
  instance_type = "t2.micro"
  tags = var.tags
}

variables.tfvars

variable "variable_a" {}
variable "variable_b" {}
variable "variable_c" {}

variable "tags" {
    type = map(string)
    default = {
        costcenter = "${var.variable_a}"
        environment = "${var.variable_b}"
        primary_email = "${var.variable_c}"
     }
}

My requirement is to take variable input using python wrapper and then pass the values as tags for aws resources created. But this does not seem to work and each time I get the followoing error

Value for undeclared variable\n\nThe root module does not declare a variable named "variable_a" but a value\nwas found in file "/tmp/tmpqzpbtamy.tfvars.json". To use this value, add a\n"variable" block to the configuration.\n\nUsing a variables file to set an undeclared variable is deprecated and will\nbecome an error in a future release. If you wish to provide certain "global"\nsettings to all configurations in your organization, use TF_VAR_...\nenvironment variables to set these instead.\n\n\nWarning: Value for undeclared variable\n\n

Please can someone help

Your variables.tfvars should be called variables.tf . Also you can't declar variable "tags" which depends on other variables. Instead you should create a local in main.tf :

locals {
  tags = {
      costcenter = var.variable_a
      environment = var.variable_b
      primary_email = var.variable_c
  }
}

resource "aws_instance" "example" {
  ami           = "ami-09d19e919d57453f8"
  instance_type = "t2.micro"
  tags          = local.tags
}

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