Esempio n. 1
0
  def Args(parser):
    key_spec_group = parser.add_group(
        mutex=True,
        help='The key configuration used for the CA certificate. Defaults to a '
        'managed key if not specified.')
    reusable_config_group = parser.add_group(
        mutex=True,
        required=False,
        help='The X.509 configuration used for the CA certificate.')
    issuer_configuration_group = parser.add_group(
        mutex=True,
        required=True,
        help='The issuer configuration used for this CA certificate.')

    concept_parsers.ConceptParser([
        presentation_specs.ResourcePresentationSpec(
            'CERTIFICATE_AUTHORITY',
            resource_args.CreateCertificateAuthorityResourceSpec(
                'Certificate Authority'),
            'The name of the subordinate CA to create.',
            required=True),
        presentation_specs.ResourcePresentationSpec(
            '--issuer',
            resource_args.CreateCertificateAuthorityResourceSpec(
                'Issuer'),
            'The issuing certificate authority to use, if it is on Private CA.',
            prefixes=True,
            group=issuer_configuration_group),
        presentation_specs.ResourcePresentationSpec(
            '--kms-key-version',
            resource_args.CreateKmsKeyVersionResourceSpec(),
            'The KMS key version backing this CA.',
            group=key_spec_group),
        presentation_specs.ResourcePresentationSpec(
            '--reusable-config',
            resource_args.CreateReusableConfigResourceSpec(
                location_fallthroughs=[
                    deps.Fallthrough(
                        function=lambda: '',
                        hint=(
                            'location will default to the same location as the '
                            'CA'),
                        active=False,
                        plural=False)
                ]),
            'The Reusable Config containing X.509 values for this CA.',
            flag_name_overrides={
                'location': '',
                'project': '',
            },
            group=reusable_config_group),
        presentation_specs.ResourcePresentationSpec(
            '--from-ca',
            resource_args.CreateCertificateAuthorityResourceSpec(
                'source CA'),
            'An existing CA from which to copy configuration values for the '
            'new CA. You can still override any of those values by explicitly '
            'providing the appropriate flags.',
            flag_name_overrides={'project': '--from-ca-project'},
            prefixes=True)
    ]).AddToParser(parser)
    flags.AddTierFlag(parser)
    flags.AddSubjectFlags(parser, subject_required=False)
    flags.AddPublishCaCertFlag(parser, use_update_help_text=False)
    flags.AddPublishCrlFlag(parser, use_update_help_text=False)
    flags.AddKeyAlgorithmFlag(key_spec_group, default='rsa-pkcs1-2048-sha256')
    flags.AddInlineReusableConfigFlags(
        reusable_config_group, is_ca_command=True, default_max_chain_length=0)
    flags.AddValidityFlag(
        parser,
        resource_name='CA',
        default_value='P3Y',
        default_value_text='3 years')
    flags.AddCertificateAuthorityIssuancePolicyFlag(parser)
    labels_util.AddCreateLabelsFlags(parser)
    flags.AddBucketFlag(parser)

    offline_issuer_group = issuer_configuration_group.add_group(
        help=('If the issuing CA is not hosted on Private CA, you must provide '
              'these settings:'))
    base.Argument(
        '--create-csr',
        help=('Indicates that a CSR should be generated which can be signed by '
              'the issuing CA. This must be set if --issuer is not provided.'),
        action='store_const',
        const=True,
        default=False,
        required=True).AddToParser(offline_issuer_group)
    base.Argument(
        '--csr-output-file',
        help=('The path where the resulting PEM-encoded CSR file should be '
              'written.'),
        required=True).AddToParser(offline_issuer_group)
Esempio n. 2
0
def AddLocationFlag(parser):
    argument = base.Argument(
        '--location',
        hidden=True,
        help='The location of the app associated with the active project.')
    argument.AddToParser(parser)
