Shivani
Shivani

Reputation: 245

How to use if else in yaml?

Below is a snippet of yaml I am using. I want to call yaml say abc.yml if a variable ENV is set to, say 'abc', and xyz.yml if the variable ( passed as a parameter ) is set to 'xyz'. How do I use if condition in the yaml ?

 script:
   - ansible-playbook -i <dir> pqr.yaml --verbose -f 10 -e "ENV=${ENV}.... "
   - ansible-playbook -i <dir> abc.yaml --verbose -f 10 -e "ENV=${ENV}.... "
   - ansible-playbook -i <dir> xyz.yaml --verbose -f 10 -e "ENV=${ENV}.... "
   - ansible-playbook -i <dir> hjk.yaml --verbose -f 10 -e "ENV=${ENV}.... "

Upvotes: 0

Views: 11755

Answers (2)

Shivani
Shivani

Reputation: 245

The following piece of code did the trick:

 script:
- if [[ ${ENV} =~ "abc" ]]; then MODULE="abc"; else MODULE="xyz"; fi
- ansible-playbook -i $CI_PROJECT_DIR/ansible/${HOSTFILE} ${MODULE}_installation.yml --verbose -f 10 -e "ENV=${ENV}...

Upvotes: 1

promicro
promicro

Reputation: 1646

Well you can, using conditions.

The example could be something like below:

  • I used an input parameter as example, any variable will do
  • I separated the scripts in jobs
  • Adding condition will take care of any validation and can therefore skip the job
parameters:

  - name: whatToRunVar
    displayName: 'What should it be: abc or xyz?'
    default: ''
    type: string

jobs:
  - job: pqr
    steps:
    - script: ansible-playbook -i <dir> pqr.yaml --verbose -f 10 -e "ENV=${ENV}.... "

  - job: abc
    steps:
    - script: ansible-playbook -i <dir> abc.yaml --verbose -f 10 -e "ENV=${ENV}.... "
    condition: contains('${{ parameters.whatToRunVar}}', 'abc')

  - job: xyz
    steps:
    - script: ansible-playbook -i <dir> xyz.yaml --verbose -f 10 -e "ENV=${ENV}.... "l
    condition: contains('${{ parameters.whatToRunVar}}', 'xyz')
    
  - job: hjk
    steps:
    - script: ansible-playbook -i <dir> hjk.yaml --verbose -f 10 -e "ENV=${ENV}.... "


Submitting abcde as parameter results in: run with abcde

Upvotes: 1

Related Questions