ave
ave

Reputation: 19523

Ansible yaml dictionary reference to sibling elements

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?

Upvotes: 7

Views: 5535

Answers (2)

Sergei
Sergei

Reputation: 2130

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

Upvotes: 6

chrism
chrism

Reputation: 1661

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

Upvotes: 2

Related Questions