在下面的攻略中,有人能告诉我最后一条set_fact语句的语法有什么问题吗?如果我显式地指定了主机名R9 (按照第一个set_fact),那么它就可以正常工作。但是,如果我指定一个变量的值为R9,然后在最后的set_fact语句中使用它,我会得到如下所示的错误。啊。
---
- hosts: all
gather_facts: no
vars:
ansible_network_os: ios
ansible_connection: network_cli
tasks:
- ios_command:
commands: show ip arp
register: results
- set_fact:
some_var: "{{ hostvars['R9'].results }}"
- set_fact:
hostname: "R9"
- set_fact:
another_var: "{{ hostvars['{{hostname}}'].results }}"
- debug:
var=some_var
- debug:
var=another_var错误:
fatal: [R7]: FAILED! =>
msg: |-
The task includes an option with an undefined variable. The error was: "hostvars['{{hostname}}']" is undefined
The error appears to be in '/root/ansible/Rapid/testsetfact.yml': line 20, column 6, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
- set_fact:
^ here
fatal: [R9]: FAILED! =>
msg: |-
The task includes an option with an undefined variable. The error was: "hostvars['{{hostname}}']" is undefined
The error appears to be in '/root/ansible/Rapid/testsetfact.yml': line 20, column 6, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
- set_fact:
^ here发布于 2020-09-04 20:27:41
您可以使用inventory_hostname来实现您的目的:
- set_fact:
another_var: "{{ hostvars[inventory_hostname].results }}"https://stackoverflow.com/questions/63740580
复制相似问题