简体   繁体   English

如何将变量传递/连接到 `aws_instance` 资源中的 `data.aws_ami` 部分

[英]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.我在ami=data.aws_ami.$var.ami_name.id行内连接变量时遇到困难。

I have tried ami= "${data.aws_ami.(var.ami_name).id}" but in both cases I am getting the:我试过ami= "${data.aws_ami.(var.ami_name).id}"但在这两种情况下我都得到:

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 .它仅适用于字符串值data.aws_ami.ubuntu-1804.id

My question is how to concat the variable to the data.aws_ami ?我的问题是如何将变量连接到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.最终目标是根据不同的操作系统 ec2 实例(Suse、Ubuntu、RHEL)进行配置,这一切都取决于部署时提供的变量。

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我正在使用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.您显示的代码: data.aws_ami.$var.ami_name.id它肯定无效。
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.我的方法是在 aws_ami 中使用for_each ,它会给我们一个数组,我们可以稍后在 aws_instance 资源中使用它,您可以向集合中添加更多项目以添加其他操作系统,并且与您可以更改的过滤器相同所有这一切都可以满足您的需求。

As an extra, I added validation to your ami_name variable that way we prevent any issues right before they can cause errors.另外,我为您的ami_name变量添加了验证,这样我们可以在任何问题导致错误之前立即防止它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM