Example #1
0
  def SetIamPolicy(self, organization_id, policy_file):
    """Sets the IAM policy for an organization.

    Args:
      organization_id: organization id.
      policy_file: A JSON or YAML file containing the IAM policy.

    Returns:
      The output from the SetIamPolicy API call.
    """
    policy = iam_util.ParsePolicyFile(policy_file, self.messages.Policy)
    policy.version = iam_util.MAX_LIBRARY_IAM_SUPPORTED_VERSION

    update_mask = iam_util.ConstructUpdateMaskFromPolicy(policy_file)

    # To preserve the existing set-iam-policy behavior of always overwriting
    # bindings and etag, add bindings and etag to update_mask.
    if 'bindings' not in update_mask:
      update_mask += ',bindings'
    if 'etag' not in update_mask:
      update_mask += ',etag'

    set_iam_policy_request = self.messages.SetIamPolicyRequest(
        policy=policy,
        updateMask=update_mask)

    policy_request = (
        self.messages.CloudresourcemanagerOrganizationsSetIamPolicyRequest(
            organizationsId=organization_id,
            setIamPolicyRequest=set_iam_policy_request))
    result = self.client.organizations.SetIamPolicy(policy_request)
    iam_util.LogSetIamPolicy(organization_id, 'organization')
    return result
Example #2
0
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

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

        subnetwork_ref = SetIamPolicy.SUBNETWORK_ARG.ResolveAsResource(
            args,
            holder.resources,
            scope_lister=compute_flags.GetDefaultScopeLister(client))

        # TODO(b/78371568): Construct the RegionSetPolicyRequest 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)

        # 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.subnetworks, 'SetIamPolicy',
             client.messages.ComputeSubnetworksSetIamPolicyRequest(
                 regionSetPolicyRequest=client.messages.RegionSetPolicyRequest(
                     bindings=policy.bindings, etag=policy.etag),
                 project=subnetwork_ref.project,
                 region=subnetwork_ref.region,
                 resource=subnetwork_ref.subnetwork))
        ])[0]
        iam_util.LogSetIamPolicy(subnetwork_ref.RelativeName(), 'subnetwork')
        return result
    def Run(self, args):
        client = namespaces.NamespacesClient()
        namespace_ref = args.CONCEPTS.namespace.Parse()
        policy = iam_util.ParsePolicyFile(args.policy_file, client.msgs.Policy)

        iam_util.LogSetIamPolicy(namespace_ref.Name(), _RESOURCE_TYPE)
        return client.SetIamPolicy(namespace_ref, policy)
Example #4
0
    def Run(self, args):
        policy = iam_util.ParsePolicyFile(args.policy_file,
                                          self.messages.Policy)

        ref = self.CreateReference(args)
        request_class = self.service.GetRequestType(self.method)
        request = request_class(project=self.project)
        self.ScopeRequest(ref, request)
        self.SetResourceName(ref, request)
        request.policy = policy

        set_policy_request = (self.service, self.method, request)
        errors = []
        objects = request_helper.MakeRequests(requests=[set_policy_request],
                                              http=self.http,
                                              batch_url=self.batch_url,
                                              errors=errors)

        # Converting the objects genrator to a list triggers the
        # logic that actually populates the errors list.
        resources = list(objects)
        if errors:
            utils.RaiseToolException(errors,
                                     error_message='Could not fetch resource:')

        # TODO(user): 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 resources[0]
def SetIamPolicy(models_client, model, policy_file):
    model_ref = ParseModel(model)
    policy = iam_util.ParsePolicyFile(policy_file,
                                      models_client.messages.GoogleIamV1Policy)
    update_mask = iam_util.ConstructUpdateMaskFromPolicy(policy_file)
    iam_util.LogSetIamPolicy(model_ref.Name(), 'model')
    return models_client.SetIamPolicy(model_ref, policy, update_mask)
Example #6
0
  def Run(self, args):
    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
    client = holder.client

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

    subnetwork_ref = SetIamPolicy.SUBNETWORK_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.subnetworks, 'SetIamPolicy',
          client.messages.ComputeSubnetworksSetIamPolicyRequest(
              regionSetPolicyRequest=client.messages.RegionSetPolicyRequest(
                  policy=policy),
              project=subnetwork_ref.project,
              region=subnetwork_ref.region,
              resource=subnetwork_ref.subnetwork))])[0]
    iam_util.LogSetIamPolicy(subnetwork_ref.RelativeName(), 'subnetwork')
    return result
Example #7
0
    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/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(
                 policy=policy,
                 project=instance_ref.project,
                 resource=instance_ref.instance,
                 zone=instance_ref.zone))
        ])[0]
    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]
Example #9
0
    def testParseIamPolicyMissingEtag(self):
        policy_file = self._CreateIAMPolicyFile()
        expected_policy = self._GetTestIAMPolicy()

        self.WriteInput('Y\n')
        policy = iam_util.ParsePolicyFile(policy_file, self.messages.Policy)

        self.assertEqual(policy, expected_policy)
