Search code examples
python-3.xjmespath

Using python variables in jmespath.search


I am working on a script to query instances not running an AMI. Below query works

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

I would like to use a variable instead. Like below. What's the recommended way to do variable substitution?

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
))

Solution

  • Use simple string formatting, e.g. with f-strings (since 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
    ))
    

    You have to escape curly braces by duplicating them because they're otherwise used to insert variables.