在 jmespath.search 中使用 python 个变量

Using python variables in jmespath.search

我正在编写一个脚本来查询实例,而不是 运行 AMI。以下查询有效

print(jmespath.search(
    "Reservations[].Instances[?ImageId != `ami-056c679fab9e48d8a`].{ InstanceName: Tags[?Key == `Name`]|[0].Value, ImageId: ImageId, PrivateDNSName: PrivateDnsName, PrivateIpAddress: PrivateIpAddress}",
    response
))

我想改用变量。如下图。推荐的变量替换方法是什么?

image_id="ami-056c679fab9e48d8a"
print(jmespath.search(
    "Reservations[].Instances[?ImageId != `{image_id}`].{ InstanceName: Tags[?Key == `Name`]|[0].Value, ImageId: ImageId, PrivateDNSName: PrivateDnsName, PrivateIpAddress: PrivateIpAddress}",
    response
))

使用简单的字符串格式,例如使用 f-strings(自 Python 3.6):

image_id = "ami-056c679fab9e48d8a"
print(jmespath.search(
    f"Reservations[].Instances[?ImageId != `{image_id}`].{{ InstanceName: Tags[?Key == `Name`]|[0].Value, ImageId: ImageId, PrivateDNSName: PrivateDnsName, PrivateIpAddress: PrivateIpAddress}}",
    response
))

您必须通过复制花括号来转义它们,因为它们在其他情况下用于插入变量。