def testValidEndpointOverride(self):
     properties.PersistProperty(
         properties.VALUES.api_endpoint_overrides.compute,
         'http://localhost:8787/v1beta1/')
     properties.PersistProperty(
         properties.VALUES.api_endpoint_overrides.compute,
         'https://test-endpoint.sandbox.googleapis.com/')
示例#2
0
  def LoginAs(self, account, creds, project, activate, brief):
    """Logs in with valid credentials."""
    if not activate:
      return creds
    properties.PersistProperty(properties.VALUES.core.account, account)
    if project:
      properties.PersistProperty(properties.VALUES.core.project, project)

    google_creds = client.GoogleCredentials(
        creds.access_token, creds.client_id, creds.client_secret,
        creds.refresh_token, creds.token_expiry, creds.token_uri,
        creds.user_agent, creds.revoke_uri)
    try:
      auth_util.CreateWellKnownFileDir()
      client.save_to_well_known_file(google_creds)
    except IOError as e:
      raise c_exc.ToolException(
          'error saving Application Default Credentials: ' + str(e))
    if not brief:
      log.status.write('Saved Application Default Credentials.\n')
      log.warning(
          '`gcloud auth login` will stop writing application default '
          'credentials\nin a future release. See:\n    '
          'https://developers.google.com/identity/protocols/'
          'application-default-credentials#toolcloudsdk'
          '\nfor more information.')

    if not brief:
      log.status.write(
          '\nYou are now logged in as [{account}].\n'
          'Your current project is [{project}].  You can change this setting '
          'by running:\n  $ gcloud config set project PROJECT_ID\n'.format(
              account=account, project=properties.VALUES.core.project.Get()))
    return creds
示例#3
0
 def LoginAs(self, account, creds, project, activate, brief):
   """Logs in with valid credentials."""
   if not activate:
     return creds
   properties.PersistProperty(properties.VALUES.core.account, account)
   if project:
     properties.PersistProperty(properties.VALUES.core.project, project)
   if not config.Paths().workspace_dir:
     google_creds = client.GoogleCredentials(
         creds.access_token, creds.client_id, creds.client_secret,
         creds.refresh_token, creds.token_expiry, creds.token_uri,
         creds.user_agent, creds.revoke_uri)
     try:
       client.save_to_well_known_file(google_creds)
     except IOError as e:
       raise c_exc.ToolException(
           'error saving Application Default Credentials: ' + str(e))
     if not brief:
       log.status.write('Saved Application Default Credentials.\n')
   if not brief:
     log.status.write(
         '\nYou are now logged in as [{account}].\n'
         'Your current project is [{project}].  You can change this setting '
         'by running:\n  $ gcloud config set project PROJECT_ID\n'.format(
             account=account, project=properties.VALUES.core.project.Get()))
   return creds
def LoginAs(account, creds, project, activate, brief, update_adc,
            add_quota_project_to_adc):
    """Logs in with valid credentials."""
    _ValidateADCFlags(update_adc, add_quota_project_to_adc)
    if update_adc:
        _UpdateADC(creds, add_quota_project_to_adc)
    if not activate:
        return creds
    properties.PersistProperty(properties.VALUES.core.account, account)
    if project:
        properties.PersistProperty(properties.VALUES.core.project, project)

    if not brief:
        if c_creds.IsExternalAccountCredentials(creds):
            confirmation_msg = (
                'Authenticated with external account credentials for: [{0}].'.
                format(account))
        elif c_creds.IsExternalAccountUserCredentials(creds):
            confirmation_msg = (
                'Authenticated with external account user credentials for: '
                '[{0}].'.format(account))
        elif c_creds.IsServiceAccountCredentials(creds):
            confirmation_msg = (
                'Authenticated with service account credentials for: [{0}].'.
                format(account))
        else:
            confirmation_msg = 'You are now logged in as [{0}].'.format(
                account)
        log.status.write(
            '\n{confirmation_msg}\n'
            'Your current project is [{project}].  You can change this setting '
            'by running:\n  $ gcloud config set project PROJECT_ID\n'.format(
                confirmation_msg=confirmation_msg,
                project=properties.VALUES.core.project.Get()))
    return creds
