コード例 #1
0
  def Run(self, args):
    """Create service account credentials."""

    file_content, is_json = _IsJsonFile(args.key_file)
    if is_json:
      cred = auth_service_account.CredentialsFromAdcDict(file_content)
      if args.password_file or args.prompt_for_password:
        raise c_exc.InvalidArgumentException(
            '--password-file',
            'A .json service account key does not require a password.')
      account = cred.service_account_email
      if args.account and args.account != account:
        raise c_exc.InvalidArgumentException(
            'ACCOUNT',
            'The given account name does not match the account name in the key '
            'file.  This argument can be omitted when using .json keys.')
    else:
      account = args.account
      if not account:
        raise c_exc.RequiredArgumentException(
            'ACCOUNT', 'An account is required when using .p12 keys')
      password = None
      if args.password_file:
        try:
          with open(args.password_file) as f:
            password = f.read().strip()
        except IOError as e:
          raise c_exc.UnknownArgumentException('--password-file', e)
      elif args.prompt_for_password:
        password = getpass.getpass('Password: '******'Failed to activate the given service account. '
          'Please ensure provided key file is valid.')

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

    log.status.Print('Activated service account credentials for: [{0}]'
                     .format(account))
コード例 #2
0
def SetScanConfigAuth(unused_ref, args, request):
    """Modify request hook to set scan config details.

  Args:
    unused_ref: not used parameter to modify request hooks
    args: Parsed args namespace
    request: The partially filled request object.

  Returns:
    Request object with Authentication message filled out.
  """
    c = wss_base.WebSecurityScannerCommand()
    if args.auth_type is None:
        if any([args.auth_user, args.auth_password, args.auth_url]):
            raise exceptions.RequiredArgumentException(
                '--auth-type', 'Required when setting authentication flags.')
        return request

    if args.auth_type == 'none':
        if any([args.auth_user, args.auth_password, args.auth_url]):
            raise exceptions.InvalidArgumentException(
                '--auth-type',
                'No other auth flags can be set with --auth-type=none')
        return request

    if request.scanConfig is None:
        request.scanConfig = c.messages.ScanConfig()
    request.scanConfig.authentication = c.messages.Authentication()
    if args.auth_type == 'google':
        _RequireAllFlagsOrRaiseForAuthType(args,
                                           ['auth_user', 'auth_password'],
                                           'google')
        request.scanConfig.authentication.googleAccount = c.messages.GoogleAccount(
            username=args.auth_user, password=args.auth_password)
    elif args.auth_type == 'custom':
        _RequireAllFlagsOrRaiseForAuthType(
            args, ['auth_user', 'auth_password', 'auth_url'], 'custom')
        request.scanConfig.authentication.customAccount = c.messages.CustomAccount(
            username=args.auth_user,
            password=args.auth_password,
            loginUrl=args.auth_url)
    else:
        raise exceptions.UnknownArgumentException('--auth-type',
                                                  args.auth_type)

    return request
コード例 #3
0
ファイル: revoke.py プロジェクト: bopopescu/gcloud_cli
    def Run(self, args):
        """Revoke credentials and update active account."""
        accounts = args.accounts or []
        if isinstance(accounts, 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,
                                  use_google_auth=not args.use_oauth2client):
                if account.endswith('.gserviceaccount.com'):
                    log.warning(
                        '[{}] appears to be a service account. Service account tokens '
                        'cannot be revoked, but they will expire automatically. To '
                        'prevent use of the service account token earlier than the '
                        'expiration, revoke the parent service account or service '
                        'account key.'.format(account))
                else:
                    log.warning(
                        '[{}] already inactive (previously revoked?)'.format(
                            account))
        return accounts
コード例 #4
0
def _GetDefaultsFromAndroidCatalog(catalog):
    """Builds a default dimensions dictionary using the environment catalog.

  Args:
    catalog: the Android environment catalog.

  Returns:
    A dictionary containing the default dimensions. If there is more than one
    dimension value marked as default (a bug), the first one found is used.
    Return value is formatted to be used with _ApplyLowerPriorityArgs.

  Raises:
    exceptions.UnknownArgumentException: if the default argument could not be
      detected from the catalog response.
  """
    catalog_by_dimension = {
        'device_ids': catalog.models,
        'os_version_ids': catalog.versions,
        'locales': catalog.runtimeConfiguration.locales,
        'orientations': catalog.runtimeConfiguration.orientations
    }
    defaults = {
        'device_ids': None,
        'os_version_ids': None,
        'locales': None,
        'orientations': None
    }

    for dimension_name in catalog_by_dimension:
        for dimension in catalog_by_dimension[dimension_name]:
            if 'default' in dimension.tags:
                defaults[dimension_name] = [dimension.id]
                break
        if defaults[dimension_name] is None:
            raise exceptions.UnknownArgumentException(
                dimension_name,
                'Testing service failed to provide a default argument.')

    return defaults
コード例 #5
0
def ListDenyPolicies(resource_id, resource_type, release_track):
    """Gets the IAM Deny policies for an organization.

  Args:
    resource_id: id for the resource
    resource_type: what type of a resource the id represents. Either
      organization, project, or folder
    release_track: ALPHA or BETA, GA not supported

  Returns:
    The output from the ListPolicies API call for deny policies for the passed
    resource.
  """

    client = GetClientInstance(release_track)
    messages = GetMessagesModule(release_track)
    policies_to_return = []

    if resource_type in ['organization', 'folder', 'project']:

        attachment_point = 'policies/cloudresourcemanager.googleapis.com%2F{}s%2F{}/denypolicies'.format(
            resource_type, resource_id)

        policies_to_fetch = client.policies.ListPolicies(
            messages.IamPoliciesListPoliciesRequest(
                parent=attachment_point)).policies

        for policy_metadata in policies_to_fetch:
            policy = client.policies.Get(
                messages.IamPoliciesGetRequest(name=policy_metadata.name))
            policies_to_return.append(policy)

        return policies_to_return

    raise gcloud_exceptions.UnknownArgumentException('resource_type',
                                                     resource_type)
