Beispiel #1
0
class SetIamPolicy(base.Command):
    """Set IAM policy for a dataset.

  This command sets the IAM policy for a dataset, given a dataset ID and a
  file that contains the JSON encoded IAM policy.
  """

    detailed_help = iam_util.GetDetailedHelpForSetIamPolicy(
        'dataset', '1000',
        """See https://cloud.google.com/genomics/v1/access-control for details on
          managing access control on Genomics datasets.""")

    @staticmethod
    def Args(parser):
        parser.add_argument('id', type=str, help='The ID of the dataset.')
        parser.add_argument('policy_file',
                            help='JSON file with the IAM policy')

    def Run(self, args):
        apitools_client = genomics_util.GetGenomicsClient()
        messages = genomics_util.GetGenomicsMessages()

        dataset_resource = resources.REGISTRY.Parse(
            args.id, collection='genomics.datasets')

        policy = iam_util.ParseJsonPolicyFile(args.policy_file,
                                              messages.Policy)

        policy_request = messages.GenomicsDatasetsSetIamPolicyRequest(
            resource='datasets/{0}'.format(dataset_resource.Name()),
            setIamPolicyRequest=messages.SetIamPolicyRequest(policy=policy),
        )
        return apitools_client.datasets.SetIamPolicy(policy_request)
Beispiel #2
0
class SetIamPolicy(base.Command):
    """Set IAM policy for a workflow template.

  Sets the IAM policy for a workflow template, given a template ID and the
  policy.
  """

    detailed_help = iam_util.GetDetailedHelpForSetIamPolicy('template')

    @staticmethod
    def Args(parser):
        flags.AddTemplateFlag(parser, 'set the policy on')
        iam_util.AddArgForPolicyFile(parser)

    def Run(self, args):
        dataproc = dp.Dataproc(self.ReleaseTrack())
        msgs = dataproc.messages

        policy = iam_util.ParsePolicyFile(args.policy_file, msgs.Policy)
        set_iam_policy_request = msgs.SetIamPolicyRequest(policy=policy)

        template = util.ParseWorkflowTemplates(args.template, dataproc)
        request = msgs.DataprocProjectsRegionsWorkflowTemplatesSetIamPolicyRequest(
            resource=template.RelativeName(),
            setIamPolicyRequest=set_iam_policy_request)

        return dataproc.client.projects_regions_workflowTemplates.SetIamPolicy(
            request)
Beispiel #3
0
class SetIamPolicy(base.Command):
    """Set the IAM Policy for a Google Compute Engine disk image.

  *{command}* replaces the existing IAM policy for a disk image, given an image
  and a file encoded in JSON or YAML that contains the IAM policy. If the given
  policy file specifies an "etag" value, then the replacement will succeed only
  if the policy already in place matches that etag. (An etag obtained via
  `get-iam-policy` will prevent the replacement if the policy for the image has
  been subsequently updated.) A policy file that does not contain an etag value
  will replace any existing policy for the image.
  """

    detailed_help = iam_util.GetDetailedHelpForSetIamPolicy(
        'disk image', 'my-image')

    @staticmethod
    def Args(parser):
        SetIamPolicy.disk_image_arg = flags.MakeDiskImageArg(plural=False)
        SetIamPolicy.disk_image_arg.AddArgument(
            parser, operation_type='set the IAM policy of')
        compute_flags.AddPolicyFileFlag(parser)

    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client
        image_ref = SetIamPolicy.disk_image_arg.ResolveAsResource(
            args,
            holder.resources,
            scope_lister=compute_flags.GetDefaultScopeLister(client))
        policy = iam_util.ParsePolicyFile(args.policy_file,
                                          client.messages.Policy)
        request = client.messages.ComputeImagesSetIamPolicyRequest(
            policy=policy, resource=image_ref.image, project=image_ref.project)
        return client.apitools_client.images.SetIamPolicy(request)
class SetIamPolicy(base.Command):
    """Set IAM policy for an operation.

  Sets the IAM policy for an operation, given an operation ID and the policy.
  """

    detailed_help = iam_util.GetDetailedHelpForSetIamPolicy('operation',
                                                            use_an=True)

    @staticmethod
    def Args(parser):
        flags.AddOperationFlag(parser, 'set the policy on')
        iam_util.AddArgForPolicyFile(parser)

    def Run(self, args):
        dataproc = dp.Dataproc(self.ReleaseTrack())
        msgs = dataproc.messages

        policy = iam_util.ParsePolicyFile(args.policy_file, msgs.Policy)
        set_iam_policy_request = msgs.SetIamPolicyRequest(policy=policy)

        operation = util.ParseOperation(args.operation, dataproc)
        request = msgs.DataprocProjectsRegionsOperationsSetIamPolicyRequest(
            resource=operation.RelativeName(),
            setIamPolicyRequest=set_iam_policy_request)

        return dataproc.client.projects_regions_operations.SetIamPolicy(
            request)
class SetIamPolicy(base.Command):
  """Set the IAM policy for a device registry.

  This command replaces the existing IAM policy for a device registry, given
  a REGISTRY and a file encoded in JSON or YAML that contains the IAM
  policy. If the given policy file specifies an "etag" value, then the
  replacement will succeed only if the policy already in place matches that
  etag. (An etag obtained via $ gcloud iot registries get-iam-policy will
  prevent the replacement if the policy for the device registry has been
  subsequently updated.) A policy file that does not contain an etag value will
  replace any existing policy for the device registry.
  """

  detailed_help = iam_util.GetDetailedHelpForSetIamPolicy(
      'device registry', 'my-registry', additional_flags='--region=us-central1')

  @staticmethod
  def Args(parser):
    resource_args.AddRegistryResourceArg(parser, 'for which to set IAM policy')
    flags.GetIamPolicyFileFlag().AddToParser(parser)

  def Run(self, args):
    client = registries.RegistriesClient()
    messages = client.messages

    policy = iam_util.ParsePolicyFile(args.policy_file, messages.Policy)
    registry_ref = args.CONCEPTS.registry.Parse()

    response = client.SetIamPolicy(
        registry_ref,
        set_iam_policy_request=messages.SetIamPolicyRequest(policy=policy))
    iam_util.LogSetIamPolicy(registry_ref.Name(), 'registry')
    return response
Beispiel #6
0
class SetIamPolicy(base.Command):
    """Set the IAM policy for a queue.

  This command replaces the existing IAM policy for a queue, given a queue and a
  file encoded in JSON or YAML that contains the IAM policy. If the given policy
  file specifies an "etag" value, then the replacement will succeed only if the
  policy already in place matches that etag. (An etag obtained via
  `get-iam-policy` will prevent the replacement if the policy for the queue has
  been subsequently updated.) A policy file that does not contain an etag value
  will replace any existing policy for the queue.
  """

    detailed_help = iam_util.GetDetailedHelpForSetIamPolicy(
        'queue', 'my-queue')

    @staticmethod
    def Args(parser):
        flags.AddQueueResourceArg(parser, 'to set the IAM policy for')
        flags.AddLocationFlag(parser)
        flags.AddPolicyFileFlag(parser)

    def Run(self, args):
        queues_client = queues.Queues()
        queues_messages = queues_client.api.messages
        queue_ref = parsers.ParseQueue(args.queue, args.location)
        self.context['iam-messages'] = queues_messages
        policy = iam_util.ParsePolicyFile(args.policy_file,
                                          queues_messages.Policy)
        response = queues_client.SetIamPolicy(queue_ref, policy)
        log.status.Print('Set IAM policy for queue [{}].'.format(
            queue_ref.Name()))
        return response
class SetIamPolicy(base.Command):
    """Set IAM policy for an autoscaling policy.

  Sets the IAM policy for an autoscaling policy, given an autoscaling policy ID
  and the IAM policy.
  """

    detailed_help = iam_util.GetDetailedHelpForSetIamPolicy(
        'autoscaling-policy', use_an=True)

    @staticmethod
    def Args(parser):
        flags.AddAutoscalingPolicyResourceArg(parser,
                                              'retrieve the IAM policy for',
                                              api_version='v1beta2')
        iam_util.AddArgForPolicyFile(parser)

    def Run(self, args):
        dataproc = dp.Dataproc(self.ReleaseTrack())
        messages = dataproc.messages

        policy = iam_util.ParsePolicyFile(args.policy_file, messages.Policy)
        set_iam_policy_request = messages.SetIamPolicyRequest(policy=policy)

        policy_ref = args.CONCEPTS.autoscaling_policy.Parse()
        # pylint: disable=line-too-long
        request = messages.DataprocProjectsRegionsAutoscalingPoliciesSetIamPolicyRequest(
            resource=policy_ref.RelativeName(),
            setIamPolicyRequest=set_iam_policy_request)
        # pylint: enable=line-too-long

        return dataproc.client.projects_regions_autoscalingPolicies.SetIamPolicy(
            request)
Beispiel #8
0
class SetIamPolicy(base_classes.BaseIamCommand):
    """Set the IAM policy for a service account.

  This command replaces the existing IAM policy for a service account, given
  an IAM-ACCOUNT and a file encoded in JSON or YAML that contains the IAM
  policy. If the given policy file specifies an "etag" value, then the
  replacement will succeed only if the policy already in place matches that
  etag. (An etag obtained via $ gcloud iam service-accounts get-iam-policy will
  prevent the replacement if the policy for the service account has been
  subsequently updated.) A policy file that does not contain an etag value will
  replace any existing policy for the service account.
  """

    detailed_help = iam_util.GetDetailedHelpForSetIamPolicy(
        'service account', '*****@*****.**')

    @staticmethod
    def Args(parser):
        iam_util.AddServiceAccountNameArg(
            parser, help_text='The service account whose policy to set.')
        parser.add_argument('policy_file',
                            metavar='POLICY-FILE',
                            help='Path to a local JSON or YAML formatted file '
                            'containing a valid policy.')

    def Run(self, args):
        policy = iam_util.ParsePolicyFile(args.policy_file,
                                          self.messages.Policy)

        return self.iam_client.projects_serviceAccounts.SetIamPolicy(
            self.messages.IamProjectsServiceAccountsSetIamPolicyRequest(
                resource=iam_util.EmailToAccountResourceName(args.name),
                setIamPolicyRequest=self.messages.SetIamPolicyRequest(
                    policy=policy)))
class SetIamPolicy(base_classes.BaseIamCommand):
  """Set the IAM policy for a Cloud Pub/Sub Subscription."""

  detailed_help = iam_util.GetDetailedHelpForSetIamPolicy(
      'subscription', 'my-subscription')

  @staticmethod
  def Args(parser):
    resource_args.AddSubscriptionResourceArg(parser, 'to set an IAM policy on.')
    flags.AddIamPolicyFileFlag(parser)

  def Run(self, args):
    client = subscriptions.SubscriptionsClient()
    messages = client.messages

    subscription_ref = args.CONCEPTS.subscription.Parse()
    policy = iam_util.ParsePolicyFile(args.policy_file, messages.Policy)

    response = client.SetIamPolicy(
        subscription_ref,
        policy=policy)
    log.status.Print(
        'Set IAM policy for Subscription [{}].'.format(
            subscription_ref.Name()))
    return response
class SetIamPolicy(base.Command):
    """Set IAM policy for a job.

  Sets the IAM policy for a job, given a job ID and the policy.
  """

    detailed_help = iam_util.GetDetailedHelpForSetIamPolicy('job')

    @staticmethod
    def Args(parser):
        flags.AddJobFlag(parser, 'set the policy on')
        iam_util.AddArgForPolicyFile(parser)

    def Run(self, args):
        dataproc = dp.Dataproc(self.ReleaseTrack())
        msgs = dataproc.messages

        policy = iam_util.ParsePolicyFile(args.policy_file, msgs.Policy)
        set_iam_policy_request = msgs.SetIamPolicyRequest(policy=policy)

        job = util.ParseJob(args.job, dataproc)
        request = msgs.DataprocProjectsRegionsJobsSetIamPolicyRequest(
            resource=job.RelativeName(),
            setIamPolicyRequest=set_iam_policy_request)

        return dataproc.client.projects_regions_jobs.SetIamPolicy(request)
