Reputation: 15
I have written following code, which return me list of Snapshot, which have particular string, but this does not return snapshots whose Size is 0,
https://cloud.google.com/compute/docs/reference/rest/v1/snapshots/list
this API have following attributes:
I am trying to put some filter based on regular expression which will match all snapshot which have "intance-snap" in there name.
def snapshotlist():
query = "name eq <string>.*"
snaplist = compute.snapshots().list(project=project,filter=query).execute()
snaplist = ast.literal_eval(json.dumps(snaplist))
for snap in snaplist['items']:
print(snap['name'])
Above code does not return Snapshots, which have size 0, is there way to get all snapshots, regardless of there SIZE ?
Upvotes: 0
Views: 1382
Reputation: 9862
From the Snapshot documentation, for the optional parameter's filter
attribute:
The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either
=
,!=
,>
, or<
.
While this means you cannot perform a query similar to what is done with the Drive API, e.g. q: "name contains 'some string'"
, the Snapshots#list
method still appears to support wildcard matching. If you are unable to successfully write the appropriate regex, then the solution is to collect your entire list of Snapshot
s, and then use your language's string and regex methods to filter the output.
def get_matching_snapshots(projectId: str, query='',
fields='id,nextPageToken,warning,items(id,name,description)'):
snaplist = []
params = {project: projectId,
filter: query,
fields: fields}
# Collect all pages of results
request = compute.snapshots().list(**params)
while request:
response = request.execute()
if 'items' in response:
snaplist.extend(response['items'])
if 'warning' in response:
pprint(response['warning'])
request = compute.snapshots().list_next(request, response)
return snaplist
# Use 'filter' parameter to restrict on server side:
name_fragment = "some required part of the name"
q = f'name = "{name_fragment}.*"'
pprint(get_matching_snapshots("some project id", q))
# get all, then apply restrictions after retrieval:
all_snapshots = get_matching_snapshots("some project id")
matches = []
rgx = re.compile('some regex')
for snap in all_snapshots:
# use rgx.match with the relevant snap property
...
You may find it beneficial to consult the Compute API's Python documentation, or to use the Python client's API Explorer:
Upvotes: 1