Home > Software engineering >  Can't access attributes on a primitive-typed value (string) - trying to create an instance in e
Can't access attributes on a primitive-typed value (string) - trying to create an instance in e

Time:07-01

I'm using a VPC module that specifies a list of public subnets (3 to be exact) and I want to deploy an instance in each subnet. Here's my VPC module:

module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "3.12.0"

  name                   = "${var.name}-vpc"
  cidr                   = "10.1.0.0/16"
  azs                    = [var.azs]
  private_subnets        = ["10.1.0.0/19", "10.1.32.0/19", "10.1.64.0/19"]
  public_subnets         = ["10.1.128.0/20", "10.1.144.0/20", "10.1.160.0/20"]
  enable_nat_gateway     = true
  single_nat_gateway     = false
  one_nat_gateway_per_az = false

  enable_dns_hostnames = true

  tags = {
    "kubernetes.io/cluster/${var.cluster_name}" = "shared"
  }

  public_subnet_tags = {
    "kubernetes.io/cluster/${var.cluster_name}" = "shared"
    "kubernetes.io/role/elb"                    = "1"
  }

  private_subnet_tags = {
    "kubernetes.io/cluster/${var.cluster_name}" = "shared"
    "kubernetes.io/role/internal-elb"           = "1"
  }

}

Here's my instance resource block

resource "aws_instance" "bastion" {
  count           = length(var.azs)
  ami             = var.instance_ami
  key_name        = aws_key_pair.bastion_auth.id
  instance_type   = var.instance_type
  security_groups = [aws_security_group.bastion-sg.id]

  associate_public_ip_address = true
  subnet_id                   = module.vpc.public_subnets[count.index].id
  user_data                   = file("userdata.tpl")

  root_block_device {
    volume_size = var.main_vol_size
  }

  tags = {
    Name = "${var.name}-bastion-host-${count.index   1}"
  }
}

How can I get it to deploy an instance in each subnet? I tried using count.index but I'm getting this error

│   on bastion.tf line 9, in resource "aws_instance" "bastion":
│    9:   subnet_id                   = module.vpc.public_subnets[count.index].id
│     ├────────────────
│     │ count.index is 0
│     │ module.vpc.public_subnets is tuple with 3 elements
│
│ Can't access attributes on a primitive-typed value (string).

CodePudding user response:

public_subnets is already a list of IDs. So it should be:

subnet_id                   = module.vpc.public_subnets[count.index]
  • Related