コード例 #6
0
  def Run(self, args):
    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
    client = holder.client
    messages = holder.client.messages

    instance_ref = instances_flags.INSTANCE_ARG.ResolveAsResource(
        args,
        holder.resources,
        scope_lister=flags.GetDefaultScopeLister(holder.client))

    instance = client.apitools_client.instances.Get(
        messages.ComputeInstancesGetRequest(**instance_ref.AsDict()))
    for i in instance.networkInterfaces:
      if i.name == args.network_interface:
        break
    else:
      raise exceptions.UnknownArgumentException(
          'network-interface',
          'Instance does not have a network interface [{}], '
          'present interfaces are [{}].'.format(
              args.network_interface,
              ', '.join([i.name for i in instance.networkInterfaces])))

    request = messages.ComputeInstancesGetEffectiveFirewallsRequest(
        project=instance_ref.project,
        instance=instance_ref.instance,
        zone=instance_ref.zone,
        networkInterface=args.network_interface)
    res = client.apitools_client.instances.GetEffectiveFirewalls(request)
    org_firewall = []
    network_firewall = []
    org_firewall_policy = []
    all_firewall_policy = []

    if hasattr(res, 'firewalls'):
      network_firewall = firewalls_utils.SortNetworkFirewallRules(
          client, res.firewalls)

    if hasattr(res, 'firewallPolicys') and res.firewallPolicys:
      for fp in res.firewallPolicys:
        firewall_policy_rule = firewalls_utils.SortFirewallPolicyRules(
            client, fp.rules)
        if (fp.type == client.messages
            .InstancesGetEffectiveFirewallsResponseEffectiveFirewallPolicy
            .TypeValueValuesEnum.HIERARCHY):
          fp_response = (
              client.messages
              .InstancesGetEffectiveFirewallsResponseEffectiveFirewallPolicy(
                  name=fp.name, rules=firewall_policy_rule))
          org_firewall_policy.append(fp_response)
          all_firewall_policy.append(fp_response)
    elif hasattr(res, 'organizationFirewalls'):
      for sp in res.organizationFirewalls:
        org_firewall_rule = firewalls_utils.SortOrgFirewallRules(
            client, sp.rules)
        org_firewall.append(
            client.messages
            .InstancesGetEffectiveFirewallsResponseOrganizationFirewallPolicy(
                id=sp.id, rules=org_firewall_rule))

    if args.IsSpecified('format') and args.format == 'json':
      return client.messages.InstancesGetEffectiveFirewallsResponse(
          organizationFirewalls=org_firewall,
          firewalls=network_firewall,
          firewallPolicys=all_firewall_policy)

    result = []
    for fp in org_firewall_policy:
      result.extend(
          firewalls_utils.ConvertFirewallPolicyRulesToEffectiveFwRules(fp))
    for sp in org_firewall:
      result.extend(
          firewalls_utils.ConvertOrgSecurityPolicyRulesToEffectiveFwRules(sp))
    result.extend(
        firewalls_utils.ConvertNetworkFirewallRulesToEffectiveFwRules(
            network_firewall))
    return result