Example #10
0
def SetIamPolicyFromFile(project_ref, policy_file):
    """Read projects IAM policy from a file, and set it."""
    messages = projects_util.GetMessages()
    policy = iam_util.ParsePolicyFile(policy_file, messages.Policy)
    try:
        return SetIamPolicy(project_ref, policy)
    except exceptions.HttpError as error:
        raise projects_util.ConvertHttpError(error)
 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)
   request = client.messages.ComputeDisksSetIamPolicyRequest(
       policy=policy, resource=disk_ref.disk, zone=disk_ref.zone,
       project=disk_ref.project)
   return client.apitools_client.disks.SetIamPolicy(request)
Example #12
0
    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)))
    def Run(self, args):
        client = services.ServicesClient()
        service_ref = args.CONCEPTS.service.Parse()
        policy = iam_util.ParsePolicyFile(args.policy_file, client.msgs.Policy)

        result = client.SetIamPolicy(service_ref, policy)
        iam_util.LogSetIamPolicy(service_ref.Name(), _RESOURCE_TYPE)

        return result
Example #14
0
 def Run(self_, args):
     policy_type = self.method.GetMessageByName('Policy')
     policy = iam_util.ParsePolicyFile(args.policy_file,
                                       policy_type)
     self.spec.request.static_fields[
         'setIamPolicyRequest.policy'] = policy
     ref, response = self._CommonRun(args)
     iam_util.LogSetIamPolicy(ref.Name(), self.resource_type)
     return self._HandleResponse(response)
Example #15
0
 def Run(self, args):
     messages = self.OrganizationsMessages()
     policy = iam_util.ParsePolicyFile(args.policy_file, messages.Policy)
     policy_request = (
         messages.CloudresourcemanagerOrganizationsSetIamPolicyRequest(
             organizationsId=args.id,
             setIamPolicyRequest=messages.SetIamPolicyRequest(
                 policy=policy)))
     return self.OrganizationsClient().SetIamPolicy(policy_request)
 def Run(self, args):
   queues_client = queues.Queues()
   queues_messages = queues_client.api.messages
   queue_ref = parsers.ParseQueue(args.queue)
   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
Example #17
0
 def testParseIamPolicyInvalidYaml(self):
     bad_file = self.Touch(self.dir.path,
                           name='bad_yaml.json',
                           contents='NOT YAML OR JSON')
     with self.assertRaisesRegex(
             gcloud_exceptions.BadFileException,
             r'Policy file \[.*\] is not a '
             'properly formatted YAML or JSON '
             'policy file.'):
         iam_util.ParsePolicyFile(bad_file, self.messages.Policy)
  def Run(self, args):
    client = registries.RegistriesClient()
    messages = apis.GetMessagesModule('cloudiot', 'v1beta1')

    policy = iam_util.ParsePolicyFile(args.policy_file, messages.Policy)
    registry_ref = util.ParseRegistry(args.id, region=args.region)

    return client.SetIamPolicy(
        registry_ref,
        set_iam_policy_request=messages.SetIamPolicyRequest(policy=policy))
  def Run(self, args):
    client, messages = util.GetClientAndMessages()
    policy = iam_util.ParsePolicyFile(args.policy_file, messages.Policy)

    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
    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('Updated IAM policy for subscription [{}].'.format(
            subscription_ref.Name()))
        return response
    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
Example #22
0
 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)
  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
Example #24
0
  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))
    log.status.Print(
        'Set IAM policy for registry [{}].'.format(registry_ref.Name()))
    return response
Example #25
0
    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)

        cluster_ref = util.ParseCluster(args.cluster, dataproc)
        request = messages.DataprocProjectsRegionsClustersSetIamPolicyRequest(
            resource=cluster_ref.RelativeName(),
            setIamPolicyRequest=set_iam_policy_request)

        return dataproc.client.projects_regions_clusters.SetIamPolicy(request)
    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)
Example #27
0
    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)
Example #28
0
  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.ParsePolicyFile(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)
Example #29
0
    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_ref = args.CONCEPTS.operation.Parse()
        request = msgs.DataprocProjectsRegionsOperationsSetIamPolicyRequest(
            resource=operation_ref.RelativeName(),
            setIamPolicyRequest=set_iam_policy_request)

        return dataproc.client.projects_regions_operations.SetIamPolicy(
            request)
Example #30
0
def SetIamPolicyFromFile(project_ref, policy_file):
    """Read projects IAM policy from a file, and set it."""
    messages = projects_util.GetMessages()
    policy = iam_util.ParsePolicyFile(policy_file, messages.Policy)
    update_mask = iam_util.ConstructUpdateMaskFromPolicy(policy_file)

    # To preserve the existing set-iam-policy behavior of always overwriting
    # bindings and etag, add bindings and etag to update_mask.
    if 'bindings' not in update_mask:
        update_mask += ',bindings'
    if 'etag' not in update_mask:
        update_mask += ',etag'

    return SetIamPolicy(project_ref, policy, update_mask)