执行此操作的正确方法是什么:我有一个shell模块的任务,它从Bash shell导出var。
我是否可以从另一个任务(可能是设置环境?)访问所述var而无需注册命令输出并解析shellvar_register.stdout? Ansible的范围是localhost和远程主机的ansible_env吗?
---
- name: test var play
hosts: localhost
tasks:
- name: export shell var
become: no
local_action: shell export shellvar=foo
args:
executable: /bin/bash
#register: shellvar_register
- name: print debug msg
local_action:
module: debug
msg: "{{ ansible_env.shellvar }}"
% ansible-playbook playbooks/test/test_shellvar.yml
PLAY [test var play] ***
TASK [Gathering Facts] ***
ok: [localhost]
TASK [export shell var] ***
changed: [localhost -> localhost]
TASK [print debug msg] ***
fatal: [localhost]: FAILED! => {"msg": "The task includes an option
with an undefined variable. The error was: 'dict object' has no
attribute
'shellvar'\n\nThe error appears to be in '/home/robert/tmp/common.git
/playbooks/test/test_shellvar.yml': line 12, column 5, but may\nbe
elsewhere in the file depending on the exact syntax problem.\n\nThe
offending line appears to be:\n\n\n - name: print debug msg\n ^
here\n"}
to retry, use: --limit @/home/robert/tmp/common.git/playbooks
/test/test_shellvar.retry
PLAY RECAP ***
localhost: ok=2 changed=1 unreachable=0 failed=1 skipped=0
C.F. https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#registering-variables
任务结束后,shell将退出。只需将值作为ansible值捕获以供以后使用。
- name: set a var
command: 'echo foo'
register: not_a_shell_var
- name: show it
debug:
msg: "{{ not_a_shell_var.stdout }}"
您可以在Ansible: Store command's stdout in new variable?中使用set_fact并设置一个新的ansible变量,您也可以在其他游戏中使用它。
- hosts: loc
tasks:
- name: set a ansible variable for later use
set_fact:
new_ansible_var: "foo"
- name: run a command with this var
shell: "shellvar={{ new_ansible_var }} {{ playbook_dir }}/bash_script_using_shellvar.sh"
第一个任务设置ansible_variable。第二个任务将此变量用于shellvar,因此bashscript可以使用shellvar。