【问题标题】:Why does terraform aws code fail to render?为什么 terraform aws 代码无法渲染?
【发布时间】:2020-02-13 23:47:54
【问题描述】:

Terraform 版本 = 0.12

resource "aws_instance" "bespin-ec2-web" {
  ami = "ami-0bea7fd38fabe821a"
  instance_type = "t2.micro"
  vpc_security_group_ids = [aws_security_group.bespin-sg.id]
  subnet_id = aws_subnet.bespin-subnet-public-a.id
  associate_public_ip_address = true
  tags = {
    Name = "bespin-ec2-web-a"
  }
  user_data = data.template_file.user_data.rendered
}

data "template_file" "user_data" {
template = file("${path.module}/userdata.sh")
}

userdata.sh 文件

 #!/bin/bash
   USERS="bespin"
   GROUP="bespin"
   for i in $USERS; do
   /usr/sbin/adduser ${i};
   /bin/echo ${i}:${i}1! | chpasswd;
   done

   cp -a /etc/ssh/sshd_config /etc/ssh/sshd_config_old
   sed -i 's/PasswordAuthentication no/#PasswordAuthentication no/' /etc/ssh/sshd_config
   sed -i 's/#PasswordAuthentication yes/PasswordAuthentication yes/' /etc/ssh/sshd_config
   systemctl restart sshd

地形规划结果

Error: failed to render : <template_file>:5,24-25: Unknown variable; There is no variable named "i"., and 2 other di
agnostic(s)

  on instance.tf line 13, in data "template_file" "user_data":
  13: data "template_file" "user_data" {

为什么会出现错误?

【问题讨论】:

  • 在你的 userdata.sh 中尝试双倍 $:$${i}

标签: bash amazon-web-services terraform render


【解决方案1】:

template_file 数据源中的 template 参数被处理为 Terraform 模板语法。

在这种语法中,使用${...} 有一个特殊的含义,即... 部分将被传递到模板中的某个变量注入。

Bash 也允许这种语法,用于获取变量的值作为您打算使用它的值。

要协调这一点,您需要转义 $ 字符,以便 terraform 模板编译器保留它,您可以通过将字符加倍来做到这一点:$${i} 在所有情况下。

https://www.terraform.io/docs/configuration/expressions.html#string-templates

【讨论】:

  • 如果你使用 $$ 那么 shell 只能在 terraform 环境中运行。我建议使用eval "$"{i},它将外壳保持为外壳并与 terraform 一起使用。我想知道是否可以选择告诉 terraform 不要解释 shell 脚本。
猜你喜欢
  • 2012-06-03
  • 1970-01-01
  • 1970-01-01
  • 2014-11-26
  • 2020-07-20
  • 1970-01-01
  • 1970-01-01
  • 2013-03-18
  • 2019-02-04
相关资源
最近更新 更多