我正在尝试在一个角色中注册一个变量,然后在另一个角色中使用它。
以下是我正在使用的不同文件:
playbook.yml
---
- hosts: hostsgroup1
[...]
roles:
- role1
- hosts: 127.0.0.1
connection: local
roles:
- role2
role1/tasks/main.yml
- name: Example 1
[...]
- name: Example 2
shell:
qm agent {{ VM_id }} network-get-interfaces |grep ip-address |grep '172.20' |grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])'
register: var_role1
role2/tasks/main.yml
- name: Adding server to bastion
ansible.builtin.debug:
msg : Test {{ var_role1.stdout }}
供参考,qm agent 命令给了我一个 IP 地址,我想在第二个角色中使用它。但显然,现在当我执行 playbook 时它会显示一个错误:
fatal: [127.0.0.1]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: \"hostvars['proxmoxhosts']\" is undefined\n\nThe error appears to be in '/root/ansible/roles/bastion_add/tasks/main.yml': line 3, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n# tasks file for bastion_add\n- name: Adding server to bastion\n ^ here\n"}
总而言之,我想在角色2中使用在角色1中注册的var_role1。
答案1
set_fact
应该可以解决问题。
- name: Example 2
shell:
qm agent {{ VM_id }} network-get-interfaces |grep ip-address |grep '172.20' |grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])'
register: var_role1
- set_fact:
var_role1: "{{ var_role1.stdout }}"