2

I have a variable with list of node IP's and its respective Availability Zone.

seed = {
  10.18.13.12 = us-east-1a
  10.18.37.93 = us-east-1b
  10.18.68.147 = us-east-1a
  10.18.21.55 = us-east-1b
}

I will be using this variable in Jinja template but want to filter out the variable based on unique Avalability Zones and get the IP. I want to compare the Avalability Zones to get unique values and have IP from each unique Avalability Zone. For instance I want the output in form of

"10.18.13.12, 10.18.37.93" 

or

"10.18.68.147, 10.18.21.55"

Is this possible to perform such operations of comparing strings and get its respective value in Jinja template? Anything would help. Thanks in advance.

2

Yes, this can be done. The following should do the trick:

"{%- for ip, az in seed.iteritems() %} 
  {%- if 'us-east-1a' in az %}
    {%- if firstloop is not defined %}
    {%- set firstloop = 1 %}
{{- ip }}
    {%- else %}
{{- " " + ip}}
    {%- endif %}    
  {%- endif %}
{%- endfor%}"

To test it with https://cryptic-cliffs-32040.herokuapp.com/, you can use the following JSON:

{
    "seed": {
      "10.18.13.12": "us-east-1a",
      "10.18.37.93": "us-east-1b", 
      "10.18.68.147": "us-east-1a",
      "10.18.21.55": "us-east-1b"
    }
}

You might give the documentation a read if you are going to be doing much jinja templating. I have found it indispensible.

5
  • Thank you for your reply. I am new to Jinja and not able to progress on this challenging task. I tested it out on cryptic-cliffs-32040.herokuapp.com and getting few errors. It would be great if you can help me solve it – Nahush Dec 14 '17 at 21:13
  • @Nahush - Nice tool! I've definitely done things like this before. I'll update my answer in a few min with a working example. – James Shewey Dec 14 '17 at 21:21
  • @Nahush - That should do it. Aside from the typos, I had to account for the fact that variables set in a loop are scoped for the life of the loop, and are thus vars set/modified in the loop are unavailable outside the loop. There is a workaround for this using .append() but it is not available on the Jinja version used in your tool, but the above works. – James Shewey Dec 14 '17 at 22:05
  • Also worth noting: if you needed all IPs for us-east, you would change {%- if 'us-east-1a' in az %} to {%- if 'us-east' in az %} – James Shewey Dec 14 '17 at 22:06
  • that is really great work. I think I am getting IP's from same AZ rather than IP's from unique AZ. I wanted IP's to be one from us-east-1a and one from us-east-1b. – Nahush Dec 14 '17 at 22:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.