コード例 #7
0
ファイル: subnets_utils.py プロジェクト: bopopescu/my-to-do
def MakeSubnetworkUpdateRequest(
        client,
        subnet_ref,
        include_alpha_logging,
        enable_private_ip_google_access=None,
        add_secondary_ranges=None,
        remove_secondary_ranges=None,
        enable_flow_logs=None,
        aggregation_interval=None,
        flow_sampling=None,
        metadata=None,
        set_role_active=None,
        drain_timeout_seconds=None,
        enable_private_ipv6_access=None,
        private_ipv6_google_access_type=None,
        private_ipv6_google_access_service_accounts=None):
    """Make the appropriate update request for the args.

  Args:
    client: GCE API client
    subnet_ref: Reference to a subnetwork
    include_alpha_logging: Include alpha-specific logging args.
    enable_private_ip_google_access: Enable/disable access to Google Cloud APIs
      from this subnet for instances without a public ip address.
    add_secondary_ranges: List of secondary IP ranges to add to the subnetwork
      for use in IP aliasing.
    remove_secondary_ranges: List of secondary ranges to remove from the
      subnetwork.
    enable_flow_logs: Enable/disable flow logging for this subnet.
    aggregation_interval: The internal at which to aggregate flow logs.
    flow_sampling: The sampling rate for flow logging in this subnet.
    metadata: Whether metadata fields should be added reported flow logs.
    set_role_active: Updates the role of a BACKUP subnet to ACTIVE.
    drain_timeout_seconds: The maximum amount of time to drain connections from
      the active subnet to the backup subnet with set_role_active=True.
    enable_private_ipv6_access: Enable/disable private IPv6 access for the
      subnet.
    private_ipv6_google_access_type: The private IPv6 google access type for the
      VMs in this subnet.
    private_ipv6_google_access_service_accounts: The service accounts can be
      used to selectively turn on Private IPv6 Google Access only on the VMs
      primary service account matching the value.

  Returns:
    response, result of sending the update request for the subnetwork
  """
    convert_to_enum = lambda x: x.replace('-', '_').upper()
    if enable_private_ip_google_access is not None:
        google_access = (
            client.messages.SubnetworksSetPrivateIpGoogleAccessRequest())
        google_access.privateIpGoogleAccess = enable_private_ip_google_access

        google_access_request = (
            client.messages.ComputeSubnetworksSetPrivateIpGoogleAccessRequest(
                project=subnet_ref.project,
                region=subnet_ref.region,
                subnetwork=subnet_ref.Name(),
                subnetworksSetPrivateIpGoogleAccessRequest=google_access))
        return client.MakeRequests([
            (client.apitools_client.subnetworks, 'SetPrivateIpGoogleAccess',
             google_access_request)
        ])
    elif add_secondary_ranges is not None:
        subnetwork = client.MakeRequests([
            (client.apitools_client.subnetworks, 'Get',
             client.messages.ComputeSubnetworksGetRequest(
                 **subnet_ref.AsDict()))
        ])[0]

        for secondary_range in add_secondary_ranges:
            for range_name, ip_cidr_range in sorted(
                    six.iteritems(secondary_range)):
                subnetwork.secondaryIpRanges.append(
                    client.messages.SubnetworkSecondaryRange(
                        rangeName=range_name, ipCidrRange=ip_cidr_range))

        return client.MakeRequests(
            [CreateSubnetworkPatchRequest(client, subnet_ref, subnetwork)])
    elif remove_secondary_ranges is not None:
        subnetwork = client.MakeRequests([
            (client.apitools_client.subnetworks, 'Get',
             client.messages.ComputeSubnetworksGetRequest(
                 **subnet_ref.AsDict()))
        ])[0]

        for name in remove_secondary_ranges[0]:
            if name not in [r.rangeName for r in subnetwork.secondaryIpRanges]:
                raise calliope_exceptions.UnknownArgumentException(
                    'remove-secondary-ranges',
                    'Subnetwork does not have a range {}, '
                    'present ranges are {}.'.format(
                        name,
                        [r.rangeName for r in subnetwork.secondaryIpRanges]))
        subnetwork.secondaryIpRanges = [
            r for r in subnetwork.secondaryIpRanges
            if r.rangeName not in remove_secondary_ranges[0]
        ]

        cleared_fields = []
        if not subnetwork.secondaryIpRanges:
            cleared_fields.append('secondaryIpRanges')
        with client.apitools_client.IncludeFields(cleared_fields):
            return client.MakeRequests(
                [CreateSubnetworkPatchRequest(client, subnet_ref, subnetwork)])
    elif (enable_flow_logs is not None or aggregation_interval is not None
          or flow_sampling is not None or metadata is not None):
        subnetwork = client.messages.Subnetwork()
        original_subnetwork = client.MakeRequests([
            (client.apitools_client.subnetworks, 'Get',
             client.messages.ComputeSubnetworksGetRequest(
                 **subnet_ref.AsDict()))
        ])[0]
        subnetwork.fingerprint = original_subnetwork.fingerprint

        if include_alpha_logging:
            log_config = client.messages.SubnetworkLogConfig(
                enable=enable_flow_logs)
            if aggregation_interval is not None:
                log_config.aggregationInterval = (
                    flags.GetLoggingAggregationIntervalArgAlpha(
                        client.messages).GetEnumForChoice(aggregation_interval)
                )
            if flow_sampling is not None:
                log_config.flowSampling = flow_sampling
            if metadata is not None:
                log_config.metadata = flags.GetLoggingMetadataArgAlpha(
                    client.messages).GetEnumForChoice(metadata)
            subnetwork.logConfig = log_config
        else:
            log_config = client.messages.SubnetworkLogConfig(
                enable=enable_flow_logs)
            if aggregation_interval is not None:
                log_config.aggregationInterval = flags.GetLoggingAggregationIntervalArg(
                    client.messages).GetEnumForChoice(aggregation_interval)
            if flow_sampling is not None:
                log_config.flowSampling = flow_sampling
            if metadata is not None:
                log_config.metadata = flags.GetLoggingMetadataArg(
                    client.messages).GetEnumForChoice(metadata)
            subnetwork.logConfig = log_config

        return client.MakeRequests(
            [CreateSubnetworkPatchRequest(client, subnet_ref, subnetwork)])
    elif (private_ipv6_google_access_type is not None
          or private_ipv6_google_access_service_accounts is not None):
        subnetwork = client.MakeRequests([
            (client.apitools_client.subnetworks, 'Get',
             client.messages.ComputeSubnetworksGetRequest(
                 **subnet_ref.AsDict()))
        ])[0]

        cleared_fields = []
        if private_ipv6_google_access_type is not None:
            subnetwork.privateIpv6GoogleAccess = (
                client.messages.Subnetwork.
                PrivateIpv6GoogleAccessValueValuesEnum(
                    ConvertPrivateIpv6GoogleAccess(
                        convert_to_enum(private_ipv6_google_access_type))))
        if private_ipv6_google_access_service_accounts is not None:
            subnetwork.privateIpv6GoogleAccessServiceAccounts = (
                private_ipv6_google_access_service_accounts)
            if not private_ipv6_google_access_service_accounts:
                cleared_fields.append('privateIpv6GoogleAccessServiceAccounts')
        with client.apitools_client.IncludeFields(cleared_fields):
            return client.MakeRequests(
                [CreateSubnetworkPatchRequest(client, subnet_ref, subnetwork)])
    elif enable_private_ipv6_access is not None:
        subnetwork = client.MakeRequests([
            (client.apitools_client.subnetworks, 'Get',
             client.messages.ComputeSubnetworksGetRequest(
                 **subnet_ref.AsDict()))
        ])[0]

        subnetwork.enablePrivateV6Access = enable_private_ipv6_access
        subnetwork.privateIpv6GoogleAccess = None
        return client.MakeRequests(
            [CreateSubnetworkPatchRequest(client, subnet_ref, subnetwork)])
    elif set_role_active is not None:
        subnetwork = client.MakeRequests([
            (client.apitools_client.subnetworks, 'Get',
             client.messages.ComputeSubnetworksGetRequest(
                 **subnet_ref.AsDict()))
        ])[0]

        subnetwork.role = client.messages.Subnetwork.RoleValueValuesEnum.ACTIVE
        patch_request = client.messages.ComputeSubnetworksPatchRequest(
            project=subnet_ref.project,
            subnetwork=subnet_ref.subnetwork,
            region=subnet_ref.region,
            subnetworkResource=subnetwork,
            drainTimeoutSeconds=drain_timeout_seconds)
        return client.MakeRequests([(client.apitools_client.subnetworks,
                                     'Patch', patch_request)])

    return client.MakeRequests([])
コード例 #8
0
ファイル: update.py プロジェクト: piotradamczyk5/gcloud_cli
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client.apitools_client
        messages = holder.client.messages
        resources = holder.resources

        instance_ref = instances_flags.INSTANCE_ARG.ResolveAsResource(
            args,
            holder.resources,
            scope_lister=flags.GetDefaultScopeLister(holder.client))

        instance = client.instances.Get(
            messages.ComputeInstancesGetRequest(**instance_ref.AsDict()))
        for i in instance.networkInterfaces:
            if i.name == args.network_interface:
                fingerprint = i.fingerprint
                break
        else:
            raise exceptions.UnknownArgumentException(
                'network-interface',
                'Instance does not have a network interface [{}], '
                'present interfaces are [{}].'.format(
                    args.network_interface,
                    ', '.join([i.name for i in instance.networkInterfaces])))

        network_uri = None
        if getattr(args, 'network', None) is not None:
            network_uri = resources.Parse(
                args.network, {
                    'project': instance_ref.project
                },
                collection='compute.networks').SelfLink()

        subnetwork_uri = None
        if getattr(args, 'subnetwork', None) is not None:
            region = api_utils.ZoneNameToRegionName(instance_ref.zone)
            subnetwork_uri = resources.Parse(
                args.subnetwork, {
                    'project': instance_ref.project,
                    'region': region
                },
                collection='compute.subnetworks').SelfLink()

        patch_network_interface = messages.NetworkInterface(
            aliasIpRanges=(
                alias_ip_range_utils.CreateAliasIpRangeMessagesFromString(
                    messages, True, args.aliases)),
            network=network_uri,
            subnetwork=subnetwork_uri,
            networkIP=getattr(args, 'private_network_ip', None),
            fingerprint=fingerprint)

        request = messages.ComputeInstancesUpdateNetworkInterfaceRequest(
            project=instance_ref.project,
            instance=instance_ref.instance,
            zone=instance_ref.zone,
            networkInterface=args.network_interface,
            networkInterfaceResource=patch_network_interface)

        cleared_fields = []
        if not patch_network_interface.aliasIpRanges:
            cleared_fields.append('aliasIpRanges')
        with client.IncludeFields(cleared_fields):
            operation = client.instances.UpdateNetworkInterface(request)
        operation_ref = holder.resources.Parse(
            operation.selfLink, collection='compute.zoneOperations')

        operation_poller = poller.Poller(client.instances)
        return waiter.WaitFor(
            operation_poller, operation_ref,
            'Updating network interface [{0}] of instance [{1}]'.format(
                args.network_interface, instance_ref.Name()))
