How to delegate Ansible host variables with set_fact

Bernd Malmqvist
1 min readJan 15, 2019

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

Highly versatile Senior technical Lead Engineer, I am a consummate and competent qualified IT Professional specialising in distributed systems