使用Terraform创建VM时,Molecule实例信息传递失败致SSH连接错误
问题描述
我用Terraform创建VM,搭配Molecule测试Ansible Roles。执行molecule create后VM创建成功,实例信息也写入了~/.cache/molecule/<role-name>/<scenario-name>/instance_config.yml,但跑molecule converge时触发SSH连接错误:
fatal: [instance]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: ssh: Could not resolve hostname instance: Name or service not known", "unreachable": true}
查看Molecule生成的~/.cache/molecule/<role-name>/default/inventory,发现ansible_host等字段都是null。请问怎么把Terraform创建的VM信息正确传递到Molecule的inventory里?
解决方案
1. 配置Molecule的Terraform Driver
在Molecule场景配置文件(通常是molecule/default/molecule.yml)中,指定Terraform driver的实例配置模板路径,确保驱动能正确生成实例配置:
driver: name: terraform instance_config_template: templates/instance_config.yml.j2
2. 编写实例配置模板
创建molecule/default/templates/instance_config.yml.j2模板文件,将Terraform输出的VM属性映射到Ansible所需的变量:
--- - name: instance ansible_host: "{{ terraform_outputs.vm_public_ip.value }}" ansible_user: "{{ terraform_outputs.vm_ssh_user.value }}" ansible_ssh_private_key_file: "{{ terraform_outputs.ssh_private_key_path.value }}" ansible_ssh_common_args: "-o StrictHostKeyChecking=no"
同时需要在你的Terraform代码中定义对应的输出变量,让Molecule能读取到这些值:
output "vm_public_ip" { value = aws_instance.test_vm.public_ip # 替换为你的VM资源ID } output "vm_ssh_user" { value = "ubuntu" # 根据你的VM镜像调整用户名 } output "ssh_private_key_path" { value = "./keys/id_rsa" # 替换为你的SSH私钥实际路径 }
3. 验证Terraform输出有效性
执行以下命令,确认Terraform已正确输出VM的关键信息:
terraform output
如果输出为空或缺失字段,检查Terraform代码中的输出定义是否正确。
4. 清理缓存并重新生成配置
如果之前的缓存导致实例信息未更新,先清理缓存再重新运行创建流程:
molecule destroy rm -rf ~/.cache/molecule/<role-name>/default molecule create
5. 检查自定义Inventory模板(可选)
如果你自定义了Molecule的inventory模板,确保模板正确引用了实例配置中的变量。默认模板无需修改,但若使用自定义模板,需包含类似逻辑:
[all] {% for instance in instances %} {{ instance.name }} ansible_host={{ instance.ansible_host }} ansible_user={{ instance.ansible_user }} ansible_ssh_private_key_file={{ instance.ansible_ssh_private_key_file }} {% endfor %}
内容的提问来源于stack exchange,提问作者Vasai

