0

我正在尝试使用该aws ec2命令在 AWS 中查找设备和主机的最新快照。我从aws ec2 describe-snapshots.

如您所见,我可以为同一主机(请参阅带有密钥主机名和设备名的标签)和设备创建多个快照。开始时间不同。

{
"Snapshots": [
    {
        "Description": "My desc.",
        "Encrypted": false,
        "VolumeId": "vol-aaa",
        "State": "completed",
        "VolumeSize": 8,
        "StartTime": "2018-02-02T19:27:56.000Z",
        "Progress": "100%",
        "OwnerId": "5674567",
        "SnapshotId": "snap-xxx"
    },  
    {
        "Description": "host1.domain.com - sdc",
        "Tags": [
            {
                "Value": "SNAP1",
                "Key": "Name"
            },
            {
                "Value": "sdc",
                "Key": "devicename"
            },
            {
                "Value": "host1.domain.com",
                "Key": "hostname"
            }
        ],
        "Encrypted": false,
        "VolumeId": "vol-xxx",
        "State": "completed",
        "VolumeSize": 140,
        "StartTime": "2018-09-21T08:39:58.000Z",
        "Progress": "100%",
        "OwnerId": "345634563456",
        "SnapshotId": "snap-xxx"
    },  
    {
        "Description": "host1.domain.com - sdc",
        "Tags": [
            {
                "Value": "SNAP2",
                "Key": "Name"
            },
            {
                "Value": "sdc",
                "Key": "devicename"
            },
            {
                "Value": "host1.domain.com",
                "Key": "hostname"
            }
        ],
        "Encrypted": false,
        "VolumeId": "vol-xxx",
        "State": "completed",
        "VolumeSize": 140,
        "StartTime": "2018-09-22T08:39:58.000Z",
        "Progress": "100%",
        "OwnerId": "345634563456",
        "SnapshotId": "snap-xxx"
    }
}

如何在 Ansible 中查询此 JSON 以获得主机名和设备的最新快照?我不经常这样做,因此对查询语法感到困惑。

到目前为止,我有以下内容。

 - shell: "aws ec2 describe-snapshots"
   register: snap
   delegate_to: localhost

 - debug:
     msg: "{{ snap.stdout | from_json | json_query(query) }}"
   vars:
     query: "Snapshots[].Tags[?Key=='hostname'].Value"

但是,如何选择 Tags.Value 等于 Key 为“主机名”的某个值的所有快照元素?然后我如何从我得到的列表中选择最新的?

4

1 回答 1

2

根据精细手册,JMESPath 支持嵌套括号说明符表达式:

  vars:
    snap: |
      {
        "Snapshots": [
          {"Id": "aaa", "Tags": [{"Key": "hostname", "Value": "alpha"}]},
          {"Id": "bbb", "Tags": [{"Key": "hostname", "Value": "beta"}]}
        ]
      }
    jq: "Snapshots[? Tags[? Key=='hostname' && Value=='alpha']].Id"
  tasks:
  - debug:
      msg: "{{ snap | from_json | json_query(jq) }}"

至于“对于某个主机”部分,vars: query:就像其他所有的 ansible 字符串一样,它受 jinja2 插值的影响,因此:

vars:
  query: ... [? Value=='{{ the_hostname }}' ] ...

请注意确保正确转义该值 - 这可能不会是主机名的问题,但我的意思是一般来说

然后,对于“列表中的最新”部分,ISO8601 具有按字典顺序排序的非常令人愉悦的附带好处,因此:

  vars:
    jq: "Snapshots[? Tags[? Key=='hostname' && Value=='alpha']]"
  tasks:
  - debug:
      msg: "{{ snap | from_json | json_query(jq) | sort(attribute='StartTime', reverse=True) }}"
于 2018-09-22T19:47:48.667 回答