def SetGcloudProxyProperties(proxy_type=None, address=None, port=None,
                             username=None, password=None):
  """Sets proxy group properties; clears any property not explicitly set."""
  properties.PersistProperty(properties.VALUES.proxy.proxy_type, proxy_type)
  properties.PersistProperty(properties.VALUES.proxy.address, address)
  properties.PersistProperty(properties.VALUES.proxy.port, port)
  properties.PersistProperty(properties.VALUES.proxy.username, username)
  properties.PersistProperty(properties.VALUES.proxy.password, password)
 def testValidBool(self):
     # Check that values expected to be valid don't throw an InvalidValueError
     properties.PersistProperty(properties.VALUES.core.disable_prompts,
                                True)
     properties.PersistProperty(properties.VALUES.core.disable_prompts,
                                'on')
     properties.PersistProperty(properties.VALUES.core.disable_prompts, 0)
     properties.PersistProperty(properties.VALUES.core.disable_prompts,
                                'no')
     properties.PersistProperty(properties.VALUES.core.disable_prompts,
                                'FALSE')
  def Run(self, args):
    """Create service account credentials."""

    try:
      private_key = open(args.key_file).read()
    except IOError as e:
      raise c_exc.BadFileException(e)

    password = None
    if args.password_file:
      try:
        password = open(args.password_file).read().strip()
      except IOError as e:
        raise c_exc.UnknownArgumentException('--password-file', e)
    if args.prompt_for_password:
      password = getpass.getpass('Password: '******'CLOUDSDK_PYTHON_SITEPACKAGES'):
        raise c_exc.ToolException(
            ('PyOpenSSL is not available. If you have already installed '
             'PyOpenSSL, you will need to enable site packages by '
             'setting the environment variable CLOUDSDK_PYTHON_SITEPACKAGES to '
             '1. If that does not work, See '
             'https://developers.google.com/cloud/sdk/crypto for details.'))
      else:
        raise c_exc.ToolException(
            ('PyOpenSSL is not available. See '
             'https://developers.google.com/cloud/sdk/crypto for details.'))

    if password:
      cred = client.SignedJwtAssertionCredentials(
          service_account_name=args.account,
          private_key=private_key,
          scope=config.CLOUDSDK_SCOPES,
          private_key_password=password,
          user_agent=config.CLOUDSDK_USER_AGENT)
    else:
      cred = client.SignedJwtAssertionCredentials(
          service_account_name=args.account,
          private_key=private_key,
          scope=config.CLOUDSDK_SCOPES,
          user_agent=config.CLOUDSDK_USER_AGENT)

    c_store.Store(cred, args.account)

    properties.PersistProperty(properties.VALUES.core.account, args.account)

    project = args.project
    if project:
      properties.PersistProperty(properties.VALUES.core.project, project)

    return cred
    def testProject(self):
        """Make sure the project gets set."""
        project_prop = properties.VALUES.core.project
        account_prop = properties.VALUES.core.account
        properties.PersistProperty(project_prop, None)
        properties.PersistProperty(account_prop, None)

        json_key_file = self._GetTestDataPathFor(
            'inactive_service_account.json')
        self.Run('--project=junkproj auth activate-service-account {account} '
                 '--key-file={key_file} '.format(
                     account=_SERVICE_ACCOUNT_EMAIL, key_file=json_key_file))
        self.assertEqual('junkproj', project_prop.Get())
        self.assertEqual(_SERVICE_ACCOUNT_EMAIL, account_prop.Get())
    def testPersistScopes(self):
        self.StartPropertyPatch(config.Paths,
                                'sdk_root',
                                return_value=self.temp_path)

        prop = Prop('foo', 'bar')

        self.CheckProperty(prop, properties.Scope.USER)
        self.CheckProperty(prop, properties.Scope.INSTALLATION)
        self.assertFalse(os.path.isfile(config.Paths().config_sentinel_file))

        properties.PersistProperty(prop, '2', properties.Scope.USER)
        self.CheckProperty(prop, properties.Scope.USER, value='2')
        self.CheckProperty(prop, properties.Scope.INSTALLATION)
        self.assertEqual(prop.Get(), '2')
        self.assertTrue(os.path.isfile(config.Paths().config_sentinel_file))
        os.remove(config.Paths().config_sentinel_file)
        self.assertFalse(os.path.isfile(config.Paths().config_sentinel_file))

        properties.PersistProperty(prop, '3', properties.Scope.INSTALLATION)
        self.CheckProperty(prop, properties.Scope.USER, value='2')
        self.CheckProperty(prop, properties.Scope.INSTALLATION, value='3')
        self.assertEqual(prop.Get(), '2')
        self.assertTrue(os.path.isfile(config.Paths().config_sentinel_file))

        if not self.IsOnWindows():
            # Apparently readonly does not work how you would expect on Windows.
            # There does not seem to be an easy way to make a directory non-writable
            # from Python.
            try:
                os.chmod(self.temp_path, 0o400)
                with self.assertRaisesRegex(
                        exceptions.RequiresAdminRightsError,
                        'you do not have permission to modify the Google Cloud SDK '
                        'installation directory'):
                    properties.PersistProperty(prop, '4',
                                               properties.Scope.INSTALLATION)
            finally:
                os.chmod(self.temp_path, 0o755)

        properties.PersistProperty(prop, '4')
        self.CheckProperty(prop, properties.Scope.USER, value='4')
        self.CheckProperty(prop, properties.Scope.INSTALLATION, value='3')
        self.assertEqual(prop.Get(), '4')

        properties.PersistProperty(prop, None)
        self.CheckProperty(prop, properties.Scope.USER)
        self.CheckProperty(prop, properties.Scope.INSTALLATION, value='3')
        self.assertEqual(prop.Get(), '3')
  def testDifferentProjectForBilling_SetProperty(self):

    properties.PersistProperty(properties.VALUES.billing.quota_project,
                               'billing_project_in_property',
                               properties.Scope.USER)
    try:
      self.Run('iot registries list --region=us-central1 --project fake-project'
               ' --billing-project billing_project_in_flag')
    finally:
      properties.PersistProperty(properties.VALUES.billing.quota_project, None,
                                 properties.Scope.USER)

    project_override_header = self.request_mock.call_args[1]['headers'][
        b'X-Goog-User-Project']
    self.assertEqual(project_override_header, b'billing_project_in_flag')
示例#11
0
    def testDifferentProjectForBilling_SetProperty(self):

        properties.PersistProperty(properties.VALUES.billing.quota_project,
                                   'billing_project_in_property',
                                   properties.Scope.USER)
        try:
            self.Run('asset export --project fake-project '
                     '--output-path=gs://my-bucket/my-object '
                     '--billing-project billing_project_in_flag')
        finally:
            properties.PersistProperty(properties.VALUES.billing.quota_project,
                                       None, properties.Scope.USER)

        project_override_header = self.request_mock.call_args[0][4][
            b'X-Goog-User-Project']
        self.assertEqual(project_override_header, b'billing_project_in_flag')
 def testProjectIsSet(self):
     # Test that the arg is recognized.
     self.assertEqual(self.cli.Execute(['command1', '--trace-email=foo']),
                      'foo')
     # Test that if the arg is not set, we read the workspace properties.
     properties.PersistProperty(properties.VALUES.core.trace_email, 'bar')
     self.assertEqual(self.cli.Execute(['command1']), 'bar')
示例#13
0
  def Run(self, args):
    scope = (properties.Scope.INSTALLATION if args.installation
             else properties.Scope.USER)

    prop = properties.FromString(args.property)
    if not prop:
      raise c_exc.InvalidArgumentException(
          'property', 'Must be in the form: [SECTION/]PROPERTY')

    scope_msg = ''
    if args.installation:
      scope_msg = 'installation '

    if prop == properties.VALUES.context_aware.use_client_certificate:
      config_validators.WarnIfActivateUseClientCertificate(args.value)

    showed_warning = False
    if prop == properties.VALUES.core.project:
      showed_warning = config_validators.WarnIfSettingProjectWithNoAccess(
          scope, args.value)
    if prop == properties.VALUES.compute.zone:
      showed_warning = config_validators.WarnIfSettingNonExistentRegionZone(
          args.value, zonal=True)
    if prop == properties.VALUES.compute.region:
      showed_warning = config_validators.WarnIfSettingNonExistentRegionZone(
          args.value, zonal=False)
    if showed_warning and not args.quiet and console_io.CanPrompt():
      if not console_io.PromptContinue(
          'Are you sure you wish to set {0}property [{1}] to {2}?'.format(
              scope_msg, prop, args.value)):
        return

    properties.PersistProperty(prop, args.value, scope=scope)
    log.status.Print('Updated {0}property [{1}].'.format(scope_msg, prop))
