1

What is the correct way of going about doing this: I have a task with the shell module that exports a var from the Bash shell.

Can I access said var from another task (maybe setting environment?) without having to register command output and parse shellvar_register.stdout? Does Ansible scope an ansible_env for localhost and remote host?

---

- 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

2 Answers2

1

c.f. https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#registering-variables

Your shell exits when the task is over. Just capture the value as an ansible value for later uses.

  - name: set a var
    command: 'echo foo'
    register: not_a_shell_var

  - name: show it
    debug:
      msg: "{{ not_a_shell_var.stdout }}"
Paul Hodges
  • 13,382
  • 1
  • 17
  • 36
1

you could use set_fact like in Ansible: Store command's stdout in new variable? and set a new ansible variable, which you can use in other plays too.

- 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"

The first task sets the ansible_variable. The second task takes this variable for shellvar, so the bashscript can use shellvar.

Oliver Gaida
  • 1,722
  • 7
  • 14