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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM