【问题标题】:ansible - "when" condition not working with logical "AND" operatoransible - “when”条件不适用于逻辑“AND”运算符
【发布时间】:2016-01-19 02:25:58
【问题描述】:

我正在尝试为 django 应用程序的开发和测试环境配置编写 ansible 剧本。但是,在 ansible 任务中使用 when 条件似乎存在问题。

在下面的代码中,任务 2 会在任务 1 更改时执行。它不检查第二个条件。

- 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

只要 Task1 更改而不评估第二个条件,任务 2 就会运行

"'Applying auth.0001_initial... OK' in django_migration_result.stdout"

当我尝试不使用 django_migration_result|changed 时,它按预期工作。

- 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"

以上内容按预期工作。我尝试用布尔变量替换它,即使仍然没有运气。

Ansible 版本:2.0.0.1

任何想法,请帮忙。

【问题讨论】:

    标签: yaml jinja2 ansible ansible-playbook


    【解决方案1】:

    您的第二个条件似乎是一个字符串。我的意思是整个情况。字符串始终为真。

    "'Applying auth.0001_initial... OK' in django_migration_result.stdout"
    

    在您的最后一个代码块中,整个条件都用引号引起来。那将是 yaml 级别的字符串以及它工作的原因。

    这个:

    key: value
    

    等同于:

    key: "value"
    

    这样写你的条件应该可以解决问题:

    when: django_migration_result|changed and ('Applying auth.0001_initial... OK' in django_migration_result.stdout)
    

    甚至更好:

    when:
      - django_migration_result | changed
      - 'Applying auth.0001_initial... OK' in django_migration_result.stdout
    

    【讨论】:

    • 这就像一个魅力,你拯救了我的一天。但是我想指出,第二种方法仅在将- 'Applying auth.0001_initial... OK' in django_migration_result.stdout 括在括号内时才有效。所以它应该是:`-('Applying auth.0001_initial...OK' in django_migration_result.stdout)`
    • 是的。如果它以引用开头,Ansible 期望整个内容都被引用。忘了那个。 :)
    • 我发现 Ansible 的语法像这样完全令人困惑。在某些地方,您必须引用和使用转义符,例如"{{ variable|int }}"。在其他地方,你可以写一个条件裸。在其中一些地方,引用和转义的形式似乎也不起作用......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-14
    • 2016-07-18
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    相关资源
    最近更新 更多