コード例 #9
0
  def Run(self, args):
    """Revoke credentials and update active account."""
    accounts = args.accounts or []
    if isinstance(accounts, 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)
      # External account and external account user credentials cannot be
      # revoked.
      # Detect these type of credentials to show a more user friendly message
      # on revocation calls.
      # Note that impersonated external account credentials will appear like
      # service accounts. These will end with gserviceaccount.com and will be
      # handled the same way service account credentials are handled.
      try:
        creds = c_store.Load(
            account, prevent_refresh=True, use_google_auth=True)
      except creds_exceptions.Error:
        # Ignore all errors. These will be properly handled in the subsequent
        # Revoke call.
        creds = None
      if not c_store.Revoke(account):
        if account.endswith('.gserviceaccount.com'):
          log.warning(
              '[{}] appears to be a service account. Service account tokens '
              'cannot be revoked, but they will expire automatically. To '
              'prevent use of the service account token earlier than the '
              'expiration, delete or disable the parent service account.'
              .format(account))
        elif c_creds.IsExternalAccountCredentials(creds):
          log.warning(
              '[{}] appears to be an external account. External account '
              'tokens cannot be revoked, but they will expire automatically.'
              .format(account))
        elif c_creds.IsExternalAccountUserCredentials(creds):
          log.warning(
              '[{}] appears to be an external account user. External account '
              'user tokens cannot be revoked, but they will expire '
              'automatically.'.format(account))
        else:
          log.warning(
              '[{}] already inactive (previously revoked?)'.format(account))
    return accounts
コード例 #10
0
  def Run(self, args):
    """Create service account credentials."""

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

    json_key = None
    try:
      json_key = json.loads(private_key)
    except ValueError:
      pass

    account = None
    if json_key:
      if args.password_file or args.prompt_for_password:
        raise c_exc.InvalidArgumentException(
            '--password-file',
            'A .json service account key does not require a password.')
      account = json_key.get('client_email', None)
      if not account:
        raise c_exc.ToolException(
            'The .json key file is not in a valid format.')
      if args.account and args.account != account:
        raise c_exc.InvalidArgumentException(
            'ACCOUNT',
            'The given account name does not match the account name in the key '
            'file.  This argument can be omitted when using .json keys.')
      cred = service_account.ServiceAccountCredentials(
          service_account_id=json_key['client_id'],
          service_account_email=json_key['client_email'],
          private_key_id=json_key['private_key_id'],
          private_key_pkcs8_text=json_key['private_key'],
          scopes=config.CLOUDSDK_SCOPES,
          user_agent=config.CLOUDSDK_USER_AGENT)
    else:
      account = args.account
      if not account:
        raise c_exc.RequiredArgumentException(
            'ACCOUNT', 'An account is required when using .p12 keys')
      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=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=account,
            private_key=private_key,
            scope=config.CLOUDSDK_SCOPES,
            user_agent=config.CLOUDSDK_USER_AGENT)
      try:
        c_store.Refresh(cred)
      except c_store.RefreshError:
        log.error(
            'Failed to activate the given service account.  Please ensure the '
            'key is valid and that you have provided the correct account name.')
        raise

    c_store.Store(cred, account)

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

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

    log.status.Print('Activated service account credentials for: [{0}]'
                     .format(account))
    return cred
コード例 #11
0
ファイル: update.py プロジェクト: saranraju90/multik8s
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client.apitools_client
        messages = holder.client.messages
        resources = holder.resources

        instance_ref = instances_flags.INSTANCE_ARG.ResolveAsResource(
            args,
            holder.resources,
            scope_lister=flags.GetDefaultScopeLister(holder.client))

        instance = client.instances.Get(
            messages.ComputeInstancesGetRequest(**instance_ref.AsDict()))
        for i in instance.networkInterfaces:
            if i.name == args.network_interface:
                fingerprint = i.fingerprint
                break
        else:
            raise exceptions.UnknownArgumentException(
                'network-interface',
                'Instance does not have a network interface [{}], '
                'present interfaces are [{}].'.format(
                    args.network_interface,
                    ', '.join([i.name for i in instance.networkInterfaces])))

        network_uri = None
        if getattr(args, 'network', None) is not None:
            network_uri = resources.Parse(
                args.network, {
                    'project': instance_ref.project
                },
                collection='compute.networks').SelfLink()

        subnetwork_uri = None
        if getattr(args, 'subnetwork', None) is not None:
            region = api_utils.ZoneNameToRegionName(instance_ref.zone)
            subnetwork_uri = resources.Parse(
                args.subnetwork, {
                    'project': instance_ref.project,
                    'region': region
                },
                collection='compute.subnetworks').SelfLink()

        stack_type = getattr(args, 'stack_type', None)
        if stack_type is not None:
            stack_type_enum = (
                messages.NetworkInterface.StackTypeValueValuesEnum(stack_type))
            ipv6_network_tier = getattr(args, 'ipv6_network_tier', None)

            ipv6_access_configs = []
            if ipv6_network_tier is not None:
                # If provide IPv6 network tier then set IPv6 access config in request.
                ipv6_access_config = messages.AccessConfig(
                    name=constants.DEFAULT_IPV6_ACCESS_CONFIG_NAME,
                    type=messages.AccessConfig.TypeValueValuesEnum.DIRECT_IPV6)
                ipv6_access_config.networkTier = (
                    messages.AccessConfig.NetworkTierValueValuesEnum(
                        ipv6_network_tier))
                ipv6_access_configs = [ipv6_access_config]
            patch_network_interface = messages.NetworkInterface(
                aliasIpRanges=(
                    alias_ip_range_utils.CreateAliasIpRangeMessagesFromString(
                        messages, True, args.aliases)),
                network=network_uri,
                subnetwork=subnetwork_uri,
                networkIP=getattr(args, 'private_network_ip', None),
                stackType=stack_type_enum,
                ipv6AccessConfigs=ipv6_access_configs,
                fingerprint=fingerprint)
        else:
            patch_network_interface = messages.NetworkInterface(
                aliasIpRanges=(
                    alias_ip_range_utils.CreateAliasIpRangeMessagesFromString(
                        messages, True, args.aliases)),
                network=network_uri,
                subnetwork=subnetwork_uri,
                networkIP=getattr(args, 'private_network_ip', None),
                fingerprint=fingerprint)

        request = messages.ComputeInstancesUpdateNetworkInterfaceRequest(
            project=instance_ref.project,
            instance=instance_ref.instance,
            zone=instance_ref.zone,
            networkInterface=args.network_interface,
            networkInterfaceResource=patch_network_interface)

        cleared_fields = []
        if not patch_network_interface.aliasIpRanges:
            cleared_fields.append('aliasIpRanges')
        with client.IncludeFields(cleared_fields):
            operation = client.instances.UpdateNetworkInterface(request)
        operation_ref = holder.resources.Parse(
            operation.selfLink, collection='compute.zoneOperations')

        operation_poller = poller.Poller(client.instances)
        return waiter.WaitFor(
            operation_poller, operation_ref,
            'Updating network interface [{0}] of instance [{1}]'.format(
                args.network_interface, instance_ref.Name()))
コード例 #12
0
def MakeSubnetworkUpdateRequest(
    client,
    subnet_ref,
    enable_private_ip_google_access=None,
    add_secondary_ranges=None,
    add_secondary_ranges_with_reserved_internal_range=None,
    remove_secondary_ranges=None,
    enable_flow_logs=None,
    aggregation_interval=None,
    flow_sampling=None,
    metadata=None,
    filter_expr=None,
    metadata_fields=None,
    set_new_purpose=None,
    set_role_active=None,
    drain_timeout_seconds=None,
    private_ipv6_google_access_type=None,
    stack_type=None,
    ipv6_access_type=None,
):
    """Make the appropriate update request for the args.

  Args:
    client: GCE API client
    subnet_ref: Reference to a subnetwork
    enable_private_ip_google_access: Enable/disable access to Google Cloud APIs
      from this subnet for instances without a public ip address.
    add_secondary_ranges: List of secondary IP ranges to add to the subnetwork
      for use in IP aliasing.
    add_secondary_ranges_with_reserved_internal_range: List of secondary IP
    ranges that are associated with InternalRange resources.
    remove_secondary_ranges: List of secondary ranges to remove from the
      subnetwork.
    enable_flow_logs: Enable/disable flow logging for this subnet.
    aggregation_interval: The internal at which to aggregate flow logs.
    flow_sampling: The sampling rate for flow logging in this subnet.
    metadata: Whether metadata fields should be added reported flow logs.
    filter_expr: custom CEL expression for filtering flow logs
    metadata_fields: custom metadata fields to be added to flow logs
    set_new_purpose: Update the purpose of the subnet.
    set_role_active: Updates the role of a BACKUP subnet to ACTIVE.
    drain_timeout_seconds: The maximum amount of time to drain connections from
      the active subnet to the backup subnet with set_role_active=True.
    private_ipv6_google_access_type: The private IPv6 google access type for the
      VMs in this subnet.
    stack_type: The stack type for this subnet.
    ipv6_access_type: The IPv6 access type for this subnet.

  Returns:
    response, result of sending the update request for the subnetwork
  """
    convert_to_enum = lambda x: x.replace('-', '_').upper()
    if enable_private_ip_google_access is not None:
        google_access = (
            client.messages.SubnetworksSetPrivateIpGoogleAccessRequest())
        google_access.privateIpGoogleAccess = enable_private_ip_google_access

        google_access_request = (
            client.messages.ComputeSubnetworksSetPrivateIpGoogleAccessRequest(
                project=subnet_ref.project,
                region=subnet_ref.region,
                subnetwork=subnet_ref.Name(),
                subnetworksSetPrivateIpGoogleAccessRequest=google_access))
        return client.MakeRequests([
            (client.apitools_client.subnetworks, 'SetPrivateIpGoogleAccess',
             google_access_request)
        ])
    elif (add_secondary_ranges is not None
          or add_secondary_ranges_with_reserved_internal_range is not None):
        subnetwork = client.messages.Subnetwork()
        original_subnetwork = client.MakeRequests([
            (client.apitools_client.subnetworks, 'Get',
             client.messages.ComputeSubnetworksGetRequest(
                 **subnet_ref.AsDict()))
        ])[0]
        subnetwork.secondaryIpRanges = original_subnetwork.secondaryIpRanges
        subnetwork.fingerprint = original_subnetwork.fingerprint

        subnetwork.secondaryIpRanges.extend(
            CreateSecondaryRanges(
                client, add_secondary_ranges,
                add_secondary_ranges_with_reserved_internal_range))

        return client.MakeRequests(
            [CreateSubnetworkPatchRequest(client, subnet_ref, subnetwork)])
    elif remove_secondary_ranges is not None:
        subnetwork = client.messages.Subnetwork()
        original_subnetwork = client.MakeRequests([
            (client.apitools_client.subnetworks, 'Get',
             client.messages.ComputeSubnetworksGetRequest(
                 **subnet_ref.AsDict()))
        ])[0]
        subnetwork.secondaryIpRanges = original_subnetwork.secondaryIpRanges
        subnetwork.fingerprint = original_subnetwork.fingerprint

        for name in remove_secondary_ranges[0]:
            if name not in [r.rangeName for r in subnetwork.secondaryIpRanges]:
                raise calliope_exceptions.UnknownArgumentException(
                    'remove-secondary-ranges',
                    'Subnetwork does not have a range {}, '
                    'present ranges are {}.'.format(
                        name,
                        [r.rangeName for r in subnetwork.secondaryIpRanges]))
        subnetwork.secondaryIpRanges = [
            r for r in original_subnetwork.secondaryIpRanges
            if r.rangeName not in remove_secondary_ranges[0]
        ]

        cleared_fields = []
        if not subnetwork.secondaryIpRanges:
            cleared_fields.append('secondaryIpRanges')
        with client.apitools_client.IncludeFields(cleared_fields):
            return client.MakeRequests(
                [CreateSubnetworkPatchRequest(client, subnet_ref, subnetwork)])
    elif (enable_flow_logs is not None or aggregation_interval is not None
          or flow_sampling is not None or metadata is not None
          or filter_expr is not None or metadata_fields is not None):
        subnetwork = client.messages.Subnetwork()
        original_subnetwork = client.MakeRequests([
            (client.apitools_client.subnetworks, 'Get',
             client.messages.ComputeSubnetworksGetRequest(
                 **subnet_ref.AsDict()))
        ])[0]
        subnetwork.fingerprint = original_subnetwork.fingerprint

        log_config = client.messages.SubnetworkLogConfig(
            enable=enable_flow_logs)
        if aggregation_interval is not None:
            log_config.aggregationInterval = flags.GetLoggingAggregationIntervalArg(
                client.messages).GetEnumForChoice(aggregation_interval)
        if flow_sampling is not None:
            log_config.flowSampling = flow_sampling
        if metadata is not None:
            log_config.metadata = flags.GetLoggingMetadataArg(
                client.messages).GetEnumForChoice(metadata)
        if filter_expr is not None:
            log_config.filterExpr = filter_expr
        if metadata_fields is not None:
            log_config.metadataFields = metadata_fields
        subnetwork.logConfig = log_config

        return client.MakeRequests(
            [CreateSubnetworkPatchRequest(client, subnet_ref, subnetwork)])
    elif private_ipv6_google_access_type is not None:
        subnetwork = client.messages.Subnetwork()
        original_subnetwork = client.MakeRequests([
            (client.apitools_client.subnetworks, 'Get',
             client.messages.ComputeSubnetworksGetRequest(
                 **subnet_ref.AsDict()))
        ])[0]
        subnetwork.fingerprint = original_subnetwork.fingerprint

        subnetwork.privateIpv6GoogleAccess = (
            client.messages.Subnetwork.PrivateIpv6GoogleAccessValueValuesEnum(
                ConvertPrivateIpv6GoogleAccess(
                    convert_to_enum(private_ipv6_google_access_type))))
        return client.MakeRequests(
            [CreateSubnetworkPatchRequest(client, subnet_ref, subnetwork)])
    elif set_new_purpose is not None:
        subnetwork = client.messages.Subnetwork()
        original_subnetwork = client.MakeRequests([
            (client.apitools_client.subnetworks, 'Get',
             client.messages.ComputeSubnetworksGetRequest(
                 **subnet_ref.AsDict()))
        ])[0]
        subnetwork.fingerprint = original_subnetwork.fingerprint

        subnetwork.purpose = client.messages.Subnetwork.PurposeValueValuesEnum(
            set_new_purpose)
        return client.MakeRequests(
            [CreateSubnetworkPatchRequest(client, subnet_ref, subnetwork)])
    elif set_role_active is not None:
        subnetwork = client.messages.Subnetwork()
        original_subnetwork = client.MakeRequests([
            (client.apitools_client.subnetworks, 'Get',
             client.messages.ComputeSubnetworksGetRequest(
                 **subnet_ref.AsDict()))
        ])[0]
        subnetwork.fingerprint = original_subnetwork.fingerprint

        subnetwork.role = client.messages.Subnetwork.RoleValueValuesEnum.ACTIVE
        patch_request = client.messages.ComputeSubnetworksPatchRequest(
            project=subnet_ref.project,
            subnetwork=subnet_ref.subnetwork,
            region=subnet_ref.region,
            subnetworkResource=subnetwork,
            drainTimeoutSeconds=drain_timeout_seconds)
        return client.MakeRequests([(client.apitools_client.subnetworks,
                                     'Patch', patch_request)])
    elif stack_type is not None:
        subnetwork = client.messages.Subnetwork()
        original_subnetwork = client.MakeRequests([
            (client.apitools_client.subnetworks, 'Get',
             client.messages.ComputeSubnetworksGetRequest(
                 **subnet_ref.AsDict()))
        ])[0]
        subnetwork.fingerprint = original_subnetwork.fingerprint

        subnetwork.stackType = (
            client.messages.Subnetwork.StackTypeValueValuesEnum(stack_type))
        if ipv6_access_type is not None:
            subnetwork.ipv6AccessType = (
                client.messages.Subnetwork.Ipv6AccessTypeValueValuesEnum(
                    ipv6_access_type))
        return client.MakeRequests(
            [CreateSubnetworkPatchRequest(client, subnet_ref, subnetwork)])

    return client.MakeRequests([])
