Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible yaml dictionary reference to sibling elements

Tags:

yaml

ansible

I'm trying to organize my variable definitions for ansible playbooks.

Example:

a_b: "a b"
a_c: "{{a_b}} c"

Works fine.

Trying to turn this into a dict:

a:
  b: "a b"
  c: "{{a.b}} c"

Sadly, this results in error that a.b is undefined.

Is it technically possible to refer to sibling elements within a dict?

like image 984
ave Avatar asked Dec 29 '15 13:12

ave


2 Answers

This doesn't help with your specific case, but if you simply trying to re-use value of a sibling variable, you can try use YAML anchor/alias to link to the value of the dictionary element you've defined earlier:

a:
  b: &anchor_b "a b"
  c: *anchor_b

This will result in:

a:
  b: "a b"
  c: "a b"

Here's an example where I re-use my tags dictionary to add tags to ec2 instances and also as uniqueness counter to create exact number of ec2 instances with particular set of tags:

create_ec2_instance:
  tags: &tags
    env: "prod"
    role: "database"
    cluster: "backend-db"
    owner: "me"
  count_tag: *tags
like image 196
Sergei Avatar answered Oct 16 '22 17:10

Sergei


You can't reference variables during the "init" variables phase. You can use set_fact to reference {{ a.b }}.

like image 23
chrism Avatar answered Oct 16 '22 17:10

chrism