Best method of storing shell output to variable to use on other hosts?

I’m looking for some tips on the best way to store a variable persistently across all hosts or multiple plays.

I am attempting to create a docker swarm manager using something similar to this:

    • hosts: swarm-init
  1. gather_facts: no
  2. tasks:
    • shell: docker swarm init
    • shell: docker swarm join-token -q manager
  3. register: manager
    • shell: docker swarm join-token -q worker
  4. register: worker

I would run this play once and don’t have that logic built yet but I have not been able to find a method of storing {{ worker }} in a variable so that I could join the swarm from another host in another play. Any advice?

http://docs.ansible.com/ansible/set_fact_module.html

  • name: set fact from hosts output
    set_fact:
    docker_manager: manager.stdout
    docker_worker: worker.stdout

you may want to just pick out a line too, see the debug for what you may want

  • debug:
    var:
  • worker.stdout_lines
  • manager.stdout_lines

Thanks for the tip. I am much closer but I’m getting some undesirable characters added to the var named “key” I’m setting.

I actually got this to work by change key variable to:

  1. key: “{{ hostvars[groups[‘swarm-init’][0]][‘worker’] | replace(‘[u’, ‘’) | replace(‘]’, ‘’)}}”

What a pia! Surely i am doing something early in the play that is causing me to have to replace those characters.

Your worker is a list so maybe something like this
hostvars[groups['swarm-init'][0]]['worker'][0]

I am facing an issue where I need to specify hosts like this

    • hosts: “swarm-init-{{ env }}”

but trying to use that group value in hostvars stanza yields the below error. any suggestions?

  1. mtoken: “{{ hostvars[groups[‘swarm-init-{{ env }}’][0]][‘manager’] | replace(‘[u’, ‘’) | replace(‘]’, ‘’)}}”

{“failed”: true, “msg”: “‘dict object’ has no attribute ‘swarm-init-{{ env }}’”}

hosts: only has access to extra-vars, you cannot get group vars when they depend on the hosts you select in hosts: …

{{ env }} is an extra-vars in this instance

This works just fine when I set_fact for “manager” on the desired host.
1.

  1. mtoken: “{{ hostvars[‘myhost.net’][‘manager’] | replace(‘[u’, ‘’) | replace(‘]’, ‘’)}}”
    but I need to be able to get the name of the single host that is in the group passed with something like this. Perhaps i need to step back and regroup and go about this in a different way. Any tips would be appreciated.

    • hosts: “swarm-init-{{ env }}”

I concede…there is no way to do this without passing an extra var at run time.