How to set shell output to a variable in ansible

Viewed 2155

I need to get a shell output to a variable in set_fact in ansible. And this variable is referred in the somewhere in the same playbook but targeting a different set of hosts

But I am not sure how to do that.

This is my playbook:

---
- hosts: kube-master
  tasks:
    - name: Print the value
      become: true
      shell: |
        echo "hi"
      set_fact:
        banuka: <value-taken-from-above-shell-command>

- hosts: kube-minions
  tasks:
    - name: Print the variable
      become: true
      shell: |
        echo {{banuka}}

But I don't know these:

1. How to get the shell command output to the variable in set_fact and refer it somewhere

2. Is it possible to have multiple hosts (as shown in the above playbook)

1 Answers

I would do it the following way:

---
- hosts: master01
  tasks:
  - name: Print the value
    shell: |
      echo "hi"
    register: somevariablename
  - name: set fact
    set_fact:
      myvar: "{{ somevariablename.stdout }}"

- hosts: kube-minions
  tasks:
  - name: Print the variable
    shell: |
      echo "{{ hostvars['master01'].myvar }}"

It's important to understand, that set_fact only set a variable on the host which it's executed. Since you have a group kube-master it could be executed on each. I had the same issue in a playbook with Kubernetes-Masters and i used one of them as a "primary" e.q. master01. Then the echo hi will only be executed on that one.

In the second hostgroup, you must refer to the hostvars of your kube-master host like the master01.

Do you have the need to run over all the hosts in the group kube-master?

Related