Terraform创建AWS实例保存Windows密码时file函数报错求助
问题原因与解决方案
错误根源
file() 函数会在Terraform的配置加载阶段(早于apply操作)执行,它只能读取随代码一同存在的静态文件。而你通过local_file.ssh_key创建的winserver.pem是在apply阶段才生成的,plan阶段该文件还不存在,所以触发报错。同时Terraform明确限制file()不能读取由资源动态生成的文件,必须直接引用资源的属性值。
修复方案
直接引用生成密钥对的资源属性来获取私钥内容,而非尝试读取本地文件:
场景1:通过tls_private_key生成密钥对
如果你的密钥对是用Terraform的tls_private_key生成并保存到local_file,直接用tls_private_key的private_key_pem属性解密:
# 生成RSA密钥对 resource "tls_private_key" "win_server_key" { algorithm = "RSA" rsa_bits = 2048 } # 保存私钥到本地文件 resource "local_file" "ssh_key" { content = tls_private_key.win_server_key.private_key_pem filename = "winserver.pem" file_permission = "0600" } # 解密Windows密码并保存 resource "local_file" "needed_details" { content = <<EOF Windows服务器管理员密码: ${rsadecrypt(module.ec2_instance.password_data, tls_private_key.win_server_key.private_key_pem)} EOF filename = "win_instance_credentials.txt" # 显式声明依赖,确保执行顺序正确 depends_on = [tls_private_key.win_server_key, module.ec2_instance] }
场景2:直接引用local_file的content属性
如果必须通过local_file的属性获取,也可以直接用local_file.ssh_key.content(该属性存储了写入文件的原始内容):
resource "local_file" "needed_details" { content = <<EOF Windows服务器管理员密码: ${rsadecrypt(module.ec2_instance.password_data, local_file.ssh_key.content)} EOF filename = "win_instance_credentials.txt" depends_on = [local_file.ssh_key, module.ec2_instance] }
关键知识点
tls_private_key资源的private_key_pem属性:直接存储生成的私钥PEM格式字符串,无需读取文件local_file资源的content属性:保存了写入文件的原始内容,可直接引用depends_on:显式声明依赖关系,确保Terraform先创建密钥对和EC2实例,再执行密码解密与保存操作
内容的提问来源于stack exchange,提问作者EBox
相关产品推荐
相关产品推荐