コード例 #13
0
ファイル: subnets_utils.py プロジェクト: 42force/beta
def MakeSubnetworkUpdateRequest(client,
                                subnet_ref,
                                enable_private_ip_google_access=None,
                                add_secondary_ranges=None,
                                remove_secondary_ranges=None,
                                enable_flow_logs=None,
                                aggregation_interval=None,
                                flow_sampling=None,
                                metadata=None,
                                set_role_active=None,
                                drain_timeout_seconds=None):
    """Make the appropriate update request for the args.

  Args:
    client: GCE API client
    subnet_ref: Reference to a subnetwork
    enable_private_ip_google_access: Enable/disable access to Google Cloud APIs
      from this subnet for instances without a public ip address.
    add_secondary_ranges: List of secondary IP ranges to add to the subnetwork
      for use in IP aliasing.
    remove_secondary_ranges: List of secondary ranges to remove from the
      subnetwork.
    enable_flow_logs: Enable/disable flow logging for this subnet.
    aggregation_interval: The internal at which to aggregate flow logs.
    flow_sampling: The sampling rate for flow logging in this subnet.
    metadata: Whether metadata fields should be added reported flow logs.
    set_role_active: Updates the role of a BACKUP subnet to ACTIVE.
    drain_timeout_seconds: The maximum amount of time to drain connections from
      the active subnet to the backup subnet with set_role_active=True.

  Returns:
    response, result of sending the update request for the subnetwork
  """
    convert_to_enum = lambda x: x.replace('-', '_').upper()
    if enable_private_ip_google_access is not None:
        google_access = (
            client.messages.SubnetworksSetPrivateIpGoogleAccessRequest())
        google_access.privateIpGoogleAccess = enable_private_ip_google_access

        google_access_request = (
            client.messages.ComputeSubnetworksSetPrivateIpGoogleAccessRequest(
                project=subnet_ref.project,
                region=subnet_ref.region,
                subnetwork=subnet_ref.Name(),
                subnetworksSetPrivateIpGoogleAccessRequest=google_access))
        return client.MakeRequests([
            (client.apitools_client.subnetworks, 'SetPrivateIpGoogleAccess',
             google_access_request)
        ])
    elif add_secondary_ranges is not None:
        subnetwork = client.MakeRequests([
            (client.apitools_client.subnetworks, 'Get',
             client.messages.ComputeSubnetworksGetRequest(
                 **subnet_ref.AsDict()))
        ])[0]

        for secondary_range in add_secondary_ranges:
            for range_name, ip_cidr_range in sorted(
                    six.iteritems(secondary_range)):
                subnetwork.secondaryIpRanges.append(
                    client.messages.SubnetworkSecondaryRange(
                        rangeName=range_name, ipCidrRange=ip_cidr_range))

        return client.MakeRequests(
            [CreateSubnetworkPatchRequest(client, subnet_ref, subnetwork)])
    elif remove_secondary_ranges is not None:
        subnetwork = client.MakeRequests([
            (client.apitools_client.subnetworks, 'Get',
             client.messages.ComputeSubnetworksGetRequest(
                 **subnet_ref.AsDict()))
        ])[0]

        for name in remove_secondary_ranges[0]:
            if name not in [r.rangeName for r in subnetwork.secondaryIpRanges]:
                raise calliope_exceptions.UnknownArgumentException(
                    'remove-secondary-ranges',
                    'Subnetwork does not have a range {}, '
                    'present ranges are {}.'.format(
                        name,
                        [r.rangeName for r in subnetwork.secondaryIpRanges]))
        subnetwork.secondaryIpRanges = [
            r for r in subnetwork.secondaryIpRanges
            if r.rangeName not in remove_secondary_ranges[0]
        ]

        cleared_fields = []
        if not subnetwork.secondaryIpRanges:
            cleared_fields.append('secondaryIpRanges')
        with client.apitools_client.IncludeFields(cleared_fields):
            return client.MakeRequests(
                [CreateSubnetworkPatchRequest(client, subnet_ref, subnetwork)])
    elif enable_flow_logs is not None:
        subnetwork = client.messages.Subnetwork()
        subnetwork.fingerprint = client.MakeRequests([
            (client.apitools_client.subnetworks, 'Get',
             client.messages.ComputeSubnetworksGetRequest(
                 **subnet_ref.AsDict()))
        ])[0].fingerprint

        subnetwork.enableFlowLogs = enable_flow_logs
        return client.MakeRequests(
            [CreateSubnetworkPatchRequest(client, subnet_ref, subnetwork)])
    elif aggregation_interval is not None:
        subnetwork = client.messages.Subnetwork()
        subnetwork.fingerprint = client.MakeRequests([
            (client.apitools_client.subnetworks, 'Get',
             client.messages.ComputeSubnetworksGetRequest(
                 **subnet_ref.AsDict()))
        ])[0].fingerprint

        subnetwork.aggregationInterval = (
            client.messages.Subnetwork.AggregationIntervalValueValuesEnum(
                convert_to_enum(aggregation_interval)))
        return client.MakeRequests(
            [CreateSubnetworkPatchRequest(client, subnet_ref, subnetwork)])
    elif flow_sampling is not None:
        subnetwork = client.messages.Subnetwork()
        subnetwork.fingerprint = client.MakeRequests([
            (client.apitools_client.subnetworks, 'Get',
             client.messages.ComputeSubnetworksGetRequest(
                 **subnet_ref.AsDict()))
        ])[0].fingerprint

        subnetwork.flowSampling = flow_sampling
        return client.MakeRequests(
            [CreateSubnetworkPatchRequest(client, subnet_ref, subnetwork)])
    elif metadata is not None:
        subnetwork = client.messages.Subnetwork()
        subnetwork.fingerprint = client.MakeRequests([
            (client.apitools_client.subnetworks, 'Get',
             client.messages.ComputeSubnetworksGetRequest(
                 **subnet_ref.AsDict()))
        ])[0].fingerprint

        subnetwork.metadata = client.messages.Subnetwork.MetadataValueValuesEnum(
            convert_to_enum(metadata))
        return client.MakeRequests(
            [CreateSubnetworkPatchRequest(client, subnet_ref, subnetwork)])
    elif set_role_active is not None:
        subnetwork = client.MakeRequests([
            (client.apitools_client.subnetworks, 'Get',
             client.messages.ComputeSubnetworksGetRequest(
                 **subnet_ref.AsDict()))
        ])[0]

        subnetwork.role = client.messages.Subnetwork.RoleValueValuesEnum.ACTIVE
        patch_request = client.messages.ComputeSubnetworksPatchRequest(
            project=subnet_ref.project,
            subnetwork=subnet_ref.subnetwork,
            region=subnet_ref.region,
            subnetworkResource=subnetwork,
            drainTimeoutSeconds=drain_timeout_seconds)
        return client.MakeRequests([(client.apitools_client.subnetworks,
                                     'Patch', patch_request)])

    return client.MakeRequests([])
コード例 #14
0
def MakeSubnetworkUpdateRequest(client,
                                subnet_ref,
                                enable_private_ip_google_access=None,
                                add_secondary_ranges=None,
                                remove_secondary_ranges=None,
                                enable_flow_logs=None):
    """Make the appropriate update request for the args.

  Args:
    client: GCE API client
    subnet_ref: Reference to a subnetwork
    enable_private_ip_google_access: Enable/disable access to Google Cloud APIs
      from this subnet for instances without a public ip address.
    add_secondary_ranges: List of secondary IP ranges to add to the subnetwork
      for use in IP aliasing.
    remove_secondary_ranges: List of secondary ranges to remove from the
      subnetwork.
    enable_flow_logs: Enable/disable flow logging for this subnet.

  Returns:
    response, result of sending the update request for the subnetwork
  """
    if enable_private_ip_google_access is not None:
        google_access = (
            client.messages.SubnetworksSetPrivateIpGoogleAccessRequest())
        google_access.privateIpGoogleAccess = enable_private_ip_google_access

        google_access_request = (
            client.messages.ComputeSubnetworksSetPrivateIpGoogleAccessRequest(
                project=subnet_ref.project,
                region=subnet_ref.region,
                subnetwork=subnet_ref.Name(),
                subnetworksSetPrivateIpGoogleAccessRequest=google_access))
        return client.MakeRequests([
            (client.apitools_client.subnetworks, 'SetPrivateIpGoogleAccess',
             google_access_request)
        ])
    elif add_secondary_ranges is not None:
        subnetwork = client.MakeRequests([
            (client.apitools_client.subnetworks, 'Get',
             client.messages.ComputeSubnetworksGetRequest(
                 **subnet_ref.AsDict()))
        ])[0]

        for secondary_range in add_secondary_ranges:
            for range_name, ip_cidr_range in sorted(
                    secondary_range.iteritems()):
                subnetwork.secondaryIpRanges.append(
                    client.messages.SubnetworkSecondaryRange(
                        rangeName=range_name, ipCidrRange=ip_cidr_range))

        return client.MakeRequests(
            [CreateSubnetworkPatchRequest(client, subnet_ref, subnetwork)])
    elif remove_secondary_ranges is not None:
        subnetwork = client.MakeRequests([
            (client.apitools_client.subnetworks, 'Get',
             client.messages.ComputeSubnetworksGetRequest(
                 **subnet_ref.AsDict()))
        ])[0]

        for name in remove_secondary_ranges[0]:
            if name not in [r.rangeName for r in subnetwork.secondaryIpRanges]:
                raise exceptions.UnknownArgumentException(
                    'remove-secondary-ranges',
                    'Subnetwork does not have a range {}, '
                    'present ranges are {}.'.format(
                        name,
                        [r.rangeName for r in subnetwork.secondaryIpRanges]))
        subnetwork.secondaryIpRanges = [
            r for r in subnetwork.secondaryIpRanges
            if r.rangeName not in remove_secondary_ranges[0]
        ]

        cleared_fields = []
        if not subnetwork.secondaryIpRanges:
            cleared_fields.append('secondaryIpRanges')
        with client.apitools_client.IncludeFields(cleared_fields):
            return client.MakeRequests(
                [CreateSubnetworkPatchRequest(client, subnet_ref, subnetwork)])
    elif enable_flow_logs is not None:
        subnetwork = client.MakeRequests([
            (client.apitools_client.subnetworks, 'Get',
             client.messages.ComputeSubnetworksGetRequest(
                 **subnet_ref.AsDict()))
        ])[0]

        subnetwork.enableFlowLogs = enable_flow_logs
        return client.MakeRequests(
            [CreateSubnetworkPatchRequest(client, subnet_ref, subnetwork)])

    return client.MakeRequests([])
