1
votes

I am using Terraform v0.12.6. I am using modules to create a VPC,Subnets and EC2 instances.

root.tf 
   vpc.tf
   pub_subnet.tf
   web_server.tf 

vpc.tf and pub_subnet.tf are working fine and displaying the required output. However, I am unable to use the subnet_id from the module pub_subnet.tf as input to my web_server.tf.

The reason being that it is a list and I am getting Inappropriate value for attribute "subnet_id": string required.

Looks like I have to read the terraform.tfstate file.

Here is my present code -

root.tf

    provider "aws" {
      region = "us-east-1"
    }
    data "terraform_remote_state" "public_subnet" {
    backend = "local"
    config = {
      path = "terraform.tfstate"
    }
    }
    module "my_vpc" {
      source = "../modules/vpc_flowlogs"
      vpc_cidr = "10.0.0.0/16"
     # vpc_id  = "${module.my_vpc.vpc_id}"
       }

    module "vpc_igw" {
      source = "../modules/vpc_igw"  
      vpc_id  = "${module.my_vpc.vpc_id}"

    }
    module "public_subnets" {
      source="../modules/pub_subnets"
      vpc_id  = "${module.my_vpc.vpc_id}"
    }

     module "web_servers" {
    source = "../modules/webservers"
    vpc_id  = "${module.my_vpc.vpc_id}"
    subnet_id = 
    "${data.terraform_remote_state.public_subnet.outputs.subnet_id[0]}"
    } 

web_servers.tf

resource "aws_instance" "web-srvs" {
count="${var.instance_count == "0" ? "1" : var.instance_count}"
ami = "ami-035b3c7efe6d061d5"
instance_type = "t2.nano"
key_name="xxx-dev"
subnet_id = "${var.subnet_id}"
vpc_security_group_ids = ["${aws_security_group.pub_sg.id}"]
associate_public_ip_address=true
}

I am trying to use of the two subnet_ids created. I have tried different ways but now running out of ideas. Just as an FYI, my tfstate file is located in the same directory as root.tf

Appreciate any help. OR is this a bug ?

1

1 Answers

0
votes

You're requesting a remote state for no reason. Remote state is for referencing output from other configs. You have modules so you should just change it to reference the module resource, but you are going to have to output the values in the module so you can reference it elsewhere.

subnet_id = 
    "${data.terraform_remote_state.public_subnet.outputs.subnet_id[0]}"
    } 

Should be

subnet_id = 
    "${module.public_subnets.subnet.id}"
    }

In your subnet module, create an output resource.

output "subnet" {
  value = "${aws_subnet.some_subnet.id}"
}