Esempio n. 3
0
def AddDeviceFlagsToParser(parser, default_for_blocked_flags=True):
    """Add flags for device commands to parser.

  Args:
    parser: argparse parser to which to add these flags.
    default_for_blocked_flags: bool, whether to populate default values for
        device blocked state flags.
  """
    blocked_state_help_text = (
        'If {0}, connections from this device will fail.\n\n'
        'Can be used to temporarily prevent the device from '
        'connecting if, for example, the sensor is generating bad '
        'data and needs maintenance.\n\n')
    enable_device_format_args = ('disabled', )
    blocked_format_args = ('blocked', )
    if not default_for_blocked_flags:
        blocked_state_help_text += (
            '+\n\n'  # '+' here preserves markdown indentation.
            'Use `--{1}` to enable connections and `--{2}` to disable.')
        enable_device_format_args += ('enable-device', 'no-enable-device')
        blocked_format_args += ('no-blocked', 'blocked')
    else:
        blocked_state_help_text += (
            '+\n\n'
            'Connections to device is not blocked by default.')

    blocked_state_args = parser.add_mutually_exclusive_group()
    # Defaults are set to None because with nested groups, help text isn't being
    # generated correctly.
    blocked_state_args.add_argument(
        '--enable-device',
        default=None,
        action=actions.DeprecationAction(
            '--[no-]enable-device',
            warn=('Flag {flag_name} is deprecated. '
                  'Use --[no-]blocked instead.'),
            action='store_true'),
        help=blocked_state_help_text.format(*enable_device_format_args))
    blocked_state_args.add_argument(
        '--blocked',
        default=None,
        action='store_true',
        help=blocked_state_help_text.format(*blocked_format_args))

    metadata_key_validator = arg_parsers.RegexpValidator(
        r'[a-zA-Z0-9-_]{1,127}',
        'Invalid metadata key. Keys should only contain the following characters '
        '[a-zA-Z0-9-_] and be fewer than 128 bytes in length.')
    base.Argument('--metadata',
                  metavar='KEY=VALUE',
                  type=arg_parsers.ArgDict(key_type=metadata_key_validator),
                  help="""\
The metadata key/value pairs assigned to devices. This metadata is not
interpreted or indexed by Cloud IoT Core. It can be used to add contextual
information for the device.

Keys should only contain the following characters ```[a-zA-Z0-9-_]``` and be
fewer than 128 bytes in length. Values are free-form strings. Each value must
be fewer than or equal to 32 KB in size.

The total size of all keys and values must be less than 256 KB, and the
maximum number of key-value pairs is 500.
""").AddToParser(parser)

    base.Argument(
        '--metadata-from-file',
        metavar='KEY=PATH',
        type=arg_parsers.ArgDict(key_type=metadata_key_validator),
        help=(
            'Same as --metadata, but the metadata values will be read from the '
            'file specified by path.')).AddToParser(parser)
Esempio n. 4
0
def AddPolicyFileFlag(parser):
    base.Argument('policy_file',
                  help="""\
      JSON or YAML file containing the IAM policy.""").AddToParser(parser)
Esempio n. 5
0
def AddQueueResourceFlag(parser, required=True, plural_tasks=False):
    description = ('The queue the tasks belong to.'
                   if plural_tasks else 'The queue the task belongs to.')
    argument = base.Argument('--queue', help=description, required=required)
    argument.AddToParser(parser)
Esempio n. 6
0
"""This module holds common flags used by the gcloud app commands."""
from __future__ import absolute_import
import argparse

from googlecloudsdk.api_lib.app import logs_util
from googlecloudsdk.api_lib.storage import storage_util
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.app import exceptions
from googlecloudsdk.core import log
from googlecloudsdk.core.docker import constants
from googlecloudsdk.core.docker import docker
from googlecloudsdk.third_party.appengine.api import appinfo

DOMAIN_FLAG = base.Argument(
    'domain',
    help=('A valid domain which may begin with a wildcard, such as: '
          '`example.com` or `*.example.com`'))

CERTIFICATE_ID_FLAG = base.Argument(
    'id',
    help=('The id of the certificate. This identifier is printed upon'
          ' creation of a new certificate. Run `{parent_command}'
          ' list` to view existing certificates.'))

LAUNCH_BROWSER = base.Argument(
    '--launch-browser',
    action='store_true',
    default=True,
    dest='launch_browser',
    help='Launch a browser if possible. When disabled, only displays the URL.')
Esempio n. 7
0
class Config(base.Group):
  """View and edit Google Cloud SDK properties."""

  SCOPE_FLAG = base.Argument(
      '--scope',
      required=False,
      choices=properties.Scope.AllScopeNames(),
      help='The configuration location in which to update the property. '
      '({scopes})'.format(scopes=', '.join(properties.Scope.AllScopeNames())),
      detailed_help="""\
The scope flag determines which configuration file is modified by this
operation.  The files are read (and take precedence) in the following
order:

{scope_help}
""".format(scope_help=properties.Scope.GetHelpString())
  )

  @staticmethod
  def PropertiesCompleter(prefix, parsed_args, **unused_kwargs):
    """Properties commmand completion helper."""
    all_sections = properties.VALUES.AllSections()
    options = []

    if '/' in prefix:
      # Section has been specified, only return properties under that section.
      parts = prefix.split('/', 1)
      section = parts[0]
      prefix = parts[1]
      if section in all_sections:
        section_str = section + '/'
        props = properties.VALUES.Section(section).AllProperties()
        options.extend([section_str + p for p in props if p.startswith(prefix)])
    else:
      # No section.  Return matching sections and properties in the default
      # group.
      options.extend([s + '/' for s in all_sections if s.startswith(prefix)])
      section = properties.VALUES.default_section.name
      props = properties.VALUES.Section(section).AllProperties()
      options.extend([p for p in props if p.startswith(prefix)])

    return options

  def ParsePropertyString(self, property_string):
    """Parses a string into a section and property name.

    Args:
      property_string: str, The property string in the format section/property.

    Returns:
      (str, str), The section and property.  Both will be none if the input
      string is empty.  Property can be None if the string ends with a slash.
    """
    if not property_string:
      return None, None

    if '/' in property_string:
      section, prop = tuple(property_string.split('/', 1))
    else:
      section = None
      prop = property_string

    section = section or properties.VALUES.default_section.name
    prop = prop or None
    return section, prop

  def PropertyFromString(self, property_string):
    """Gets the property object corresponding the given string.

    Args:
      property_string: str, The string to parse.  It can be in the format
        section/property, or just property if the section is the default one.

    Raises:
      InvalidArgumentException: For invalid arguments.

    Returns:
      properties.Property, The property.
    """
    section, prop = self.ParsePropertyString(property_string)
    if not prop:
      raise c_exc.InvalidArgumentException(
          'property', 'Must be in the form: [SECTION/]PROPERTY')
    return properties.VALUES.Section(section).Property(prop)
Esempio n. 8
0
def available_service_flag(suffix='to act on', flag_name='service'):
    # NOTE: Because listing available services often forces the tab completion
    #       code to timeout, this flag will not enable tab completion.
    return base.Argument(flag_name,
                         help='The name of the service {0}.'.format(suffix))
Esempio n. 9
0
def key_flag(suffix='to act on'):
    return base.Argument('--key',
                         help='The identifier of the key {0}.'.format(suffix))
Esempio n. 10
0
def operation_flag(suffix='to act on'):
    return base.Argument('operation',
                         help='The name of the operation {0}.'.format(suffix))
Esempio n. 11
0
def consumer_service_flag(suffix='to act on', flag_name='service'):
    return base.Argument(flag_name,
                         completer=ConsumerServiceCompleter,
                         help='The name of the service {0}.'.format(suffix))
Esempio n. 12
0
    def Args(parser):
        base.Argument(
            '--cert-output-file',
            help=
            'The path where the resulting PEM-encoded certificate chain file should be written (ordered from leaf to root).',
            required=False).AddToParser(parser)
        flags.AddValidityFlag(parser, 'certificate', 'P30D', '30 days')
        labels_util.AddCreateLabelsFlags(parser)

        cert_generation_group = parser.add_group(
            mutex=True, required=True, help='Certificate generation method.')
        base.Argument(
            '--csr',
            help='A PEM-encoded certificate signing request file path.'
        ).AddToParser(cert_generation_group)

        key_generation_group = cert_generation_group.add_group(
            help='Alternatively, to generate a new key pair, use the following:'
        )
        base.Argument(
            '--generate-key',
            help=
            'Use this flag to have a new RSA-2048 private key securely generated on your machine.',
            action='store_const',
            const=True,
            default=False,
            required=True).AddToParser(key_generation_group)
        base.Argument('--key-output-file',
                      help=_KEY_OUTPUT_HELP,
                      required=True).AddToParser(key_generation_group)

        subject_group = key_generation_group.add_group(
            help='The subject names for the certificate.', required=True)
        flags.AddSubjectFlags(subject_group)
        reusable_config_group = key_generation_group.add_group(
            mutex=True,
            help='The x509 configuration used for this certificate.')
        flags.AddInlineReusableConfigFlags(reusable_config_group, is_ca=False)

        cert_arg = 'CERTIFICATE'
        concept_parsers.ConceptParser([
            presentation_specs.ResourcePresentationSpec(
                cert_arg,
                resource_args.CreateCertificateResourceSpec(
                    cert_arg, [Create._GenerateCertificateIdFallthrough()]),
                'The name of the certificate to issue. If the certificate ID is '
                'omitted, a random identifier will be generated according to the '
                'following format: {YYYYMMDD}-{3 random alphanumeric characters}-'
                '{3 random alphanumeric characters}. The certificate ID is not '
                'required when the issuing CA is in the DevOps tier.',
                required=True)
        ]).AddToParser(parser)

        concept_parsers.ConceptParser([
            presentation_specs.ResourcePresentationSpec(
                '--reusable-config',
                resource_args.
                CreateReusableConfigResourceSpec(location_fallthroughs=[
                    deps.Fallthrough(
                        function=lambda: '',
                        hint=(
                            'location will default to the same location as the '
                            'certificate'),
                        active=False,
                        plural=False)
                ]),
                'The Reusable Config containing X.509 values for this certificate.',
                flag_name_overrides={
                    'location': '',
                    'project': '',
                },
                group=reusable_config_group)
        ]).AddToParser(reusable_config_group)
Esempio n. 13
0
def GetScopeFlag():
    return base.Argument(
        '--scope',
        help=('The scope to associate with the Artifact Registry registry. '
              'If not specified, Artifact Registry is set as the default '
              'registry.'))
Esempio n. 14
0
def GetDeleteTagsFlag():
    return base.Argument(
        '--delete-tags',
        help='If specified, all tags associated with the image are deleted.',
        action='store_true',
        required=False)
Esempio n. 15
0
def GetModelName(positional=True, required=False):
    help_text = 'Name of the model.'
    if positional:
        return base.Argument('model', help=help_text)
    else:
        return base.Argument('--model', help=help_text, required=required)
Esempio n. 16
0
def GenerateFlag(field, attributes, fix_bools=True, category=None):
  """Generates a flag for a single field in a message.

  Args:
    field: The apitools field object.
    attributes: yaml_command_schema.Argument, The attributes to use to
      generate the arg.
    fix_bools: True to generate boolean flags as switches that take a value or
      False to just generate them as regular string flags.
    category: The help category to put the flag in.

  Raises:
    ArgumentGenerationError: When an argument could not be generated from the
      API field.

  Returns:
    calliope.base.Argument, The generated argument.
  """
  variant = field.variant if field else None
  t = attributes.type or TYPES.get(variant, None)

  choices = None
  if attributes.choices is not None:
    choice_map = {c.arg_value: c.help_text for c in attributes.choices}
    # If help text is provided, give a choice map. Otherwise, just use the
    # choice values.
    choices = (choice_map if any(choice_map.values())
               else sorted(choice_map.keys()))
  elif variant == messages.Variant.ENUM:
    choices = [EnumNameToChoice(name) for name in sorted(field.type.names())]

  action = attributes.action
  if t == bool and fix_bools and not action:
    # For boolean flags, we want to create a flag with action 'store_true'
    # rather than a flag that takes a value and converts it to a boolean. Only
    # do this if not using a custom action.
    action = 'store_true'
  # Default action is store if one was not provided.
  action = action or 'store'

  # pylint: disable=g-explicit-bool-comparison, only an explicit False should
  # override this, None just means to do the default.
  repeated = (field and field.repeated) and attributes.repeated != False

  if repeated:
    if action != 'store':
      raise ArgumentGenerationError(
          field.name,
          'The field is repeated but is using a custom action. You might'
          ' want to set repeated: False in your arg spec.')
    if t:
      # A special ArgDict wrapper type was given, bind it to the message so it
      # can generate the message from the key/value pairs.
      if isinstance(t, RepeatedMessageBindableType):
        action = t.Action()
        t = t.GenerateType(field.type)
      # If a simple type was provided, just use a list of that type (even if it
      # is a message). The type function will be responsible for converting to
      # the correct value. If type is an ArgList or ArgDict, don't try to wrap
      # it.
      elif not isinstance(t, arg_parsers.ArgList):
        t = arg_parsers.ArgList(element_type=t, choices=choices)
        # Don't register the choices on the argparse arg because it is validated
        # by the ArgList.
        choices = None
  elif isinstance(t, RepeatedMessageBindableType):
    raise ArgumentGenerationError(
        field.name, 'The given type can only be used on repeated fields.')

  if field and not t and action == 'store' and not attributes.processor:
    # The type is unknown and there is no custom action or processor, we don't
    # know what to do with this.
    raise ArgumentGenerationError(
        field.name, 'The field is of an unknown type. You can specify a type '
                    'function or a processor to manually handle this argument.')

  name = attributes.arg_name
  arg = base.Argument(
      name if attributes.is_positional else '--' + name,
      category=category if not attributes.is_positional else None,
      action=action,
      completer=attributes.completer,
      help=attributes.help_text,
      hidden=attributes.hidden,
  )
  if attributes.default != UNSPECIFIED:
    arg.kwargs['default'] = attributes.default
  if action != 'store_true':
    # For this special action type, it won't accept a bunch of the common
    # kwargs, so we can only add them if not generating a boolean flag.
    metavar = attributes.metavar or name
    arg.kwargs['metavar'] = resource_property.ConvertToAngrySnakeCase(
        metavar.replace('-', '_'))
    arg.kwargs['type'] = t
    arg.kwargs['choices'] = choices
  if not attributes.is_positional:
    arg.kwargs['required'] = attributes.required
  return arg
Esempio n. 17
0
# Copyright 2014 Google Inc. All Rights Reserved.

"""This module holds common flags used by the gcloud app commands."""
import argparse

from googlecloudsdk.calliope import base

SERVER_FLAG = base.Argument(
    '--server',
    help='The App Engine server to connect to.  You will not typically need to '
    'change this value.')

VERSION_FLAG = base.Argument(
    '--version',
    required=True,
    help='The version of the app that you want to operate on.')

# TODO(user): Add module globbing.
MODULES_ARG = base.Argument(
    'modules',
    nargs='+',
    help='One or more module names to perform this action on.  To select the '
    'default module for your app, use "default".')

MODULES_OPTIONAL_ARG = base.Argument(
    'modules',
    nargs='*',
    help='An optional list of module names to perform this action on.  To '
    'select the default module for your app, use "default".  If no modules are '
    'given all modules are used.')
Esempio n. 18
0
              self).__init__(resource_collection=models_util.MODELS_COLLECTION,
                             resource_dest='model',
                             **kwargs)


def GetDescriptionFlag(noun):
    return base.Argument('--description',
                         required=False,
                         default=None,
                         help='Description of the {noun}.'.format(noun=noun))


# Run flags
DISTRIBUTED = base.Argument(
    '--distributed',
    action='store_true',
    default=False,
    help=('Runs the provided code in distributed mode by providing cluster '
          'configurations as environment variables to subprocesses'))
PARAM_SERVERS = base.Argument(
    '--parameter-server-count',
    type=int,
    help=('Number of parameter servers with which to run. '
          'Ignored if --distributed is not specified. Default: 2'))
WORKERS = base.Argument(
    '--worker-count',
    type=int,
    help=('Number of workers with which to run. '
          'Ignored if --distributed is not specified. Default: 2'))