Beispiel #11
0
class SetIamPolicy(base_classes.BaseIamCommand):
  """Set the IAM policy for a service account.

  This command sets the IAM policy for a service account, given an IAM-ACCOUNT
  and a file that contains the JSON encoded IAM policy.
  """

  detailed_help = iam_util.GetDetailedHelpForSetIamPolicy(
      'service account', '*****@*****.**')

  @staticmethod
  def Args(parser):
    parser.add_argument('account',
                        metavar='IAM-ACCOUNT',
                        help='The service account whose policy to '
                        'set.')
    parser.add_argument('policy_file',
                        metavar='POLICY-FILE',
                        help='Path to a local JSON formatted file containing '
                        'a valid policy.')

  def Run(self, args):
    try:
      policy = iam_util.ParseJsonPolicyFile(
          args.policy_file,
          self.messages.Policy)

      return self.iam_client.projects_serviceAccounts.SetIamPolicy(
          self.messages.IamProjectsServiceAccountsSetIamPolicyRequest(
              resource=utils.EmailToAccountResourceName(args.account),
              setIamPolicyRequest=self.messages.SetIamPolicyRequest(
                  policy=policy)))
    except exceptions.HttpError as error:
      raise utils.ConvertToServiceAccountException(error, args.account)
Beispiel #12
0
class SetIamPolicy(base.Command):
    """Set the IAM policy for a Cloud Bigtable instance."""

    detailed_help = iam_util.GetDetailedHelpForSetIamPolicy(
        'instance', example_id='my-instance-id', use_an=True)

    @staticmethod
    def Args(parser):
        """Register flags for this command."""
        arguments.AddInstanceResourceArg(parser,
                                         'to set the IAM policy for',
                                         positional=True)
        iam_util.AddArgForPolicyFile(parser)

    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:
      A IAM policy message.
    """
        instance_ref = util.GetInstanceRef(args.instance)
        result = iam.SetInstanceIamPolicy(instance_ref, args.policy_file)
        iam_util.LogSetIamPolicy(instance_ref.Name(), 'instance')
        return result
class SetIamPolicy(base_classes.BaseIamCommand):
    """Set the IAM policy for a service account.

  This command replaces the existing IAM policy for a service account, given
  an IAM-ACCOUNT and a file that contains the new JSON-encoded IAM policy. If
  the given policy file specifies an "etag" value, then the replacement will
  succeed only if the policy already in place matches that etag. (An etag
  obtained via $ gcloud iam service-accounts get-iam-policy will prevent the
  replacement if the policy for the service account has been subsequently
  updated.) A policy file that does not contain an etag value will replace any
  existing policy for the service account.
  """

    detailed_help = iam_util.GetDetailedHelpForSetIamPolicy(
        'service account', '*****@*****.**')

    @staticmethod
    def Args(parser):
        parser.add_argument('account',
                            metavar='IAM-ACCOUNT',
                            help='The service account whose policy to '
                            'set.')
        parser.add_argument(
            'policy_file',
            metavar='POLICY-FILE',
            help='Path to a local JSON formatted file containing '
            'a valid policy.')

    def Run(self, args):
        try:
            policy = iam_util.ParseJsonPolicyFile(args.policy_file,
                                                  self.messages.Policy)
            if not policy.etag:
                msg = (
                    'The specified policy does not contain an "etag" field '
                    'identifying a specific version to replace. Changing a '
                    'policy without an "etag" can overwrite concurrent policy '
                    'changes.')
                console_io.PromptContinue(
                    message=msg,
                    prompt_string='Replace existing policy',
                    cancel_on_no=True)
            return self.iam_client.projects_serviceAccounts.SetIamPolicy(
                self.messages.IamProjectsServiceAccountsSetIamPolicyRequest(
                    resource=iam_util.EmailToAccountResourceName(args.account),
                    setIamPolicyRequest=self.messages.SetIamPolicyRequest(
                        policy=policy)))
        except exceptions.HttpError as error:
            raise iam_util.ConvertToServiceAccountException(
                error, args.account)
class SetIamPolicy(base.Command):
    """Set the IAM Policy for a Google Compute Engine instance.

  *{command}* sets the IAM Policy associated with a Google Compute Engine
  instance in a project.
  """

    detailed_help = iam_util.GetDetailedHelpForSetIamPolicy('instance',
                                                            'my-instance',
                                                            use_an=True)

    @staticmethod
    def Args(parser):
        flags.INSTANCE_ARG.AddArgument(parser,
                                       operation_type='set the IAM policy of')
        compute_flags.AddPolicyFileFlag(parser)

    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

        policy = iam_util.ParsePolicyFile(args.policy_file,
                                          client.messages.Policy)

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

        # TODO(b/78371568): Construct the ZoneSetPolicyRequest directly
        # out of the parsed policy instead of setting 'bindings' and 'etags'.
        # This current form is required so gcloud won't break while Compute
        # roll outs the breaking change to SetIamPolicy (b/75971480)

        # TODO(b/36053578): determine how this output should look when empty.

        # SetIamPolicy always returns either an error or the newly set policy.
        # If the policy was just set to the empty policy it returns a valid empty
        # policy (just an etag.)
        # It is not possible to have multiple policies for one resource.
        return client.MakeRequests([
            (client.apitools_client.instances, 'SetIamPolicy',
             client.messages.ComputeInstancesSetIamPolicyRequest(
                 zoneSetPolicyRequest=client.messages.ZoneSetPolicyRequest(
                     bindings=policy.bindings, etag=policy.etag),
                 project=instance_ref.project,
                 resource=instance_ref.instance,
                 zone=instance_ref.zone))
        ])[0]
class SetIamPolicy(base.Command):
  """Set the IAM policy for a service account.

  This command replaces the existing IAM policy for a service account, given
  an IAM_ACCOUNT and a file encoded in JSON or YAML that contains the IAM
  policy. If the given policy file specifies an "etag" value, then the
  replacement will succeed only if the policy already in place matches that
  etag. (An etag obtained via $ gcloud iam service-accounts get-iam-policy will
  prevent the replacement if the policy for the service account has been
  subsequently updated.) A policy file that does not contain an etag value will
  replace any existing policy for the service account.

  If the service account does not exist, this command returns a
  `PERMISSION_DENIED` error.
  """

  detailed_help = iam_util.GetDetailedHelpForSetIamPolicy(
      'service account', '*****@*****.**')
  detailed_help['DESCRIPTION'] += '\n\n' + (
      iam_util.GetHintForServiceAccountResource(
          'set the iam policy of'))

  @staticmethod
  def Args(parser):
    iam_util.AddServiceAccountNameArg(
        parser,
        action='whose policy to set')
    parser.add_argument(
        'policy_file',
        metavar='POLICY_FILE',
        help='Path to a local JSON or YAML formatted file '
        'containing a valid policy.')

  def Run(self, args):
    client, messages = util.GetClientAndMessages()
    policy = iam_util.ParsePolicyFile(args.policy_file, messages.Policy)
    policy.version = iam_util.MAX_LIBRARY_IAM_SUPPORTED_VERSION

    result = client.projects_serviceAccounts.SetIamPolicy(
        messages.IamProjectsServiceAccountsSetIamPolicyRequest(
            resource=iam_util.EmailToAccountResourceName(args.service_account),
            setIamPolicyRequest=messages.SetIamPolicyRequest(
                policy=policy)))
    iam_util.LogSetIamPolicy(args.service_account, 'service account')
    return result
Beispiel #16
0
class SetIamPolicy(base.Command):
    """Set the IAM Policy for a Google Compute Engine instance.

  *{command}* sets the IAM Policy associated with a Google Compute Engine
  instance in a project.
  """

    detailed_help = iam_util.GetDetailedHelpForSetIamPolicy('instance',
                                                            'my-instance',
                                                            use_an=True)

    @staticmethod
    def Args(parser):
        flags.INSTANCE_ARG.AddArgument(parser,
                                       operation_type='set the IAM policy of')
        compute_flags.AddPolicyFileFlag(parser)

    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

        policy = iam_util.ParsePolicyFile(args.policy_file,
                                          client.messages.Policy)

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

        # SetIamPolicy always returns either an error or the newly set policy.
        # If the policy was just set to the empty policy it returns a valid empty
        # policy (just an etag.)
        # It is not possible to have multiple policies for one resource.
        result = client.MakeRequests([
            (client.apitools_client.instances, 'SetIamPolicy',
             client.messages.ComputeInstancesSetIamPolicyRequest(
                 zoneSetPolicyRequest=client.messages.ZoneSetPolicyRequest(
                     policy=policy),
                 project=instance_ref.project,
                 resource=instance_ref.instance,
                 zone=instance_ref.zone))
        ])[0]
        iam_util.LogSetIamPolicy(instance_ref.RelativeName(), 'instance')
        return result
Beispiel #17
0
class SetIamPolicy(base.Command):
    """Set the IAM Policy for a Google Compute Engine disk.

  *{command}* replaces the existing IAM policy for a disk, given a disk and a
  file encoded in JSON or YAML that contains the IAM policy. If the given policy
  file specifies an "etag" value, then the replacement will succeed only if the
  policy already in place matches that etag. (An etag obtained via
  `get-iam-policy` will prevent the replacement if the policy for the disk has
  been subsequently updated.) A policy file that does not contain an etag value
  will replace any existing policy for the disk.
  """

    detailed_help = iam_util.GetDetailedHelpForSetIamPolicy('disk', 'my-disk')

    @staticmethod
    def Args(parser):
        SetIamPolicy.disk_arg = disks_flags.MakeDiskArg(plural=False)
        SetIamPolicy.disk_arg.AddArgument(
            parser, operation_type='set the IAM policy of')
        compute_flags.AddPolicyFileFlag(parser)

    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client
        disk_ref = SetIamPolicy.disk_arg.ResolveAsResource(
            args, holder.resources)
        policy = iam_util.ParsePolicyFile(args.policy_file,
                                          client.messages.Policy)
        # TODO(b/78371568): Construct the ZoneSetPolicyRequest directly
        # out of the parsed policy instead of setting 'bindings' and 'etags'.
        # This current form is required so gcloud won't break while Compute
        # roll outs the breaking change to SetIamPolicy (b/75971480)
        request = client.messages.ComputeDisksSetIamPolicyRequest(
            zoneSetPolicyRequest=client.messages.ZoneSetPolicyRequest(
                bindings=policy.bindings, etag=policy.etag),
            resource=disk_ref.disk,
            zone=disk_ref.zone,
            project=disk_ref.project)
        return client.apitools_client.disks.SetIamPolicy(request)
class SetIamPolicy(base.Command):
    """Set the IAM policy for a Cloud Pub/Sub Topic."""

    detailed_help = iam_util.GetDetailedHelpForSetIamPolicy(
        'topic', 'my-topic')

    @staticmethod
    def Args(parser):
        resource_args.AddTopicResourceArg(parser, 'to set an IAM policy on.')
        flags.AddIamPolicyFileFlag(parser)

    def Run(self, args):
        client = topics.TopicsClient()
        messages = client.messages

        topic_ref = args.CONCEPTS.topic.Parse()
        policy = iam_util.ParsePolicyFile(args.policy_file, messages.Policy)

        response = client.SetIamPolicy(topic_ref, policy=policy)
        log.status.Print('Updated IAM policy for topic [{}].'.format(
            topic_ref.Name()))
        return response