How to delegate Ansible host variables with set_fact

Bernd Malmqvist
Jan 15 · 1 min read

I ran into an interesting issues about making an service account token on OpenShift accessible by another group of nodes when running a playbook. When you run an oc command and register the output, you face the issue that the registered variable is stored under hostvars of the node name.

Normally you can access hostvars from other nodes like you see below:

"{{ hostvars['hostname']['variable-name'] }}"

I came up with something different and more flexible, instead of accessing hostvars[‘hostname’][‘variable-name’] I am delegating the variable to a group of nodes and make the variable more easily accessible there:

---
- hosts: avi-controller:masters
gather_facts: false

pre_tasks:
- block:
- name: Get OpenShift token
command: "oc sa get-token <serveraccount-name> -n <project-name> --config=/etc/origin/master/admin.kubeconfig"
register: token

- name: Set serviceaccount token variable and delegate
set_fact:
serviceaccount_token: "{{ token.stdout }}"
delegate_to: "{{ item }}"
delegate_facts: true
with_items: "{{ groups['avi-controller'] }}"
when: ( inventroy_hostname == groups["masters"][0] )

roles:
- { role: "config", when: "'avi-controller' in group_names" }

In the following Ansible role after pre tasks, you are able to access the variable serviceaccount_token on any member of the group “avi-controller” and use with the rest of your automation code.

If you like this article, please share your feedback and leave a comment.


Originally published at techbloc.net.

Bernd Malmqvist
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade