1# -*- coding: utf-8 -*- #
2# Copyright 2017 Google LLC. All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#    http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15"""List the keys within a keyring."""
16
17from __future__ import absolute_import
18from __future__ import division
19from __future__ import unicode_literals
20
21from apitools.base.py import list_pager
22from googlecloudsdk.api_lib.cloudkms import base as cloudkms_base
23from googlecloudsdk.calliope import base
24from googlecloudsdk.command_lib.kms import resource_args
25
26
27class List(base.ListCommand):
28  """List the keys within a keyring.
29
30  Lists all keys within the given keyring.
31
32  ## EXAMPLES
33
34  The following command lists all keys within the
35  keyring `fellowship` and location `global`:
36
37    $ {command} --keyring=fellowship --location=global
38  """
39
40  @staticmethod
41  def Args(parser):
42    # The format of a CryptoKeyVersion name is:
43    # 'projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*'
44    # The CryptoKeyVersionId is captured by segment(9).
45    resource_args.AddKmsKeyringResourceArgForKMS(parser, True, '--keyring')
46
47    parser.display_info.AddFormat("""
48        table(
49          name,
50          purpose,
51          version_template.algorithm,
52          version_template.protection_level,
53          labels.list(),
54          primary.name.segment(9):label=PRIMARY_ID,
55          primary.state:label=PRIMARY_STATE)
56    """)
57
58  def Run(self, args):
59    client = cloudkms_base.GetClientInstance()
60    messages = cloudkms_base.GetMessagesModule()
61
62    key_ring_ref = args.CONCEPTS.keyring.Parse()
63
64    request = messages.CloudkmsProjectsLocationsKeyRingsCryptoKeysListRequest(
65        parent=key_ring_ref.RelativeName())
66
67    return list_pager.YieldFromList(
68        client.projects_locations_keyRings_cryptoKeys,
69        request,
70        field='cryptoKeys',
71        limit=args.limit,
72        batch_size_attribute='pageSize')
73