简体   繁体   中英

How to pass/concat variable into the `data.aws_ami` section in the `aws_instance` resource

I am having difficulties with concating variable inside the ami=data.aws_ami.$var.ami_name.id line.

I have tried ami= "${data.aws_ami.(var.ami_name).id}" but in both cases I am getting the:

79:   ami = data.aws_ami.(var.ami_name)).id
│ 
│ An attribute name is required after a dot.

It only works with the string value data.aws_ami.ubuntu-1804.id .

My question is how to concat the variable to the data.aws_ami ?

The end goal is to provision based on different OS ec2 instances (Suse,Ubuntu,RHEL) All depending on the variable provided when deploying it.

variable "ami_name" {
  default = "ubuntu-1804"
}

resource "aws_instance" "linux" {
  key_name = var.ami_key_pair_name
  #ami           = var.ami_id
  ami            = data.aws_ami.$var.ami_name.id
  #ami           = data.aws_ami.ubuntu-1804.id
  instance_type = "t2.micro"
tags = {
    Name = var.instance_name
  }
  vpc_security_group_ids = [
    aws_security_group.allow-ssh-http.id
  ]
}

I did the search but could not find anything related. I am using Terraform v0.15.4

Here is a possibility for what you are asking:

variable "ami_name" {
  type    = string
  default = "ubuntu"

  validation {
    condition     = can(regex("suse|ubuntu|RHEL", var.ami_name))
    error_message = "Invalid ami name, allowed_values = [suse, ubuntu, RHEL]."
  }
}

data "aws_ami" "os" {
  for_each = toset(["suse", "ubuntu", "RHEL"])

  most_recent = true
  owners      = ["amazon"]

  filter {
    name   = "name"
    values = ["*${each.value}*"]
  }
}

resource "aws_instance" "linux" {
  ami           = data.aws_ami.os[var.ami_name].id
  instance_type = "t2.micro"
  ...
}

the code you show: data.aws_ami.$var.ami_name.id it certainly not valid.
My approach here is to use a for_each in the aws_ami, that will give us an array, we can consume that later in the aws_instance resource, you can add more items to the set to add other operating systems and same with the filters you can change all that to suit your needs.

As an extra, I added validation to your ami_name variable that way we prevent any issues right before they can cause errors.

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