3

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 Answer 1

3

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?

Sign up to request clarification or add additional context in comments.

6 Comments

hosts kube-master has only one server and kube-minions 3 servers.
So what I want to do this, get the join token from master and execute in on the minions. So this way I think it will be possible, but the problem is, when i execute kubeadm token create --print-join-command it prints the with a warning. So how can I get rid of warning and only prints the join command itself?
You could experiment with filters: docs.ansible.com/ansible/latest/user_guide/… echo "{{ hostvars['master01'].myvar | regex_search('(foo)') }}"
Hi, I tried your above method, but it gives an error in hostvars['master01'].myvar line. I changed this line according to mine, but still it fails
hostvars['thismustbeyourhostname'] <-- this must contain your masters hostname, the name which you used in your inventory
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.