I have a simple playbook that loads data to different instances based on the DEPLOY_TO
environment variable that is entered from jenkins which has the value dev
and test
. By comparing the {{ lookup('env','DEPLOY_TO') }}
variable with dev
or test
using when
condition
- name: load loadBase files into target mysql dev
shell: mysql -h {{ lookup('env','db_host_dev') }} -u {{ lookup('env','db_user_dev') }} --password={{ lookup('env','db_root_password_dev') }} {{ lookup('env','db_name') }} < /tmp/{{ item | basename }}
with_items: "{{ data.loadBase }}"
no_log: false
when: "{{ lookup('env','DEPLOY_TO') }} == dev"
- name: load loadBase files into target mysql test
shell: mysql -h {{ lookup('env','db_host_test') }} -u {{ lookup('env','db_user_test') }} --password={{ lookup('env','db_root_password_test') }} {{ lookup('env','db_name') }} < /tmp/{{ item | basename }}
with_items: "{{ data.loadBase }}"
no_log: false
when: "{{ lookup('env','DEPLOY_TO') }} == test"
But when running the pipeline to DEPLOY_TO
either dev or test, it fails with the following error
18:34:15 [WARNING]: conditional statements should not include jinja2 templating
18:34:15 delimiters such as {{ }} or {% %}. Found: {{ lookup('env','DEPLOY_TO') }} ==
18:34:15 dev
18:34:15 fatal: [10.0.1.78]: FAILED! => {
18:34:15 "msg": "The conditional check '{{ lookup('env','DEPLOY_TO') }} == dev' failed. The error was: error while evaluating conditional ({{ lookup('env','DEPLOY_TO') }} == dev): 'dev' is undefined\n\nThe error appears to be in '/home/deploy/jenkins/workspace/infrastructure/deploy.yml': line 77, column 11, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - name: load loadBase files into target mysql dev\n ^ here\n"
May I please know what am I doing wrong?
CodePudding user response:
You have two problems, both called out in the error messages. The first is:
conditional statements should not include jinja2 templating
The value of a when
condition is already evaluated in an implicit template context; you don't need (and shouldn't add) {{...}}
markers around (or anywhere inside) the expression. That gets you:
when: "lookup('env','DEPLOY_TO') == dev"
That gets you to the second error:
The error was: error while evaluating conditional ({{ lookup('env','DEPLOY_TO') }} == dev): 'dev' is undefined
You're comparing the result of the lookup
to a variable named dev
. If you meant to compare it to a literal string, you need to quote it (just like in the arguments to lookup
):
when: "lookup('env','DEPLOY_TO') == 'dev'"