根据条件创建字典

时间:2019-08-21 14:59:15

标签: ansible ansible-2.x

我有以下字典:

mariadb_custom_cnf: { mysqld: { log-bin: '', server_id: '{{ groups[host_group_name].index(inventory_hostname) | int + 1 }}', replicate-do-db: 'replicate' }}

我想做的是在满足条件(例如my_var: "{{ 'foo' if my_condition }}")时创建它,但是我找不到正确的语法来使其工作。

我尝试了几种方法,但没有成功:

mariadb_custom_cnf: { mysqld: { log-bin: '', server_id: '{{ groups[host_group_name].index(inventory_hostname) | int + 1 }}', replicate-do-db: 'replicate' }} if mariadb_replication_user is defined
mariadb_custom_cnf: "{ mysqld: { log-bin: '', server_id: '{{ groups[host_group_name].index(inventory_hostname) | int + 1 }}', replicate-do-db: 'replicate' }} if mariadb_replication_user is defined"
mariadb_custom_cnf: "{{ { mysqld: { log-bin: '', server_id: '{{ groups[host_group_name].index(inventory_hostname) | int + 1 }}', replicate-do-db: 'replicate' }} if mariadb_replication_user is defined }}"

有任何想法吗?

1 个答案:

答案 0 :(得分:0)

您可以在带有set_fact子句的任务when中最终创建字典:

- name: Define mariadb_custom_cnf
  set_fact:
    mariadb_custom_cnf: 
      mysqld:
        log-bin: ""
        server_id: "{{ groups[host_group_name].index(inventory_hostname) | int + 1 }}"
        replicate-do-db: "replicate"
  when: mariadb_replication_user is defined