ansible - "when" condition not working with logical "AND" operator
Your second condition appears to be a string. I mean the whole condition. A string always is true.
"'Applying auth.0001_initial... OK' in django_migration_result.stdout"
In your last code block, the whole condition is in quotes. That would be a string on the yaml level and the reason why it then works.
This:
key: value
is the same as:
key: "value"
Writing your condition like this should do the trick:
when: django_migration_result|changed and ('Applying auth.0001_initial... OK' in django_migration_result.stdout)
Or even better:
when:
- django_migration_result | changed
- 'Applying auth.0001_initial... OK' in django_migration_result.stdout
Jahan Balasubramaniam
Updated on June 04, 2022Comments
-
Jahan Balasubramaniam almost 2 years
I am trying to write ansible playbooks for dev and test env provisioning for a django app. However there seems to be a problem in using when conditional in the ansible tasks.
In below code the Task 2 is executed when ever the Task 1 is changed. It doesn't check for the second condition.
- name: Task 1 become: yes command: docker-compose run --rm web python manage.py migrate chdir="{{ server_code_path }}" when: perform_migration register: django_migration_result changed_when: "'No migrations to apply.' not in django_migration_result.stdout" tags: - start_service - django_manage - name: Task 2 # Django Create Super user on 1st migration become: yes command: docker-compose run --rm web python manage.py loaddata create_super_user_data.yaml chdir="{{ server_code_path }}" when: django_migration_result|changed and ("'Applying auth.0001_initial... OK' in django_migration_result.stdout") ignore_errors: yes tags: - start_service - django_manage
Task 2 is run whenever Task1 is changed without evaluating second conditional
"'Applying auth.0001_initial... OK' in django_migration_result.stdout"
When I try without
django_migration_result|changed
it is working as intended.- name: Task 2 # Django Create Super user on 1st migration become: yes command: docker-compose run --rm web python manage.py loaddata create_super_user_data.yaml chdir="{{ server_code_path }}" when: "'Applying auth.0001_initial... OK' in django_migration_result.stdout"
The above is working as intended. I tried replacing it with boolean var, even still no luck.
Ansible version: 2.0.0.1
Any ideas, kindly help.