示例#14
0
def Prompts(usage_reporting):
    """Display prompts to opt out of usage reporting.

  Args:
    usage_reporting: bool, If True, enable usage reporting. If None, ask.
  """

    if config.InstallationConfig.Load().IsAlternateReleaseChannel():
        usage_reporting = True
        print("""
Usage reporting is always on for alternate release channels.
""")
        return

    if usage_reporting is None:
        print("""
The Google Cloud SDK is currently in developer preview. To help improve the
quality of this product, we collect anonymized data on how the SDK is used.
You may choose to opt out of this collection now (by choosing 'N' at the below
prompt), or at any time in the future by running the following command:
    gcloud config set --scope=user disable_usage_reporting true
""")

        usage_reporting = console_io.PromptContinue(
            prompt_string='Do you want to help improve the Google Cloud SDK')
    properties.PersistProperty(properties.VALUES.core.disable_usage_reporting,
                               not usage_reporting,
                               scope=properties.Scope.INSTALLATION)
示例#15
0
  def Run(self, args):
    """Revoke credentials and update active account."""
    accounts = args.accounts or []
    if type(accounts) is str:
      accounts = [accounts]
    available_accounts = c_store.AvailableAccounts()
    unknown_accounts = set(accounts) - set(available_accounts)
    if unknown_accounts:
      raise c_exc.UnknownArgumentException(
          'accounts', ' '.join(unknown_accounts))
    if args.all:
      accounts = available_accounts

    active_account = properties.VALUES.core.account.Get()

    if not accounts and active_account:
      accounts = [active_account]

    if not accounts:
      raise c_exc.InvalidArgumentException(
          'accounts', 'No credentials available to revoke.')

    for account in accounts:
      if active_account == account:
        properties.PersistProperty(properties.VALUES.core.account, None)
      if not c_store.Revoke(account):
        log.warning(
            '[{}] already inactive (previously revoked?)'.format(account))
    return accounts
示例#16
0
 def UnsetProject(self):
   """Set core/project property to None."""
   # Due to a weird interaction with the self.Project() setup in CliTestBase,
   # both of these are required to reset the project property to None.
   properties.PersistProperty(properties.VALUES.core.project, None,
                              properties.Scope.USER)
   properties.VALUES.core.project.Set(None)
示例#17
0
 def RunWithoutProject(self, cmd, track=None):
     """Test the command without a set project."""
     # Remove project.
     properties.PersistProperty(properties.VALUES.core.project, None)
     # We don't care what type of exception is raised here.
     with self.assertRaisesRegex(Exception, NO_PROJECT_REGEXP):
         self.RunTrace(cmd, track)
示例#18
0
    def Run(self, args):
        scope = (properties.Scope.INSTALLATION
                 if args.installation else properties.Scope.USER)

        prop = properties.FromString(args.property)
        if not prop:
            raise c_exc.InvalidArgumentException(
                'property', 'Must be in the form: [SECTION/]PROPERTY')
        properties.PersistProperty(prop, args.value, scope=scope)

        scope_msg = ''
        if args.installation:
            scope_msg = 'installation '
        log.status.Print('Updated {0}property [{1}].'.format(scope_msg, prop))

        if prop == properties.VALUES.core.project:
            config_validators.WarnIfSettingProjectWithNoAccess(
                scope, prop.Get())
        if prop == properties.VALUES.context_aware.use_client_certificate:
            config_validators.WarnIfActivateUseClientCertificate(prop)
        if prop == properties.VALUES.compute.zone:
            config_validators.WarnIfSettingNonExistentRegionZone(prop.Get(),
                                                                 zonal=True)
        if prop == properties.VALUES.compute.region:
            config_validators.WarnIfSettingNonExistentRegionZone(prop.Get(),
                                                                 zonal=False)
 def testPersistErrors(self):
     self.StartPropertyPatch(config.Paths, 'sdk_root', return_value=None)
     prop = Prop('foo', 'bar')
     with self.assertRaises(properties.MissingInstallationConfig):
         properties.PersistProperty(prop,
                                    '1',
                                    scope=properties.Scope.INSTALLATION)
示例#20
0
    def testRunDeviceCompleterWithPresentationKwargs(self):
        properties.VALUES.core.project.Set(None)
        properties.PersistProperty(properties.VALUES.core.project, None,
                                   properties.Scope.USER)
        self._ExpectListProjects(['p0', 'p1'])
        self._ExpectListRegistries(self._MakeRegistries(n=2, project='p0'),
                                   project='p0')
        self._ExpectListRegistries(self._MakeRegistries(n=1, project='p1'),
                                   project='p1')
        self._ExpectListDevices(self._MakeDevices(n=2, registry='r0'),
                                field_mask='name',
                                project='p0',
                                registry='r0')
        self._ExpectListDevices(self._MakeDevices(n=2, registry='r1'),
                                field_mask='name',
                                project='p0',
                                registry='r1')
        self._ExpectListDevices(self._MakeDevices(n=1, registry='r0'),
                                field_mask='name',
                                project='p1',
                                registry='r0')
        self.WriteInput(' \n')
        self.Run(
            'meta cache completers run --resource-spec-path {} '
            '--resource-presentation-kwargs prefixes=True --attribute device {} '
            '--device-region us-central1'.format(self.device_spec_path,
                                                 self.resource_completer_path))
        self.AssertOutputEquals("""\
d0:r0:us-central1:p0
d1:r0:us-central1:p0
d0:r1:us-central1:p0
d1:r1:us-central1:p0
d0:r0:us-central1:p1
""")
示例#21
0
    def testRunDeviceCompleterWithFlagNameOverrides(self):
        properties.VALUES.core.project.Set(None)
        properties.PersistProperty(properties.VALUES.core.project, None,
                                   properties.Scope.USER)
        self._ExpectListProjects(['p0', 'p1'])
        self._ExpectListRegistries(self._MakeRegistries(n=2, project='p0'),
                                   project='p0')
        self._ExpectListRegistries(self._MakeRegistries(n=1, project='p1'),
                                   project='p1')
        self._ExpectListDevices(self._MakeDevices(n=2, registry='r0'),
                                field_mask='name',
                                project='p0',
                                registry='r0')
        self._ExpectListDevices(self._MakeDevices(n=2, registry='r1'),
                                field_mask='name',
                                project='p0',
                                registry='r1')
        self._ExpectListDevices(self._MakeDevices(n=1, registry='r0'),
                                field_mask='name',
                                project='p1',
                                registry='r0')
        self.WriteInput(' \n')
        self.Run(
            'meta cache completers run --resource-spec-path {} --attribute device '
            '--resource-presentation-kwargs flag_name_overrides='
            'project:--funky-project-flag;registry:--registry-flag {} {}'.
            format(self.device_spec_path, self.resource_completer_path,
                   self.region_flag))
        self.AssertOutputEquals("""\
d0:r0:us-central1:p0
d1:r0:us-central1:p0
d0:r1:us-central1:p0
d1:r1:us-central1:p0
d0:r0:us-central1:p1
""")
示例#22
0
    def testRunDeviceCompleter(self):
        properties.VALUES.core.project.Set(None)
        properties.PersistProperty(properties.VALUES.core.project, None,
                                   properties.Scope.USER)
        self._ExpectListProjects(['p0', 'p1'])
        self._ExpectListRegistries(self._MakeRegistries(n=2, project='p0'),
                                   project='p0')
        self._ExpectListRegistries(self._MakeRegistries(n=1, project='p1'),
                                   project='p1')
        self._ExpectListDevices(self._MakeDevices(n=2, registry='r0'),
                                field_mask='name',
                                project='p0',
                                registry='r0')
        self._ExpectListDevices(self._MakeDevices(n=2, registry='r1'),
                                field_mask='name',
                                project='p0',
                                registry='r1')
        self._ExpectListDevices(self._MakeDevices(n=1, registry='r0'),
                                field_mask='name',
                                project='p1',
                                registry='r0')
        self.WriteInput(' \n')
        self.Run(
            'meta cache completers run --resource-spec-path {} --attribute device '
            '{} {}'.format(self.device_spec_path, self.resource_completer_path,
                           self.region_flag))
        self.AssertOutputEquals("""\
d0 --project=p0 --registry=r0
d1 --project=p0 --registry=r0
d0 --project=p0 --registry=r1
d1 --project=p0 --registry=r1
d0 --project=p1 --registry=r0
""")
示例#23
0
文件: init.py 项目: txl302/RA-project
 def SetProperty(name, default_value, list_command):
   """Set named compute property to default_value or get via list command."""
   if not default_value:
     values = self._RunCmd(list_command)
     if values is None:
       return
     values = list(values)
     message = (
         'Which Google Compute Engine {0} would you like to use as project '
         'default?\n'
         'If you do not specify a {0} via a command line flag while working '
         'with Compute Engine resources, the default is assumed.').format(
             name)
     idx = console_io.PromptChoice(
         [value['name'] for value in values]
         + ['Do not set default {0}'.format(name)],
         message=message, prompt_string=None, allow_freeform=True,
         freeform_suggester=usage_text.TextChoiceSuggester())
     if idx is None or idx == len(values):
       return
     default_value = values[idx]
   properties.PersistProperty(properties.VALUES.compute.Property(name),
                              default_value['name'])
   log.status.write('Your project default Compute Engine {0} has been set '
                    'to [{1}].\nYou can change it by running '
                    '[gcloud config set compute/{0} NAME].\n\n'
                    .format(name, default_value['name']))
   return default_value
示例#24
0
def Prompts(usage_reporting):
    """Display prompts to opt out of usage reporting.

  Args:
    usage_reporting: bool, If True, enable usage reporting. If None, check
    the environmental variable. If None, check if its alternate release channel.
    If not, ask.
  """

    if usage_reporting is None:
        if os.environ.get('CLOUDSDK_CORE_DISABLE_USAGE_REPORTING') is not None:
            usage_reporting = not os.environ.get(
                'CLOUDSDK_CORE_DISABLE_USAGE_REPORTING')
        else:
            if config.InstallationConfig.Load().IsAlternateReleaseChannel():
                usage_reporting = True
                print("""
    Usage reporting is always on for alternate release channels.
    """)
            else:
                print("""
To help improve the quality of this product, we collect anonymized data on how
the SDK is used. You may choose to opt out of this collection now (by choosing
'N' at the below prompt), or at any time in the future by running the following
command:
    gcloud config set disable_usage_reporting true
""")

                usage_reporting = console_io.PromptContinue(
                    prompt_string=
                    'Do you want to help improve the Google Cloud SDK')
    properties.PersistProperty(properties.VALUES.core.disable_usage_reporting,
                               not usage_reporting,
                               scope=properties.Scope.INSTALLATION)
示例#25
0
  def Run(self, args):
    """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Some value that we want to have printed later.
    """
    adapter = self.context['api_adapter']

    cluster_refs = []
    for name in args.names:
      cluster_refs.append(adapter.ParseCluster(name))

    console_io.PromptContinue(
        message=util.ConstructList(
            'The following clusters will be deleted.',
            ['[{name}] in [{zone}]'.format(name=ref.clusterId,
                                           zone=adapter.Zone(ref))
             for ref in cluster_refs]),
        throw_if_unattended=True,
        cancel_on_no=True)

    operations = []
    errors = []
    # Issue all deletes first
    for cluster_ref in cluster_refs:
      try:
        # Make sure it exists (will raise appropriate error if not)
        adapter.GetCluster(cluster_ref)

        op_ref = adapter.DeleteCluster(cluster_ref)
        operations.append((op_ref, cluster_ref))
      except exceptions.HttpError as error:
        errors.append(util.GetError(error))
      except util.Error as error:
        errors.append(error)
    if not flags.GetAsyncValueFromAsyncAndWaitFlags(args.async, args.wait):
      # Poll each operation for completion
      for operation_ref, cluster_ref in operations:
        try:
          adapter.WaitForOperation(
              operation_ref,
              'Deleting cluster {0}'.format(cluster_ref.clusterId),
              timeout_s=args.timeout)
          # Purge cached config files
          util.ClusterConfig.Purge(cluster_ref.clusterId,
                                   adapter.Zone(cluster_ref),
                                   cluster_ref.projectId)
          if properties.VALUES.container.cluster.Get() == cluster_ref.clusterId:
            properties.PersistProperty(
                properties.VALUES.container.cluster, None)
          log.DeletedResource(cluster_ref)
        except exceptions.HttpError as error:
          errors.append(util.GetError(error))
        except util.Error as error:
          errors.append(error)
