0

I am new to ansible and cant seem to figure this out. I have a playbook that configures a bunch of kubernetes objects. The hosts value should be interpolated dynamically. Ansible doesn't permit nesting of variables so I am not sure how to get this to work. **live: **"{{ k8s-{{cluster}} -{{ datacenter }} or lookup('live_node', server)}}"****

Any suggestions will be greatly appreciated.

- hosts: "{{ Live }}"
  max_fail_percentage: 1
  gather_facts: no
  vars:
    live: **"{{ k8s-{{cluster}} -{{ datacenter }} or lookup('live_node', server)}}"**
  tasks:
    - block:
        - include: kubernetes_tasks/k8s.yaml
sdhir
  • 41
  • 7
  • Really need some examples of what you're expecting. Should there really be a space before `-{{ datacenter }}`? (Don't think the `or` stuff will work, either. – Jack Mar 05 '20 at 22:31

1 Answers1

1

You have made a common error when dealing with jinja2: everything inside the mustaches is (plus or minus) a python expression; so don't try to do more templating, just reference the variable or expression like you would in a print statement:

vars:
  live: "{{ ('k8s-' + cluster + '-' + datacenter) or lookup('live_node', server) }}"

Now, because you were so imprecise with your question, that's not strictly speaking accurate since the left-hand side will always be truthy, and thus the lookup will never run, but if you do what Jack said and update with some examples, we can help you with a more syntatically accurate answer

mdaniel
  • 31,240
  • 5
  • 55
  • 58
  • 1
    Thank you so much Jack and mdaniel. I do apologize for a rather vague question. However, your guidance has given me exactly what I needed. I was looking for a way to interpolate variables within a variable. you both were absoluitely right that the "or" logic was never running because the first part of the equation was always true. This is what I ended up doing. live: "{{ lookup('live_node', server) if (server is defined and server|length != 0) else ('k8s-' + cluster + '-' + datacenter) }}". Thank you once again! – sdhir Mar 06 '20 at 17:29