How to assign an ansible variable which is avaiable across tasks

ansible

New to ansible – I'm trying to set the PS1 variable in /etc/bash.bashrc based on the condition of the host's IP address. But I am having trouble with the ps1 variable being available across tassks. I don't know if this is a scope issue (as far as I can tell from this link) or if I should really have two separate playbooks basically doing the same thing (one for LAN hosts, one for WIFI hosts). When I run this playbook I get:

The task includes an option with an undefined variable. The error: 'dict object' has no attribute 'stdout'\n\n

Is there a way to define the ps1 variable so I can assign it inside a task and have it available to other tasks?

---
- hosts: all
  tasks:
    - name: generate LAN host bash prompt
      when: ansible_default_ipv4.address is match("192.168.16")
      connection: local
      shell : /usr/local/bin/psgen -l
      register: ps1
    - debug: var=ps1.stdout

    - name: generate WIFI host bash prompt
      when: ansible_default_ipv4.address is match("172.10.1")
      connection: local
      shell : /usr/local/bin/psgen -w
      register: ps1

    - name: write PS1 to remote /etc/bash.bashrc
      lineinfile:
        dest: /etc/bash.bashrc
        line: "{{ ps1.stdout }}"
        regexp: "PS1="
        insertafter: EOF

Best Answer

If I were going to do this, I wouldn't add tasks. Instead I would remove one, making your task into a loop. When you loop over something all the results will then be stored in a list. You can then use various jinja expressions to extract the successful result from the list.

---
- hosts: all
  tasks:
  - name: generate host bash prompt
    when: ansible_default_ipv4.address is match(item.net_match)
    connection: local
    shell : "{{item.shell}}"
    register: ps1
    loop:
    - name: LAN
      shell: /usr/local/bin/psgen -l
      net_match: 192.168.16
    - name: WAN
      shell: /usr/local/bin/psgen -w
      net_match: 172.10.1

  - debug:
      msg: "ps1"
  - debug:
      msg: "{{ (ps1.results | selectattr('rc', 'defined') | list)[0].stdout }}"

  - name: write PS1 to remote /etc/bash.bashrc
    lineinfile:
      dest: /etc/bash.bashrc
      line: "{{ (ps1.results | selectattr('rc', 'defined') | list)[0].stdout }}"
      regexp: "PS1="
      insertafter: EOF