def AddIamPolicyBinding(lake_ref, member, role): """Add iam policy binding request.""" policy = GetIamPolicy(lake_ref) iam_util.AddBindingToIamPolicy( dataplex_api.GetMessageModule().GoogleIamV1Binding, policy, member, role) return SetIamPolicy(lake_ref, policy)
def AddPolicyBindingToKeyRing(key_ring_ref, member, role): """Does an atomic Read-Modify-Write, adding the member to the role.""" messages = base.GetMessagesModule() policy = GetKeyRingIamPolicy(key_ring_ref) iam_util.AddBindingToIamPolicy(messages, policy, member, role) return SetKeyRingIamPolicy(key_ring_ref, policy)
def Run(args, release_track): """Adds a binding to the IAM policy for a Google Cloud Function. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. release_track: The relevant value from the googlecloudsdk.calliope.base.ReleaseTrack enum. Returns: The updated IAM policy. """ client = api_util.GetClientInstance(release_track=release_track) messages = api_util.GetMessagesModule(release_track=release_track) function_ref = args.CONCEPTS.name.Parse() function_relative_name = function_ref.RelativeName() policy = client.projects_locations_functions.GetIamPolicy( messages.CloudfunctionsProjectsLocationsFunctionsGetIamPolicyRequest( resource=function_relative_name)) iam_util.AddBindingToIamPolicy(messages.Binding, policy, args.member, args.role) return client.projects_locations_functions.SetIamPolicy( messages.CloudfunctionsProjectsLocationsFunctionsSetIamPolicyRequest( resource=function_relative_name, setIamPolicyRequest=messages.SetIamPolicyRequest(policy=policy)))
def AddIamPolicyBindings(self, bucket_ref, member_roles): """Add IAM policy bindings on the specified bucket. Does an atomic Read-Modify-Write, adding the member to the role. Args: bucket_ref: storage_util.BucketReference to the bucket with the policy. member_roles: List of 2-tuples in the form [(member, role), ...]. Returns: The new IAM Policy. """ policy = self.GetIamPolicy(bucket_ref) policy.version = iam_util.MAX_LIBRARY_IAM_SUPPORTED_VERSION policy_was_updated = False for member, role in member_roles: if iam_util.AddBindingToIamPolicy( self.messages.Policy.BindingsValueListEntry, policy, member, role): policy_was_updated = True if policy_was_updated: return self.SetIamPolicy(bucket_ref, policy) return policy
def Run(self, args): holder = base_classes.ComputeApiHolder(self.ReleaseTrack()) client = holder.client instance_ref = flags.INSTANCE_ARG.ResolveAsResource( args, holder.resources, scope_lister=flags.GetInstanceZoneScopeLister(client)) policy = client.MakeRequests([ (client.apitools_client.instances, 'GetIamPolicy', client.messages.ComputeInstancesGetIamPolicyRequest( resource=instance_ref.instance, zone=instance_ref.zone, project=instance_ref.project)) ])[0] iam_util.AddBindingToIamPolicy(client.messages.Binding, policy, args.member, args.role) # TODO(b/78371568): Construct the ZoneSetPolicyRequest directly # out of the parsed policy. 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]
def AddIamPolicyBindings(resource, members, role): """Adds IAM policy bindings for members with the role on resource.""" iam_client, iam_messages = iam_api.GetClientAndMessages() request = iam_messages.IamProjectsServiceAccountsGetIamPolicyRequest( resource=resource) iam_policy = iam_client.projects_serviceAccounts.GetIamPolicy( request=request) binding_updated = False for member in members: binding_updated |= iam_util.AddBindingToIamPolicy( iam_messages.Binding, iam_policy, member, role) if not binding_updated: log.debug('Skipped setting IAM policy, no changes are needed.') return log.debug('Setting the updated IAM policy.') set_request = iam_messages.IamProjectsServiceAccountsSetIamPolicyRequest( resource=resource, setIamPolicyRequest=iam_messages.SetIamPolicyRequest( policy=iam_policy)) iam_policy = iam_client.projects_serviceAccounts.SetIamPolicy( request=set_request)
def AddPolicyBindingsToCryptoKey(crypto_key_ref, member_roles): """Add IAM policy bindings on the CryptoKey. Does an atomic Read-Modify-Write, adding the members to the roles. Only calls SetIamPolicy if the policy would be different. Args: crypto_key_ref: A resources.Resource naming the CryptoKey. member_roles: List of 2-tuples in the form [(member, role), ...]. Returns: The new IAM Policy. """ messages = base.GetMessagesModule() policy = GetCryptoKeyIamPolicy(crypto_key_ref) policy.version = iam_util.MAX_LIBRARY_IAM_SUPPORTED_VERSION policy_was_updated = False for member, role in member_roles: if iam_util.AddBindingToIamPolicy(messages.Binding, policy, member, role): policy_was_updated = True if policy_was_updated: return SetCryptoKeyIamPolicy(crypto_key_ref, policy, update_mask='bindings,etag') return policy
def Run(self, args): holder = base_classes.ComputeApiHolder(self.ReleaseTrack()) client = holder.client instance_ref = flags.INSTANCE_ARG.ResolveAsResource( args, holder.resources, scope_lister=flags.GetInstanceZoneScopeLister(client)) policy = client.MakeRequests([ (client.apitools_client.instances, 'GetIamPolicy', client.messages.ComputeInstancesGetIamPolicyRequest( resource=instance_ref.instance, zone=instance_ref.zone, project=instance_ref.project)) ])[0] iam_util.AddBindingToIamPolicy(client.messages.Binding, policy, args.member, args.role) 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 _GetModifiedIamPolicy(self, args, policy_binding_type): """Get the current IAM policy and then add/remove bindings as specified. An IAM binding is a pair of role and member. If policy_binding_type is add, the member and role specified in args would be added; if policy_binding_type is remove, the member and role specified in args would be removed. Args: args: The argparse parser. policy_binding_type: string, add or remove. Returns: IAM policy. """ get_iam_method = registry.GetMethod(self.spec.request.collection, 'getIamPolicy', self.spec.request.api_version) get_iam_request = self.arg_generator.CreateRequest( args, use_relative_name=self.spec.request.use_relative_name, override_method=get_iam_method) policy = get_iam_method.Call(get_iam_request) if policy_binding_type == 'add': binding = self.method.GetMessageByName('Binding') iam_util.AddBindingToIamPolicy(binding, policy, args.member, args.role) elif policy_binding_type == 'remove': iam_util.RemoveBindingFromIamPolicy(policy, args.member, args.role) else: pass return policy
def AddIamPolicyBindingServiceAccount(service_account_name, role, member): """Add an IAM policy binding to a service account. Args: service_account_name: The google service account to add the iam policy binding to. role: The role the member is granted. member: The gsa/ksa allowed to act as the defined service account. Returns: Policy: The updated policy. """ iam_client, iam_messages = iam_api_util.GetClientAndMessages() policy = iam_client.projects_serviceAccounts.GetIamPolicy( iam_messages.IamProjectsServiceAccountsGetIamPolicyRequest( resource=iam_util.EmailToAccountResourceName( service_account_name))) iam_util.AddBindingToIamPolicy(iam_messages.Binding, policy, member, role) return iam_client.projects_serviceAccounts.SetIamPolicy( iam_messages.IamProjectsServiceAccountsSetIamPolicyRequest( resource=iam_util.EmailToAccountResourceName(service_account_name), setIamPolicyRequest=iam_messages.SetIamPolicyRequest( policy=policy)))
def AddOrRemoveIamPolicyBinding(self, service_ref, add_binding=True, member=None, role=None): """Add or remove the given IAM policy binding to the provided service. If no members or role are provided, set the IAM policy to the current IAM policy. This is useful for checking whether the authenticated user has the appropriate permissions for setting policies. Args: service_ref: str, The service to which to add the IAM policy. add_binding: bool, Whether to add to or remove from the IAM policy. member: str, One of the users for which the binding applies. role: str, The role to grant the provided members. Returns: A google.iam.v1.TestIamPermissionsResponse. """ messages = self.messages_module oneplatform_service = resource_name_conversion.K8sToOnePlatform( service_ref, self._region) policy = self._GetIamPolicy(oneplatform_service) # Don't modify bindings if not member or roles provided if member and role: if add_binding: iam_util.AddBindingToIamPolicy(messages.Binding, policy, member, role) elif iam_util.BindingInPolicy(policy, member, role): iam_util.RemoveBindingFromIamPolicy(policy, member, role) request = messages.RunProjectsLocationsServicesSetIamPolicyRequest( resource=six.text_type(oneplatform_service), setIamPolicyRequest=messages.SetIamPolicyRequest(policy=policy)) result = self._op_client.projects_locations_services.SetIamPolicy(request) return result
def Run(self, args): datafusion = df.Datafusion() instance_ref = args.CONCEPTS.instance.Parse() if not args.namespace: get_request = datafusion.messages.DatafusionProjectsLocationsInstancesGetIamPolicyRequest( resource=instance_ref.RelativeName()) iam_policy = datafusion.client.projects_locations_instances.GetIamPolicy( get_request) else: get_request = datafusion.messages.DatafusionProjectsLocationsInstancesNamespacesGetIamPolicyRequest( resource='%s/namespaces/%s' % (instance_ref.RelativeName(), args.namespace)) iam_policy = datafusion.client.projects_locations_instances_namespaces.GetIamPolicy( get_request) iam_util.AddBindingToIamPolicy(datafusion.messages.Binding, iam_policy, args.member, args.role) results = data_fusion_iam_util.DoSetIamPolicy(instance_ref, args.namespace, iam_policy, datafusion.messages, datafusion.client) return results
def AddPolicyBindingToCryptoKey(crypto_key_ref, member, role): """Does an atomic Read-Modify-Write, adding the member to the role.""" messages = base.GetMessagesModule() policy = GetCryptoKeyIamPolicy(crypto_key_ref) iam_util.AddBindingToIamPolicy(messages.Binding, policy, member, role) return SetCryptoKeyIamPolicy( crypto_key_ref, policy, update_mask='bindings,etag')
def AddIamPolicyBinding(project_ref, member, role, api_version=DEFAULT_API_VERSION): messages = projects_util.GetMessages(api_version) policy = GetIamPolicy(project_ref, api_version) iam_util.AddBindingToIamPolicy(messages.Binding, policy, member, role) return SetIamPolicy(project_ref, policy, api_version=api_version)
def AddFunctionIamPolicyBinding(function_resource_name, member='allUsers', role='roles/cloudfunctions.invoker'): client = GetApiClientInstance() messages = client.MESSAGES_MODULE policy = GetFunctionIamPolicy(function_resource_name) iam_util.AddBindingToIamPolicy(messages.Binding, policy, member, role) return client.projects_locations_functions.SetIamPolicy( messages.CloudfunctionsProjectsLocationsFunctionsSetIamPolicyRequest( resource=function_resource_name, setIamPolicyRequest=messages.SetIamPolicyRequest(policy=policy)))
def AddIamPolicyBinding(project_ref, member, role): messages = projects_util.GetMessages() try: policy = GetIamPolicy(project_ref) except exceptions.HttpError as error: raise projects_util.ConvertHttpError(error) iam_util.AddBindingToIamPolicy(messages, policy, member, role) 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 image_ref = AddIamPolicyBinding.disk_image_arg.ResolveAsResource( args, holder.resources) get_request = client.messages.ComputeImagesGetIamPolicyRequest( resource=image_ref.image, project=image_ref.project) policy = client.apitools_client.images.GetIamPolicy(get_request) iam_util.AddBindingToIamPolicy(client.messages.Binding, policy, args.member, args.role) set_request = client.messages.ComputeImagesSetIamPolicyRequest( policy=policy, resource=image_ref.image, project=image_ref.project) return client.apitools_client.images.SetIamPolicy(set_request)
def Run(self, args): queues_client = queues.Queues() queues_messages = queues_client.api.messages queue_ref = parsers.ParseQueue(args.queue, args.location) try: policy = queues_client.GetIamPolicy(queue_ref) except apitools_exceptions.HttpNotFoundError: # If the error is a 404, no IAM policy exists, so just create a blank one. policy = queues_messages.Policy() iam_util.AddBindingToIamPolicy(queues_messages.Binding, policy, args.member, args.role) response = queues_client.SetIamPolicy(queue_ref, policy) return response
def Run(self, args): policy = self.iam_client.projects_serviceAccounts.GetIamPolicy( self.messages.IamProjectsServiceAccountsGetIamPolicyRequest( resource=iam_util.EmailToAccountResourceName(args.account))) iam_util.AddBindingToIamPolicy(self.messages, policy, args.member, args.role) return self.iam_client.projects_serviceAccounts.SetIamPolicy( self.messages.IamProjectsServiceAccountsSetIamPolicyRequest( resource=iam_util.EmailToAccountResourceName(args.account), setIamPolicyRequest=self.messages.SetIamPolicyRequest( policy=policy)))
def Run(self, args): try: policy = self.iam_client.projects_serviceAccounts.GetIamPolicy( self.messages.IamProjectsServiceAccountsGetIamPolicyRequest( resource=utils.EmailToAccountResourceName(args.account))) iam_util.AddBindingToIamPolicy(self.messages, policy, args.member, args.role) 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)
def Run(self, args): client, messages = util.GetClientAndMessages() policy = client.projects_serviceAccounts.GetIamPolicy( messages.IamProjectsServiceAccountsGetIamPolicyRequest( resource=iam_util.EmailToAccountResourceName( args.service_account))) iam_util.AddBindingToIamPolicy(messages.Binding, policy, args.member, args.role) return client.projects_serviceAccounts.SetIamPolicy( messages.IamProjectsServiceAccountsSetIamPolicyRequest( resource=iam_util.EmailToAccountResourceName( args.service_account), setIamPolicyRequest=messages.SetIamPolicyRequest( policy=policy)))
def AddIamPolicyBinding(self, topic_ref, member, role): """Adds an IAM Policy binding to a Topic. Args: topic_ref (Resource): Resource reference for subscription to add IAM policy binding to. member (str): The member to add. role (str): The role to assign to the member. Returns: Policy: the updated policy. Raises: api_exception.HttpException: If either of the requests failed. """ policy = self.GetIamPolicy(topic_ref) iam_util.AddBindingToIamPolicy(self.messages.Binding, policy, member, role) return self.SetIamPolicy(topic_ref, policy)
def AddIamPolicyBinding(self, object_ref, member, role): """Adds an IAM role to a member on an object. Args: self: The self of the class this is set on. object_ref: Resource, reference for object IAM policy belongs to. member: the member the binding is being added to. role: the role which to bind to the member. Returns: The IAM policy. """ policy = self.GetIamPolicy(object_ref) iam_util.AddBindingToIamPolicy(self.messages.ApigatewayBinding, policy, member, role) return self.SetIamPolicy(object_ref, policy, 'bindings,etag')
def Run(self, args): messages = self.OrganizationsMessages() get_policy_request = ( messages.CloudresourcemanagerOrganizationsGetIamPolicyRequest( organizationsId=args.id, getIamPolicyRequest=messages.GetIamPolicyRequest())) policy = self.OrganizationsClient().GetIamPolicy(get_policy_request) iam_util.AddBindingToIamPolicy(messages, policy, args.member, args.role) set_policy_request = ( messages.CloudresourcemanagerOrganizationsSetIamPolicyRequest( organizationsId=args.id, setIamPolicyRequest=messages.SetIamPolicyRequest(policy=policy))) return self.OrganizationsClient().SetIamPolicy(set_policy_request)
def testAddBindingToIamPolicy(self): parser = argparse.ArgumentParser() ai = self.getDummyArgumentInterceptor(parser) iam_util.AddArgsForAddIamPolicyBinding(ai) args = parser.parse_args( ['--role=roles/editor', '--member=user:[email protected]']) expected_policy = copy.deepcopy(self.TEST_IAM_POLICY) expected_policy.bindings.append( self.messages.Binding(members=['user:[email protected]'], role='roles/editor')) actual_policy = copy.deepcopy(self.TEST_IAM_POLICY) iam_util.AddBindingToIamPolicy(self.messages.Binding, actual_policy, args.member, args.role) self.assertEqual(actual_policy, expected_policy)
def Run(self, args): holder = base_classes.ComputeApiHolder(self.ReleaseTrack()) client = holder.client image_ref = AddIamPolicyBinding.disk_image_arg.ResolveAsResource( args, holder.resources) get_request = client.messages.ComputeImagesGetIamPolicyRequest( resource=image_ref.image, project=image_ref.project) policy = client.apitools_client.images.GetIamPolicy(get_request) iam_util.AddBindingToIamPolicy(client.messages.Binding, policy, args.member, args.role) # TODO(b/78371568): Construct the GlobalSetPolicyRequest directly # out of the parsed policy. set_request = client.messages.ComputeImagesSetIamPolicyRequest( globalSetPolicyRequest=client.messages.GlobalSetPolicyRequest( bindings=policy.bindings, etag=policy.etag), resource=image_ref.image, project=image_ref.project) return client.apitools_client.images.SetIamPolicy(set_request)
def Run(self, args): holder = base_classes.ComputeApiHolder(self.ReleaseTrack()) client = holder.client snapshot_ref = AddIamPolicyBinding.snapshot_arg.ResolveAsResource( args, holder.resources) get_request = client.messages.ComputeSnapshotsGetIamPolicyRequest( resource=snapshot_ref.snapshot, project=snapshot_ref.project) policy = client.apitools_client.snapshots.GetIamPolicy(get_request) iam_util.AddBindingToIamPolicy(client.messages.Binding, policy, args.member, args.role) set_request = client.messages.ComputeSnapshotsSetIamPolicyRequest( globalSetPolicyRequest=client.messages.GlobalSetPolicyRequest( bindings=policy.bindings, etag=policy.etag), resource=snapshot_ref.snapshot, project=snapshot_ref.project) return client.apitools_client.snapshots.SetIamPolicy(set_request)
def AddIamPolicyBindings(project_ref, member_roles, api_version=DEFAULT_API_VERSION): """Adds iam bindings to project_ref's iam policy. Args: project_ref: The project for the binding member_roles: List of 2-tuples of the form [(member, role), ...]. api_version: The version of the api Returns: The updated IAM Policy """ messages = projects_util.GetMessages(api_version) policy = GetIamPolicy(project_ref, api_version) for member, role in member_roles: iam_util.AddBindingToIamPolicy(messages.Binding, policy, member, role) return SetIamPolicy(project_ref, policy, api_version=api_version)
def AddIamPolicyBinding(self, bucket_ref, member, role): """Add an IAM policy binding on the specified bucket. Does an atomic Read-Modify-Write, adding the member to the role. Args: bucket_ref: storage_util.BucketReference to the bucket with the policy. member: Principal to add to the policy binding. role: Role to add to the policy binding. Returns: The new IAM Policy. """ policy = self.GetIamPolicy(bucket_ref) policy.version = iam_util.MAX_LIBRARY_IAM_SUPPORTED_VERSION iam_util.AddBindingToIamPolicy( self.messages.Policy.BindingsValueListEntry, policy, member, role) return self.SetIamPolicy(bucket_ref, policy)
def Run(self, args): """This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Returns: Some value that we want to have printed later. """ adapter = self.context['api_adapter'] location_get = self.context['location_get'] location = location_get(args) policy = adapter.GetIamPolicy(adapter.ParseCluster( args.name, location)) iam_util.AddBindingToIamPolicy(adapter.messages.GoogleIamV1Binding, policy, args.member, args.role) return adapter.SetIamPolicy(adapter.ParseCluster(args.name, location), policy)