-1

I have a YAML configuration file and there are multiple keys that need to be assigned with the same value, so I was trying to figure out a way to do so but nothing seems to be working.

Below is my YAML configuration:

maskingSchema:
  "ROOT_RESOURCE_GET":
    fields:
      - username
      - email
    defaultPattern: "*****"
  "ROOT_RESOURCE_CREATE":
    fields:
      - username
      - email
    defaultPattern: "*****"
  "ROOT_RESOURCE_UPDATE":
    fields:
      - username
      - email
    defaultPattern: "*****"

As we see, multiple keys have repetitive values, so I want a way to define a variable with the value and use it on multiple keys are at once.

I tried to extract a variable in the following manner.

myValue:
  fields:
    - username
    - email

And use it like:

maskingSchema:
  [ROOT_RESOURCE_GET,ROOT_RESOURCE_CREATE,ROOT_RESOURCE_UPDATE]: ${myValue}
  

This is a valid YAML syntax, but it doesn't get resolved at runtime.

I also tried the following: Declared the variable in the following manner:

myValue: &myVar
  fields:
    - username
    - email

And used it like:

maskingSchema:
  [ROOT_RESOURCE_GET,ROOT_RESOURCE_CREATE,ROOT_RESOURCE_UPDATE]: *myVar

However, this doesn't work either. I've tried a few other methods but nothing seems to work. I'm lost at this point, would appreciate some help.

  • Does this answer your question? [Use placeholders in YAML](https://stackoverflow.com/questions/41620674/use-placeholders-in-yaml) – blhsing May 15 '23 at 09:46

1 Answers1

0

YAML is not a programming language and does not have variables.

However, it is able to name a subgraph via an anchor and later reference that subgraph with an alias. It looks like this:

maskingSchema:
  "ROOT_RESOURCE_GET": &config
    fields:
      - username
      - email
    defaultPattern: "*****"
  "ROOT_RESOURCE_CREATE": *config
  "ROOT_RESOURCE_UPDATE": *config

If defaultPattern differs, you'll need to do

maskingSchema:
  "ROOT_RESOURCE_GET":
    fields: &config
      - username
      - email
    defaultPattern: "*****"
  "ROOT_RESOURCE_CREATE":
    fields: *config
    defaultPattern: "*****"
  "ROOT_RESOURCE_UPDATE":
    fields: *config
    defaultPattern: "*****"

If you want to do anything more sophisticated, you'll need to use some kind of templating engine which is what most YAML power users (Ansible, Helm, SaltStack, …) do.

flyx
  • 35,506
  • 7
  • 89
  • 126