代码之家  ›  专栏  ›  技术社区  ›  Jahan Balasubramaniam

ansible-“when”条件不适用于逻辑“AND”运算符

  •  2
  • Jahan Balasubramaniam  · 技术社区  · 9 年前

    我正在尝试为开发人员编写可理解的剧本,并测试django应用程序的env配置。然而,在可译任务中使用when条件似乎存在问题。

    在下面的代码中,当任务1被更改时,任务2被执行。它不检查第二种情况。

    - 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而不计算第二个条件,就会运行Task2

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

    上述工作按预期进行。我试着用布尔变量替换它,但仍然没有成功。

    答案版本:2.0.0.1

    有什么想法,请帮忙。

    1 回复  |  直到 9 年前
        1
  •  8
  •   udondan    9 年前

    第二个条件似乎是字符串。我是指整个情况。字符串总是真的。

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