If condition possible in yaml file?

Viewed 132826

I need to add one more name based on if condition. If If variable value from another .yml file is "yes" then add a new name in the list

I've the following code in my yaml file:

JsNames:
 - name: 'jquery.min.js'
 - name: 'script.js'

I need to add more name based on if condition. If variable value from another .yml file is "yes" then add a new name like this:

JsNames:
 - name: 'jquery.min.js'
 - name: 'script.js'
 - name: 'new.js'

is this possible?

Tried the following:

JsNames:
 - name: 'jquery.min.js'
 - name: 'script.js'
 - | # Test multiline yaml support
   if [[ "site.data.settings.requiredjs" == "yes" ]]; then
     name: 'new.js'
   fi

I need to add more name based on if condition. If variable value from another .yml file is "yes" then add a new name like this:

JsNames:
 - name: 'jquery.min.js'
 - name: 'script.js'
 - name: 'new.js'
7 Answers

As a supplement to Vaibhav's response: although yml does not inherently support if statements, some applications that use yml files for instructions may be able to parse if statements included in the yml. GitLab is one notable example. In GitLab's CI/CD, the .gitlab-ci.yml file can be configured to include if statements such as:

job:
  script: "echo Hello, Rules!"
  rules:
    - if: '$CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "master"'
      when: always
    - if: '$VAR =~ /pattern/'
      when: manual
    - when: on_success

This is from https://docs.gitlab.com/ee/ci/yaml/#rules.

For more info, see this answer: https://stackoverflow.com/a/55464100/10792235.

You can't add conditions to a yml file its just a text formatting way, not a language. But still, you can load the yml file into a programming language and can apply if else to it. based on a string.

Try this

vartodefine: "{{ 'value1' if condition else 'value2' }}"

Please try below syntax for condition in Yaml file

JsNames:
 - name: 'jquery.min.js'
 - name: 'script.js'
{{ if eq site.data.settings.requiredjs "yes" }}
 - name: 'new.js'
{{ end }}
{{if .Env.LOCAL_VARIABLE| eq ""}}
    - /^max_wal_senders = 0\s*.*/
{{ else }}
    - /^max_wal_senders = 10\s*.*/
    - /^vacuum_defer_cleanup_age = {{.Env.VACUUM}}\s*.*/
{{ end }}

An elegant option, when having multiple configuration files would be as follows:

application.yml

kafka.bootstrap-servers-nonprod: "nonprod-value"
kafka.bootstrap-servers-prod: "prod-value"
kafka.bootstrap-servers: ${kafka.bootstrap-servers-${env-type}}

application-qa.yml

env-type: "nonprod"
#kafka.bootstrap-servers will have the value: "nonprod-value"

application-prod.yml

env-type: "prod"
#kafka.bootstrap-servers will have the value: "prod-value"

Try this code, the word "item" could be whatever you want:

{% for item in JsNames %}
  {% if name == 'jquery.min.js' %}
    excute your code
  {% elif name == 'script.js' %}
    excute your code
  {% else %}
    excute your code
  {% endif %}
{% else %}
  some error message
{% endfor %}
Related