EVALUATORS = base.Argument(
    '--evaluator-count',
    type=int,
Esempio n. 19
0
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common flags for some of the SQL commands."""

from googlecloudsdk.calliope import actions
from googlecloudsdk.calliope import base

INSTANCE_FLAG = base.Argument('--instance',
                              '-i',
                              required=True,
                              completion_resource='sql.instances',
                              help='Cloud SQL instance ID.')

DEPRECATED_INSTANCE_FLAG_REQUIRED = base.Argument(
    '--instance',
    '-i',
    action=actions.DeprecationAction(
        '--instance',
        removed=False,
        warn=('Starting on 2017-06-30, --instance will no longer be a valid '
              'flag: Run the same command but omit this flag.'),
    ),
    required=True,
    completion_resource='sql.instances',
    help='Cloud SQL instance ID.')
Esempio n. 20
0
def GetModuleNameFlag(required=True):
    return base.Argument('--module-name',
                         required=required,
                         help='Name of the module to run.')
Esempio n. 21
0
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.core import properties
import ipaddress

AIRFLOW_VERSION_TYPE = arg_parsers.RegexpValidator(
    r'^(\d+\.\d+(?:\.\d+)?)', 'must be in the form X.Y[.Z].')

IMAGE_VERSION_TYPE = arg_parsers.RegexpValidator(
    r'^composer-(\d+\.\d+\.\d+|latest)-airflow-(\d+\.\d+(?:\.\d+)?)',
    'must be in the form \'composer-A.B.C-airflow-X.Y[.Z]\' or '
    '\'latest\' can be provided in place of the Cloud Composer version '
    'string. For example: \'composer-latest-airflow-1.10.0\'.')

# TODO(b/118349075): Refactor global Argument definitions to be factory methods.
ENVIRONMENT_NAME_ARG = base.Argument('name',
                                     metavar='NAME',
                                     help='The name of an environment.')

MULTI_ENVIRONMENT_NAME_ARG = base.Argument('name',
                                           metavar='NAME',
                                           nargs='+',
                                           help='The name of an environment.')

MULTI_OPERATION_NAME_ARG = base.Argument(
    'name',
    metavar='NAME',
    nargs='+',
    help='The name or UUID of an operation.')

OPERATION_NAME_ARG = base.Argument('name',
                                   metavar='NAME',
Esempio n. 22
0
def AddMachineTypeFlagToParser(parser):
    base.Argument('--machine-type',
                  help="""\
Type of machine on which to serve the model. Currently only applies to online prediction. For available machine types,
see https://cloud.google.com/ai-platform/prediction/docs/machine-types-online-prediction#available_machine_types.
""").AddToParser(parser)
Esempio n. 23
0
def AddQueueResourceArg(parser, verb):
    base.Argument('queue',
                  help='The queue {}.\n\n'.format(verb)).AddToParser(parser)
Esempio n. 24
0
def AddIdArg(parser, noun, verb, metavar=None):
    metavar = metavar or '{}_ID'.format(noun.replace(' ', '_').upper())
    argument = base.Argument('id',
                             metavar=metavar,
                             help='ID of the {} {}.\n\n'.format(noun, verb))
    argument.AddToParser(parser)
Esempio n. 25
0
def AddTaskResourceArgs(parser, verb):
    base.Argument('task',
                  help='The task {}.\n\n'.format(verb)).AddToParser(parser)
    AddQueueResourceFlag(parser, required=False)
Esempio n. 26
0
                             resource_dest='model',
                             **kwargs)


def GetDescriptionFlag(noun):
    return base.Argument(
        '--description',
        required=False,
        default=None,
        help='The description of the {noun}.'.format(noun=noun))


# Run flags
DISTRIBUTED = base.Argument(
    '--distributed',
    action='store_true',
    default=False,
    help=('Runs the provided code in distributed mode by providing cluster '
          'configurations as environment variables to subprocesses'))
PARAM_SERVERS = base.Argument(
    '--parameter-server-count',
    type=int,
    help=('Number of parameter servers with which to run. '
          'Ignored if --distributed is not specified. Default: 2'))
WORKERS = base.Argument(
    '--worker-count',
    type=int,
    help=('Number of workers with which to run. '
          'Ignored if --distributed is not specified. Default: 2'))
START_PORT = base.Argument('--start-port',
                           type=int,
                           default=27182,
Esempio n. 27
0
def GetIamPolicyFileFlag():
    return base.Argument('policy_file',
                         help='JSON or YAML file with the IAM policy')
Esempio n. 28
0
def GetDescriptionFlag(noun):
    return base.Argument(
        '--description',
        required=False,
        default=None,
        help='The description of the {noun}.'.format(noun=noun))
Esempio n. 29
0
def GetIdFlag(noun, action, metavar=None):
    return base.Argument('id',
                         metavar=metavar
                         or '{}_ID'.format(noun.replace(' ', '_').upper()),
                         help='ID of the {} {}.\n\n'.format(noun, action))
Esempio n. 30
0
  def Args(parser):
    key_spec_group = parser.add_group(
        mutex=True,
        help='The key configuration used for the CA certificate. Defaults to a '
        'managed key if not specified.')
    x509_config_group = parser.add_group(
        mutex=True,
        required=False,
        help='The X.509 configuration used for the CA certificate.')
    issuer_configuration_group = parser.add_group(
        mutex=True,
        required=True,
        help='The issuer configuration used for this CA certificate.')
    issuing_resource_group = issuer_configuration_group.add_group(
        mutex=False,
        required=False,
        help='The issuing resource used for this CA certificate.')
    base.Argument(
        '--issuer-ca',
        help=(
            'The Certificate Authority ID of the CA to issue the subordinate '
            'CA certificate from. This ID is optional. If ommitted, '
            'any available ENABLED CA in the issuing CA pool will be chosen.'),
        required=False).AddToParser(issuing_resource_group)

    concept_parsers.ConceptParser([
        presentation_specs.ResourcePresentationSpec(
            'CERTIFICATE_AUTHORITY',
            resource_args.CreateCertAuthorityResourceSpec(
                'Certificate Authority'),
            'The name of the subordinate CA to create.',
            required=True),
        presentation_specs.ResourcePresentationSpec(
            '--issuer-pool',
            resource_args.CreateCaPoolResourceSpec('Issuer'),
            'The issuing CA Pool to use, if it is on Private CA.',
            prefixes=True,
            required=False,
            flag_name_overrides={
                'location': '--issuer-location',
            },
            group=issuing_resource_group),
        presentation_specs.ResourcePresentationSpec(
            '--kms-key-version',
            resource_args.CreateKmsKeyVersionResourceSpec(),
            'The KMS key version backing this CA.',
            group=key_spec_group),
        presentation_specs.ResourcePresentationSpec(
            '--from-ca',
            resource_args.CreateCertAuthorityResourceSpec(
                'source CA',
                location_fallthroughs=[
                    deps.ArgFallthrough('--location'),
                    resource_args.LOCATION_PROPERTY_FALLTHROUGH
                ],
                pool_id_fallthroughs=[deps.ArgFallthrough('--pool')]),
            'An existing CA from which to copy configuration values for the '
            'new CA. You can still override any of those values by explicitly '
            'providing the appropriate flags. The specified existing CA must '
            'be part of the same pool as the one being created.',
            flag_name_overrides={
                'project': '',
                'location': '',
                'pool': '',
            },
            prefixes=True)
    ]).AddToParser(parser)

    flags_v1.AddSubjectFlags(parser, subject_required=False)
    flags_v1.AddKeyAlgorithmFlag(
        key_spec_group, default='rsa-pkcs1-2048-sha256')
    flags_v1.AddUsePresetProfilesFlag(x509_config_group)
    # Subordinates should have no children by default.
    flags_v1.AddInlineX509ParametersFlags(
        x509_config_group, is_ca_command=True, default_max_chain_length=0)
    flags_v1.AddValidityFlag(
        parser,
        resource_name='CA',
        default_value='P3Y',
        default_value_text='3 years')
    labels_util.AddCreateLabelsFlags(parser)
    flags_v1.AddBucketFlag(parser)

    offline_issuer_group = issuer_configuration_group.add_group(
        help=('If the issuing CA is not hosted on Private CA, you must provide '
              'these settings:'))
    base.Argument(
        '--create-csr',
        help=('Indicates that a CSR should be generated which can be signed by '
              'the issuing CA. This must be set if --issuer is not provided.'),
        action='store_const',
        const=True,
        default=False,
        required=True).AddToParser(offline_issuer_group)
    base.Argument(
        '--csr-output-file',
        help=('The path where the resulting PEM-encoded CSR file should be '
              'written.'),
        required=True).AddToParser(offline_issuer_group)
    flags_v1.AddAutoEnableFlag(parser)