为什么 terraform aws 代码无法渲染?

san*_*lee 4 bash render amazon-web-services 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")
}
Run Code Online (Sandbox Code Playgroud)

用户数据.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
Run Code Online (Sandbox Code Playgroud)

地形计划结果

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" {
Run Code Online (Sandbox Code Playgroud)

为什么我收到错误?

Dav*_*tia 7

template数据源中的参数按照template_fileTerraform 模板语法进行处理。

在此语法中,using${...}具有特殊含义,该...部分将由传递到模板中的某些 var 注入。

Bash 还允许使用这种语法,以便在您打算使用变量时获取变量的值。

为了解决这个问题,您需要转义该$字符,以便 terraform 模板编译器保留它,您可以通过$${i}在所有情况下将字符加倍来实现:

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