Ansible yaml dictionary reference to sibling eleme

2019-02-18 10:40发布

问题:

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?

回答1:

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



回答2:

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


标签: yaml ansible