简体   繁体   中英

Not able to fetch the variable's value defined in a module in Terraform

I am new to terraform... I have created a dev.tfvars file inside a module and declared some variables inside it. I am trying to fetch this value and assign it to another variable in different module. This is not working.

Below is the code snippet..

module "mydemomodule" {
  source = "../modules/dev_env"  // module call
}

resource "aws_instance" "demo" {
    ami = "${module.mydemomodule.AMIS.LINUX_MUMBAI}" // trying to fetch the value 
    region = "${module.mydemomodule.AWS_MUMBAI_REGION}"  // trying to fetch the value 
    instance_type = "${module.mydemomodule.INSTANCE_TYPE}" // trying to fetch the value 
    key_name = "${aws_key_pair.ssshkey.key_name}"
    tags = {
        Name = "${terraform.workspace}_server"
    }
}

dev.tfvars // this file is inside other module
-----------------------------------------------
variable "INSTANCE_TYPE"{
    default = "t2.micro"
}
 
//AWS_REGION      = "us-east-1"
variable "AWS_MUMBAI_REGION"{
    default = "ap-south-1"
}

variable "AWS_SINGAPORE_REGION"{
    default = "us-southeast-1"
}

variable "AMIS" {
     type = map
     default = {
        LINUX_MUMBAI  = "ami-0cca134ec43cf708f"
        UBUNTU_MUMBAI = "ami-07ffb2f4d65357b42"
        LINUX_SGP     = "ami-005835d578c62050d"
        UBUNTU_SGP    = "ami-02045ebddb047018b"
     }
}

Error as below while running terraform plan

Error: Unsupported attribute
│
│   on main.tf line 16, in resource "aws_instance" "demo":
│   16:     ami = "${module.mydemomodule.AMIS.LINUX_MUMBAI}"
│     ├────────────────
│     │ module.mydemomodule is a object
│
│ This object does not have an attribute named "AMIS".
╵
╷
│ Error: Unsupported argument
│
│   on main.tf line 17, in resource "aws_instance" "demo":
│     ├────────────────
│     │ module.mydemomodule is a object
│
│ This object does not have an attribute named "INSTANCE_TYPE".
╵

A variable in a module is scoped to that module and can not be accessed outside of that module. If you need that value in multiple modules, why don't you define it at the top level, and pass it into all the modules that need it?

If you absolutely need to define the values inside a module, then you will need to add an output to that module that outputs the value so that you can access it at the top level.

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