在 Terraform 中使用 `execute` 插值声明一个变量 [英] declare a variable using `execute` Interpolation in Terraform

查看:25
本文介绍了在 Terraform 中使用 `execute` 插值声明一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个变量的子字符串声明为另一个变量.我测试了使用 terraform 控制台获取子字符串.

I want to declare a a sub-string of a variable to another variable. I tested taking a sub-string using terraform console.

> echo 'element(split (".", "10.250.3.0/24"), 2)' | terraform console
> 3

我的子网是 10.250.3.0/24,我希望我的虚拟机在这个子网掩码 10.250.3.6 内获得私有 IP 地址.我希望通过查看子网地址来自动分配它.我试过的;

my subnet is 10.250.3.0/24 and I want my virtual machine to get private IP address within this subnet mask 10.250.3.6. I want this to get automatically assign by looking at subnet address. What I've tried;

test.tf

variable subnet {
  type = "string"
  default = "10.250.3.0/24"
  description = "subnet mask myTestVM will live"
}

variable myTestVM_subnet {
  type = "string"
  default = "10.250." ${element(split(".", var.trusted_zone_onpremises_subnet), 2)} ".6"
}

然后我测试它

terraform console
>Failed to load root config module: Error parsing /home/anum/test/test.tf: At 9:25: illegal char

我猜这只是简单的语法问题.但不知道是什么!

I guess its just simple syntax issue. but couldn't figure out what!

推荐答案

如您所见,您无法在 Terraform 中插入变量的值.

As you've seen, you can't interpolate the values of variables in Terraform.

但是,您可以插入 locals 并根据需要使用它们避免在任何地方重复自己.

You can, however, interpolate locals instead and use those if you want to avoid repeating yourself anywhere.

所以你可以这样做:

variable "subnet" {
  type = "string"
  default = "10.250.3.0/24"
  description = "subnet mask myTestVM will live"
}

locals {
  myTestVM_subnet = "10.250.${element(split(".", var.trusted_zone_onpremises_subnet), 2)}.6"
}

resource "aws_instance" "instance" {
  ...
  private_ip = "${local.myTestVM_subnet}"
}

aws_instance 仅用于演示,可以是任何需要/获取 IP 地址的资源.

Where the aws_instance is just for demonstration and could be any resource that requires/takes an IP address.

尽管您可以使用 cidrhost 函数生成给定子网中的主机地址.

As a better option in this specific use case though you could use the cidrhost function to generate the host address in a given subnet.

所以在你的情况下,你会得到这样的东西:

So in your case you would instead have something like this:

resource "aws_instance" "instance" {
  ...
  private_ip = "${cidrhost(var.subnet, 6)}"
}

这将创建一个私有 IP 地址为 10.250.3.6 的 AWS 实例.然后,这可以更容易地创建整个系列的机器,这些机器使用 count 元参数增加使用的 IP 地址.

Which would create an AWS instance with a private IP address of 10.250.3.6. This can then make it much easier to create a whole series of machines that increment the IP address used by using the count meta parameter.

这篇关于在 Terraform 中使用 `execute` 插值声明一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