Search code examples
google-cloud-platformgcloudgoogle-cloud-sdkgoogle-cloud-kms

Correct use of gcloud --sort-by combined with --limit


I'm using Google Cloud KMS, and I try to get the latest version of a specific asymmetric key with gcloud cli (v492.0). It seems that the --limit flag doesn't take into account the sorting direction provided by --sort-by. Sorting is getting applied after the limit, in my opinion this is wrong and sorting should happen first then the limit.

I currently have 3 versions of my-key. To get the latest version of a specific key I use the following command :

gcloud kms keys versions list \
  --key my-key \
  --keyring my-keyring \
  --location global \
  --filter "state:ENABLED" \
  --sort-by "~createTime" \
  --limit 1

However this command results always in the very first version of the specified key.

NAME                                                           STATE
projects/.../my-keyring/cryptoKeys/my-key/cryptoKeyVersions/1  ENABLED

I expected to see cryptoKeyVersions/3 here but I get cryptoKeyVersions/1 instead.

Omitting the --limit flag gives this result:

NAME                                                           STATE
projects/.../my-keyring/cryptoKeys/my-key/cryptoKeyVersions/3  ENABLED
projects/.../my-keyring/cryptoKeys/my-key/cryptoKeyVersions/2  ENABLED
projects/.../my-keyring/cryptoKeys/my-key/cryptoKeyVersions/1  ENABLED

So sorting has been applied correctly.

When I issue the same command but with --limit 2:

gcloud kms keys versions list \
  --key my-key \
  --keyring my-keyring \
  --location global \
  --filter "state:ENABLED" \
  --sort-by "~createTime" \
  --limit 2

It gives back two records:

NAME                                                           STATE
projects/.../my-keyring/cryptoKeys/my-key/cryptoKeyVersions/2  ENABLED
projects/.../my-keyring/cryptoKeys/my-key/cryptoKeyVersions/1  ENABLED

While I expected to see keyversions 3 and 2. So the obvious reason for this is that limit happens first sorting afterwards.

My questions is: Is this the intended way of working and I got it wrong or is this a bug?


Solution

  • There is an ongoing GCP issue with order of applying --limit= and --sort-by in this issue tracker, this is an old issue which is still going on, if you want to create a new Issue Tracker thread describing your issue. If you have paid support try create an issue.

    You can try another workaround using --format flag to get the latest versions, try below command which gives the latest versions which are enabled:

    gcloud kms keys versions list \
      --key demo1 \
      --keyring demo-1 \
      --location global \
      --filter "state:ENABLED" \
      --sort-by "~createTime" \
      --format="value(name)" | \
    head -n 2
    

    output :

    projects/………../keyRings/demo-1/cryptoKeys/demo1/cryptoKeyVersions/4
    projects/………../keyRings/demo-1/cryptoKeys/demo1/cryptoKeyVersions/2