在 Ansible 中,未定义变量错误是常见的问题之一。这种错误通常发生在尝试访问一个未声明或未正确传递的变量时。通过实际演示,我们将展示如何复现这一错误,并逐步排查和修复它。

Ansible 故障排除:未定义变量错误

错误示例

以下是一个包含未定义变量错误的 Ansible Playbook 示例:

---
- name: debug module demo
  hosts: all
  tasks:
    - name: debug message
      ansible.builtin.debug:
        msg: "{{ fruit }}"

错误信息

运行上述 Playbook 时,可能会遇到以下错误:

$ ansible-playbook troubleshooting/undefinedvariable_error.yml

PLAY [file module demo] **************************************************

TASK [Gathering Facts] **************************************************
ok: [demo.example.com]

TASK [debug message] ****************************************************
fatal: [demo.example.com]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'fruit' is undefined\n\nThe error appears to be in '/Users/lberton/prj/github/ansible-pilot/troubleshooting/undefinedvariable_error.yml': line 5, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n  tasks:\n    - name: debug message\n      ^ here\n"}

PLAY RECAP ****************************************************************
demo.example.com           : ok=1    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0

问题原因

  1. 未定义变量:变量 fruit 在 Playbook 中未被定义或未正确传递。
  2. 变量作用域问题:变量可能在其他地方定义,但未在当前任务中可用。

修复方法

  1. 定义变量:在 Playbook 中定义变量,确保变量在任务中可用。
  2. 检查变量传递:确保变量在任务中被正确传递。

修复后的 Playbook 如下所示:

---
- name: debug module demo
  hosts: all
  vars:
    fruit: "apple"
  tasks:
    - name: debug message
      ansible.builtin.debug:
        msg: "{{ fruit }}"

修复步骤

  1. 定义变量:在 Playbook 的 vars 部分定义变量 fruit。
  2. 验证变量传递:确保变量在任务中被正确引用。
  3. 重新运行 Playbook:验证修复是否有效。

验证修复

修复问题后,重新运行 Playbook:

$ ansible-playbook troubleshooting/undefinedvariable_fix.yml

PLAY [debug module demo] **************************************************

TASK [Gathering Facts] ****************************************************
ok: [demo.example.com]

TASK [debug message] ******************************************************
ok: [demo.example.com] => {
    "msg": "apple"
}

PLAY RECAP ****************************************************************
demo.example.com           : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

总结

Ansible 中的未定义变量错误通常是由于以下原因导致的:

  1. 变量未定义:变量未在 Playbook 中声明或未正确传递。
  2. 变量作用域问题:变量未在当前任务的作用域内可用。

通过以下步骤可以有效解决未定义变量错误:

  1. 定义变量:在 Playbook 的 vars 部分定义变量。
  2. 检查变量传递:确保变量在任务中被正确引用。
  3. 重新运行 Playbook:验证修复是否有效。

如果问题仍未解决,可以参考 Ansible 的 官方文档或社区支持获取更多帮助。