You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform自动扩缩容User_Data未运行及脚本嵌入问题求助

排查Terraform EC2 User Data脚本未执行问题

核心问题:双重Base64编码

你的配置存在关键错误:data "template_file" "test"已设置base64_encode = true,生成的rendered字段本身就是Base64编码后的内容,但在aws_launch_template中又调用base64encode()再次编码,导致Cloud-Init无法解析用户数据,脚本自然不会执行。

修复方式:直接使用已编码的结果作为user_data值,移除重复编码:

resource "aws_launch_template" "terraform-template-app" {
  # 保留其他原有配置
  user_data = data.template_file.test.rendered
}

必须补充Cloud-Init可执行脚本标识

Cloud-Init需要明确标识才能将用户数据识别为可执行脚本,你的脚本缺少必要的shebang头,即使编码正确也可能被忽略。需在脚本开头添加#!/bin/bash,同时优化脚本内的服务管理逻辑(避免service与systemctl混用):

data "template_file" "test" {
  base64_encode = true
  template = <<-EOT
#!/bin/bash
# Define the path to the sshd_config file
sshd_config="/etc/ssh/sshd_config"

# Define the string to be replaced
old_string="PasswordAuthentication no"
new_string="PasswordAuthentication yes"

# Check if the file exists
if [ -e "$sshd_config" ]; then
    # Use sed to replace the old string with the new string
    sudo sed -i "s/$old_string/$new_string/" "$sshd_config"

    # Check if the sed command was successful
    if [ $? -eq 0 ]; then
        echo "String replaced successfully."
        # 统一用systemctl管理服务
        sudo systemctl restart sshd
    else
        echo "Error replacing string in $sshd_config."
    fi
else
    echo "File $sshd_config not found."
fi

# 改用chpasswd兼容更多AMI(部分系统不支持passwd --stdin)
echo "ec2-user:123" | sudo chpasswd
sudo systemctl restart sshd
  EOT
}

额外排查步骤

  • 查看完整Cloud-Init日志:除/var/log/cloud-init-output.log外,/var/log/cloud-init.log会记录用户数据的解析细节,可定位编码错误或格式问题。
  • 验证元数据访问权限:确保实例所在安全组允许出站访问169.254.169.254(Cloud-Init依赖此元数据服务获取用户数据)。
  • 避免明文密码:生产环境请勿硬编码密码,建议使用AWS Secrets Manager等安全方式传递凭证。

内容的提问来源于stack exchange,提问作者newbietostack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 00:22:18