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

Ansible Azure动态Inventory:解决无法设置ansible_ssh_private_key_file错误

解决Azure动态Inventory中ansible_ssh_private_key_file配置错误

问题场景

已配置Ansible Azure动态Inventory,可通过公网IP获取服务器详情,但在azure-rm.yml中添加ansible_ssh_private_key_file选项时触发模板解析错误。

配置文件(azure-rm.yml)

plugin: azure.azcollection.azure_rm
subscription_id: "1234abc-12ab-1a2b-1a2b-12345abcd"

auth_source: msi
msi_client_id: >
  12345-1234-1234-1234-12345678  # Break long values into new lines

resource_groups:
  - "RG-Dev-001"

filters:
  os_type: "Linux"

compose:
  ansible_host: public_ip_address
  ansible_ssh_private_key_file: "/my/path/.ssh/id_rsa"

错误信息

[WARNING]:  * Failed to parse /etc/ansible/azure_rm.yml with auto plugin: Could not set ansible_ssh_private_key_file for host myvmname_nic: template error while
templating string: unexpected '/'. String: {{/my/path/.ssh/id_rsa}}. unexpected '/'
[WARNING]: Unable to parse /etc/ansible/azure_rm.yml as an inventory source
[WARNING]: No inventory was parsed, only implicit localhost is available

环境详情

$ ansible --version
ansible [core 2.17.9]
python version = 3.10.12
jinja version = 3.0.3

$ ansible-galaxy collection list | grep azure
azure.azcollection 3.3.1
azure.azcollection 2.7.0

错误原因

Ansible的compose字段会将配置值当作Jinja2模板解析,直接写入带斜杠的路径时,Jinja2会误将路径开头的/识别为模板语法的一部分,导致解析失败。

解决方法

方案1:使用Jinja2 Raw语法包裹路径

通过{% raw %}和{% endraw %}标记,让Jinja2跳过对路径字符串的解析:

compose:
  ansible_host: public_ip_address
  ansible_ssh_private_key_file: '{% raw %}/my/path/.ssh/id_rsa{% endraw %}'

方案2:通过变量引用路径

先在group_vars/all.yml(或其他变量文件)中定义密钥路径:

# group_vars/all.yml
ansible_ssh_private_key_file: "/my/path/.ssh/id_rsa"

然后在azure-rm.yml的compose中引用该变量:

compose:
  ansible_host: public_ip_address
  ansible_ssh_private_key_file: "{{ ansible_ssh_private_key_file }}"

额外优化建议

当前环境同时安装了两个版本的azure.azcollection,版本冲突可能引发未知问题,建议清理旧版本:

ansible-galaxy collection remove azure.azcollection:2.7.0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 21:23:10