- name: try wait_for_connection up to 10 times with exponential delay ansible.builtin.wait_for_connection: delay: '{{ item | int }}' timeout: 1 loop: '{{ range(1, 11) | map("pow", 2) }}' loop_control: extended: true ignore_errors: "{{ not ansible_loop.last }}" register: result when: result is not defined or result is failed
从列表中匹配元素,并从字典中提取键
Python 等效代码将是
chains = [1, 2] for chain in chains: for config in chains_config[chain]['configs']: print(config['type'])
在 Ansible 中有几种方法可以做到这一点,这只是一个例子
从字典列表中提取匹配键的方法
tasks: - name: Show extracted list of keys from a list of dictionaries ansible.builtin.debug: msg: "{{ chains | map('extract', chains_config) | map(attribute='configs') | flatten | map(attribute='type') | flatten }}" vars: chains: [1, 2] chains_config: 1: foo: bar configs: - type: routed version: 0.1 - type: bridged version: 0.2 2: foo: baz configs: - type: routed version: 1.0 - type: bridged version: 1.1
- hosts: all gather_facts: True vars: path: /var/lib/cache tasks: - name: The mount point for {{path}}, found using the Ansible mount facts, [-1] is the same as the 'last' filter ansible.builtin.debug: msg: "{{(ansible_facts.mounts | selectattr('mount', 'in', path) | list | sort(attribute='mount'))[-1]['mount']}}"
从列表中省略元素
特殊的 omit 变量仅适用于模块选项,但我们仍然可以将其用作标识符来定制元素列表
在输入模块选项时进行内联列表过滤
- name: Enable a list of Windows features, by name ansible.builtin.set_fact: win_feature_list: "{{ namestuff | reject('equalto', omit) | list }}" vars: namestuff: - "{{ (fs_installed_smb_v1 | default(False)) | ternary(omit, 'FS-SMB1') }}" - "foo" - "bar"
- hosts: localhost tasks: - name: Check hosts in inventory that respond to ssh port wait_for: host: "{{ item }}" port: 22 loop: '{{ has_ah + no_ah }}' vars: has_ah: '{{ hostvars|dictsort|selectattr("1.ansible_host", "defined")|map(attribute="1.ansible_host")|list }}' no_ah: '{{ hostvars|dictsort|rejectattr("1.ansible_host", "defined")|map(attribute="0")|list }}'
基于变量的自定义 Fileglob
此示例使用 Python 参数列表解包来创建基于变量的自定义 fileglob 列表。
将 fileglob 与基于变量的列表一起使用。
- hosts: all vars: mygroups: - prod - web tasks: - name: Copy a glob of files based on a list of groups copy: src: "{{ item }}" dest: "/tmp/{{ item }}" loop: '{{ q("fileglob", *globlist) }}' vars: globlist: '{{ mygroups | map("regex_replace", "^(.*)$", "files/\1/*.conf") | list }}'
- name: Uses 'combine' to update the dictionary and 'zip' to make pairs of both lists ansible.builtin.set_fact: mydict: "{{ mydict | default({}) | combine({item[0]: item[1]}) }}" loop: "{{ (keys | zip(values)) | list }}" vars: keys: - foo - var - bar values: - a - b - c
- name: Show the uptime in days/hours/minutes/seconds ansible.builtin.debug: msg: Uptime {{ now().replace(microsecond=0) - now().fromtimestamp(now(fmt='%s') | int - ansible_uptime_seconds) }}