Ansible Jinja2使用

常用方法

  • ternary

根据结果的真假来决定返回值

- name: Set container backend to "dir" or "lvm" based on whether the lxc VG was found
  set_fact:
     lxc_container_backing_store: "{{ (vg_result.rc != 0) | ternary('dir', 'lvm') }}"
  when: vg_result.rc is defined
  tags:
    - lxc-container-vg-detect

vg_result.rc不为0返回dir,否则返回lvm

  • if语法

根据结果的真假来决定返回值

- name: Set the external network bridge
  vars:
    agent: "{{ 'neutron-vpnaas-agent' if enable_neutron_vpnaas | bool else 'neutron-l3-agent' }}"
  ini_file:
    dest: "{{ node_config_directory }}/{{ agent }}/l3_agent.ini"
    section: "DEFAULT"
    option: "external_network_bridge"
    value: "{{ neutron_bridge_name | default('br-ex') }}"
    backup: yes
  when:
    - action == "deploy"
    - inventory_hostname in ovn_central_address
  delegate_to: "{{ item }}"
  with_items: "{{ groups['neutron-server'] }}"
  notify:
  - Restart {{ agent }} container
  • when中使用jinja2

when表达式中不建议直接使用{{}}的方式来获取变量值,如果变量是字符串可以使用管道操作| string来获取变量值

- name: Checking free port for OVN
  vars:
    service: "{{ neutron_services[item.name] }}"
  wait_for:
    host: "{{ hostvars[inventory_hostname]['ansible_' + api_interface]['ipv4']['address'] }}"
    port: "{{ item.port }}"
    connect_timeout: 1
    state: stopped
  when:
    - container_facts[ item.facts | string ] is not defined
    - service.enabled | bool
    - service.host_in_groups | bool
  with_items:
    - { name: "ovn-nb-db-server", port: "{{ ovn_northdb_port }}", facts: "ovn_nb_db" }
    - { name: "ovn-sb-db-server", port: "{{ ovn_sourthdb_port }}", facts: "ovn_sb_db" }
posted @ 2017-10-14 11:46  银魔术师  阅读(2102)  评论(0编辑  收藏  举报