示例#26
0
def LoginAs(account, creds, project, activate, brief, update_adc):
    """Logs in with valid credentials."""
    if update_adc:
        _UpdateADC(creds)
    if not activate:
        return creds
    properties.PersistProperty(properties.VALUES.core.account, account)
    if project:
        properties.PersistProperty(properties.VALUES.core.project, project)

    if not brief:
        log.status.write(
            '\nYou are now logged in as [{account}].\n'
            'Your current project is [{project}].  You can change this setting '
            'by running:\n  $ gcloud config set project PROJECT_ID\n'.format(
                account=account, project=properties.VALUES.core.project.Get()))
    return creds
示例#27
0
 def SetUp(self):
     properties.PersistProperty(properties.VALUES.core.account, 'junk')
     self.mock_accounts = self.StartObjectPatch(store,
                                                'AvailableAccounts',
                                                autospec=True)
     self.mock_revoke = self.StartObjectPatch(store,
                                              'Revoke',
                                              autospec=True)
 def testInvalidBool(self):
     regex = (
         r'The \[disable_prompts\] value \[str\] is not valid. '
         r'Possible values: \[true, 1, on, yes, y, false, 0, off, no, n, '
         r'\'\', none\]. \(See http://yaml.org/type/bool.html\)')
     with self.assertRaisesRegex(properties.InvalidValueError, regex):
         properties.PersistProperty(properties.VALUES.core.disable_prompts,
                                    'str')
示例#29
0
def RunUnset(cmd, args):
    """Unsets a property."""
    prop = properties.FromString(args.property)
    if not prop:
        raise c_exc.InvalidArgumentException(
            'property', 'Must be in the form: [SECTION/]PROPERTY')
    properties.PersistProperty(prop,
                               None,
                               scope=cmd.group.RequestedScope(args))
示例#30
0
    def Run(self, args):
        scope = (properties.Scope.INSTALLATION
                 if args.installation else properties.Scope.USER)

        prop = properties.FromString(args.property)
        if not prop:
            raise c_exc.InvalidArgumentException(
                'property', 'Must be in the form: [SECTION/]PROPERTY')
        properties.PersistProperty(prop, args.value, scope=scope)