从 Ansible 中的目录列表中检索

Retrieve from a list of directory in Ansible

我在 GCP 中有一些磁盘快照,我可以在列表中获取它们:

snap_list:
  - name: s-1-data-2022-01-01
  - name: s-1-data-2022-02-01
  - name: s-1-data-2022-03-01
  - name: s-2-data-2022-01-01
  - name: s-2-data-2022-02-01
  - name: s-2-data-2022-03-01
  - name: s-3-data-2022-01-01
  - name: s-3-data-2022-02-01
  - name: s-3-data-2022-03-01

s-1、s-2 和 s-3 是服务器。

我想创建一个 Ansible 剧本,它将为每个服务器检索最新的快照(从 2022 年 3 月 1 日开始),然后使用该快照创建磁盘,然后附加到服务器。

如何从 snap_list 中获取每台服务器的最新快照?

问:“检索每个服务器的最新快照。”

A:例如声明下面的变量为appropriate

_snap_lst: "{{ snap_list|
               zip(_srv_date)|
               map('flatten')|
               map('combine')|list }}"
_srv_date: "{{ snap_list|
               map(attribute='name')|
               map('regex_replace', _regex, _replace)|
               map('from_yaml')|list }}"
_regex: '^(.*)-data-(.*)$'
_replace: '{"server": "", "date": ""}'

给予

  _snap_lst:
    - {date: '2022-01-01', name: s-1-data-2022-01-01, server: s-1}
    - {date: '2022-02-01', name: s-1-data-2022-02-01, server: s-1}
    - {date: '2022-03-01', name: s-1-data-2022-03-01, server: s-1}
    - {date: '2022-01-01', name: s-2-data-2022-01-01, server: s-2}
    - {date: '2022-02-01', name: s-2-data-2022-02-01, server: s-2}
    - {date: '2022-03-01', name: s-2-data-2022-03-01, server: s-2}
    - {date: '2022-01-01', name: s-3-data-2022-01-01, server: s-3}
    - {date: '2022-02-01', name: s-3-data-2022-02-01, server: s-3}
    - {date: '2022-03-01', name: s-3-data-2022-03-01, server: s-3}

然后,grupby the attribute server and, in the loop, sort 通过属性 date

    - debug:
        msg: "server: {{ item.0 }}, snapshot: {{ _latest.name }}"
      loop: "{{ _snap_lst|groupby('server') }}"
      vars:
        _latest: "{{ item.1|sort(attribute='date')|last }}"

给出(删节)

  msg: 'server: s-1, snapshot: s-1-data-2022-03-01'
  msg: 'server: s-2, snapshot: s-2-data-2022-03-01'
  msg: 'server: s-3, snapshot: s-3-data-2022-03-01'