コード例 #15
0
def MakeSubnetworkUpdateRequest(client,
                                subnet_ref,
                                enable_private_ip_google_access=None,
                                add_secondary_ranges=None,
                                remove_secondary_ranges=None):
    """Make the appropriate update request for the args."""
    if enable_private_ip_google_access is not None:
        google_access = (
            client.messages.SubnetworksSetPrivateIpGoogleAccessRequest())
        google_access.privateIpGoogleAccess = enable_private_ip_google_access

        google_access_request = (
            client.messages.ComputeSubnetworksSetPrivateIpGoogleAccessRequest(
                project=subnet_ref.project,
                region=subnet_ref.region,
                subnetwork=subnet_ref.Name(),
                subnetworksSetPrivateIpGoogleAccessRequest=google_access))
        return client.MakeRequests([
            (client.apitools_client.subnetworks, 'SetPrivateIpGoogleAccess',
             google_access_request)
        ])
    elif add_secondary_ranges is not None:
        subnetwork = client.MakeRequests([
            (client.apitools_client.subnetworks, 'Get',
             client.messages.ComputeSubnetworksGetRequest(
                 **subnet_ref.AsDict()))
        ])[0]

        for secondary_range in add_secondary_ranges:
            for range_name, ip_cidr_range in sorted(
                    secondary_range.iteritems()):
                subnetwork.secondaryIpRanges.append(
                    client.messages.SubnetworkSecondaryRange(
                        rangeName=range_name, ipCidrRange=ip_cidr_range))

        return client.MakeRequests(
            [CreateSubnetworkPatchRequest(client, subnet_ref, subnetwork)])
    elif remove_secondary_ranges is not None:
        subnetwork = client.MakeRequests([
            (client.apitools_client.subnetworks, 'Get',
             client.messages.ComputeSubnetworksGetRequest(
                 **subnet_ref.AsDict()))
        ])[0]

        for name in remove_secondary_ranges[0]:
            if name not in [r.rangeName for r in subnetwork.secondaryIpRanges]:
                raise exceptions.UnknownArgumentException(
                    'remove-secondary-ranges',
                    'Subnetwork does not have a range {}, '
                    'present ranges are {}.'.format(
                        name,
                        [r.rangeName for r in subnetwork.secondaryIpRanges]))
        subnetwork.secondaryIpRanges = [
            r for r in subnetwork.secondaryIpRanges
            if r.rangeName not in remove_secondary_ranges[0]
        ]

        cleared_fields = []
        if not subnetwork.secondaryIpRanges:
            cleared_fields.append('secondaryIpRanges')
        with client.apitools_client.IncludeFields(cleared_fields):
            return client.MakeRequests(
                [CreateSubnetworkPatchRequest(client, subnet_ref, subnetwork)])

    return client.MakeRequests([])
コード例 #16
0
  def Run(self, args):
    """Create service account credentials."""

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

    json_key = None
    try:
      json_key = json.loads(private_key)
    except ValueError:
      pass

    if json_key and (args.password_file or args.prompt_for_password):
      raise c_exc.InvalidArgumentException(
          '--password-file',
          'A .json service account key does not require a password.')

    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 '
             'or consider using .json private key instead.'))
      else:
        raise c_exc.ToolException(
            ('PyOpenSSL is not available. See '
             'https://developers.google.com/cloud/sdk/crypto for details '
             'or consider using .json private key instead.'))

    if json_key:
      cred = service_account.ServiceAccountCredentials(
          service_account_id=json_key['client_id'],
          service_account_email=json_key['client_email'],
          private_key_id=json_key['private_key_id'],
          private_key_pkcs8_text=json_key['private_key'],
          scopes=config.CLOUDSDK_SCOPES,
          user_agent=config.CLOUDSDK_USER_AGENT)
    elif 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