根据条件选择变量

时间:2018-12-28 19:24:17

标签: python variables ansible jinja2

我有以下变量:

secureVar:
  cosmosconstr: ""
  postgresUrl: ""

它可以为空或包含数据库url,具体取决于我需要在kubernetes中有条件地创建外部服务:

- name: Get DB data
  when: (secureVars | from_json)['cosmosconstr'] | length == 0 and (secureVars | from_json)['postgresUrl'] | length == 0
  shell: ./python/db_credentials.py -dp {{ deploymentPrefix }}
  register: dbData

- name: Generate external services templates
  when: (secureVars | from_json)['cosmosconstr'] | length == 0 and (secureVars | from_json)['postgresUrl'] | length == 0
  action: template src=k8s/common/external-services.j2 dest=/tmp/k8s-external-svc.yml
  vars:
    cosmosUrl: "{{ dbData.stdout_lines[0] | urlsplit('hostname') }}"
    postgresUrl: "{{ dbData.stdout_lines[1] }}"

- name: Generate external services templates
  when: (secureVars | from_json)['cosmosconstr'] | length > 0 and (secureVars | from_json)['postgresUrl'] | length > 0
  action: template src=k8s/common/external-services.j2 dest=/tmp/k8s-external-svc.yml
  vars:
    cosmosUrl: "{{ ( secureVars | from_json )['cosmosconstr'] | urlsplit('hostname') }}"
    postgresUrl: "{{ ( secureVars | from_json )['postgresUrl'] }}"

这就是我现在正在做的事情,我想设置一个条件,以便如果跳过dbData,我将使用secureVars,如果不跳过,则我将使用dbData,问题是,我无法检查dbData.skipped是否等于true,因为如果不跳过,它就不包含skipped属性

1 个答案:

答案 0 :(得分:0)

您可能要使用默认的False值。

  

何时:dbData.skipped | default('False')

在OP中进行编辑:

我最终这样做:

"{% if dbData.skipped is defined %}{{ ( secureVars.stdout | from_json )['postgresUrl'] }}{% else %}{{ dbData.stdout_lines[1] }}{% endif %}"
相关问题