Best Python code snippet using localstack_python
iam_api.py
Source:iam_api.py  
1# Copyright 2016 Google Inc. All rights reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14#15# EDITING INSTRUCTIONS16# This file was generated from the file17# https://github.com/google/googleapis/blob/master/google/iam/admin/v1/iam.proto,18# and updates to that file get reflected here through a refresh process.19# For the short term, the refresh process will only be runnable by Google engineers.20#21# The only allowed edits are to method and file documentation. A 3-way22# merge preserves those additions if the generated source changes.23"""Accesses the google.iam.admin.v1 IAM API."""24import json25import os26import pkg_resources27import platform28from google.gax import api_callable29from google.gax import config30from google.gax import path_template31import google.gax32from google.cloud.gapic.iam_admin.v1 import enums33from google.iam.admin.v1 import iam_pb234from google.iam.v1 import iam_policy_pb235from google.iam.v1 import policy_pb236_PageDesc = google.gax.PageDescriptor37class IAMApi(object):38    """39    Creates and manages service account objects.40    Service account is an account that belongs to your project instead41    of to an individual end user. It is used to authenticate calls42    to a Google API.43    To create a service account, specify the ``project_id`` and ``account_id``44    for the account.  The ``account_id`` is unique within the project, and used45    to generate the service account email address and a stable46    ``unique_id``.47    All other methods can identify accounts using the format48    ``projects/{project}/serviceAccounts/{account}``.49    Using ``-`` as a wildcard for the project will infer the project from50    the account. The ``account`` value can be the ``email`` address or the51    ``unique_id`` of the service account.52    """53    SERVICE_ADDRESS = 'iam.googleapis.com'54    """The default address of the service."""55    DEFAULT_SERVICE_PORT = 44356    """The default port of the service."""57    _CODE_GEN_NAME_VERSION = 'gapic/0.1.0'58    _GAX_VERSION = pkg_resources.get_distribution('google-gax').version59    _PAGE_DESCRIPTORS = {60        'list_service_accounts': _PageDesc('page_token', 'next_page_token',61                                           'accounts')62    }63    # The scopes needed to make gRPC calls to all of the methods defined in64    # this service65    _ALL_SCOPES = ('https://www.googleapis.com/auth/cloud-platform',66                   'https://www.googleapis.com/auth/iam', )67    _PROJECT_PATH_TEMPLATE = path_template.PathTemplate('projects/{project}')68    _SERVICE_ACCOUNT_PATH_TEMPLATE = path_template.PathTemplate(69        'projects/{project}/serviceAccounts/{service_account}')70    _KEY_PATH_TEMPLATE = path_template.PathTemplate(71        'projects/{project}/serviceAccounts/{service_account}/keys/{key}')72    @classmethod73    def project_path(cls, project):74        """Returns a fully-qualified project resource name string."""75        return cls._PROJECT_PATH_TEMPLATE.render({'project': project, })76    @classmethod77    def service_account_path(cls, project, service_account):78        """Returns a fully-qualified service_account resource name string."""79        return cls._SERVICE_ACCOUNT_PATH_TEMPLATE.render({80            'project': project,81            'service_account': service_account,82        })83    @classmethod84    def key_path(cls, project, service_account, key):85        """Returns a fully-qualified key resource name string."""86        return cls._KEY_PATH_TEMPLATE.render({87            'project': project,88            'service_account': service_account,89            'key': key,90        })91    @classmethod92    def match_project_from_project_name(cls, project_name):93        """Parses the project from a project resource.94        Args:95          project_name (string): A fully-qualified path representing a project96            resource.97        Returns:98          A string representing the project.99        """100        return cls._PROJECT_PATH_TEMPLATE.match(project_name).get('project')101    @classmethod102    def match_project_from_service_account_name(cls, service_account_name):103        """Parses the project from a service_account resource.104        Args:105          service_account_name (string): A fully-qualified path representing a service_account106            resource.107        Returns:108          A string representing the project.109        """110        return cls._SERVICE_ACCOUNT_PATH_TEMPLATE.match(111            service_account_name).get('project')112    @classmethod113    def match_service_account_from_service_account_name(cls,114                                                        service_account_name):115        """Parses the service_account from a service_account resource.116        Args:117          service_account_name (string): A fully-qualified path representing a service_account118            resource.119        Returns:120          A string representing the service_account.121        """122        return cls._SERVICE_ACCOUNT_PATH_TEMPLATE.match(123            service_account_name).get('service_account')124    @classmethod125    def match_project_from_key_name(cls, key_name):126        """Parses the project from a key resource.127        Args:128          key_name (string): A fully-qualified path representing a key129            resource.130        Returns:131          A string representing the project.132        """133        return cls._KEY_PATH_TEMPLATE.match(key_name).get('project')134    @classmethod135    def match_service_account_from_key_name(cls, key_name):136        """Parses the service_account from a key resource.137        Args:138          key_name (string): A fully-qualified path representing a key139            resource.140        Returns:141          A string representing the service_account.142        """143        return cls._KEY_PATH_TEMPLATE.match(key_name).get('service_account')144    @classmethod145    def match_key_from_key_name(cls, key_name):146        """Parses the key from a key resource.147        Args:148          key_name (string): A fully-qualified path representing a key149            resource.150        Returns:151          A string representing the key.152        """153        return cls._KEY_PATH_TEMPLATE.match(key_name).get('key')154    def __init__(self,155                 service_path=SERVICE_ADDRESS,156                 port=DEFAULT_SERVICE_PORT,157                 channel=None,158                 metadata_transformer=None,159                 ssl_creds=None,160                 scopes=None,161                 client_config=None,162                 app_name='gax',163                 app_version=_GAX_VERSION):164        """Constructor.165        Args:166          service_path (string): The domain name of the API remote host.167          port (int): The port on which to connect to the remote host.168          channel (:class:`grpc.Channel`): A ``Channel`` instance through169            which to make calls.170          ssl_creds (:class:`grpc.ChannelCredentials`): A171            ``ChannelCredentials`` instance for use with an SSL-enabled172            channel.173          client_config (dict):174            A dictionary for call options for each method. See175            :func:`google.gax.construct_settings` for the structure of176            this data. Falls back to the default config if not specified177            or the specified config is missing data points.178          metadata_transformer (Callable[[], list]): A function that creates179             the metadata for requests.180          app_name (string): The codename of the calling service.181          app_version (string): The version of the calling service.182        Returns:183          A IAMApi object.184        """185        if scopes is None:186            scopes = self._ALL_SCOPES187        if client_config is None:188            client_config = {}189        goog_api_client = '{}/{} {} gax/{} python/{}'.format(190            app_name, app_version, self._CODE_GEN_NAME_VERSION,191            self._GAX_VERSION, platform.python_version())192        metadata = [('x-goog-api-client', goog_api_client)]193        default_client_config = json.loads(194            pkg_resources.resource_string(__name__, 'iam_client_config.json')195            .decode())196        defaults = api_callable.construct_settings(197            'google.iam.admin.v1.IAM',198            default_client_config,199            client_config,200            config.STATUS_CODE_NAMES,201            kwargs={'metadata': metadata},202            page_descriptors=self._PAGE_DESCRIPTORS)203        self.iam_stub = config.create_stub(204            iam_pb2.IAMStub,205            service_path,206            port,207            ssl_creds=ssl_creds,208            channel=channel,209            metadata_transformer=metadata_transformer,210            scopes=scopes)211        self._list_service_accounts = api_callable.create_api_call(212            self.iam_stub.ListServiceAccounts,213            settings=defaults['list_service_accounts'])214        self._get_service_account = api_callable.create_api_call(215            self.iam_stub.GetServiceAccount,216            settings=defaults['get_service_account'])217        self._create_service_account = api_callable.create_api_call(218            self.iam_stub.CreateServiceAccount,219            settings=defaults['create_service_account'])220        self._update_service_account = api_callable.create_api_call(221            self.iam_stub.UpdateServiceAccount,222            settings=defaults['update_service_account'])223        self._delete_service_account = api_callable.create_api_call(224            self.iam_stub.DeleteServiceAccount,225            settings=defaults['delete_service_account'])226        self._list_service_account_keys = api_callable.create_api_call(227            self.iam_stub.ListServiceAccountKeys,228            settings=defaults['list_service_account_keys'])229        self._get_service_account_key = api_callable.create_api_call(230            self.iam_stub.GetServiceAccountKey,231            settings=defaults['get_service_account_key'])232        self._create_service_account_key = api_callable.create_api_call(233            self.iam_stub.CreateServiceAccountKey,234            settings=defaults['create_service_account_key'])235        self._delete_service_account_key = api_callable.create_api_call(236            self.iam_stub.DeleteServiceAccountKey,237            settings=defaults['delete_service_account_key'])238        self._sign_blob = api_callable.create_api_call(239            self.iam_stub.SignBlob, settings=defaults['sign_blob'])240        self._get_iam_policy = api_callable.create_api_call(241            self.iam_stub.GetIamPolicy, settings=defaults['get_iam_policy'])242        self._set_iam_policy = api_callable.create_api_call(243            self.iam_stub.SetIamPolicy, settings=defaults['set_iam_policy'])244        self._test_iam_permissions = api_callable.create_api_call(245            self.iam_stub.TestIamPermissions,246            settings=defaults['test_iam_permissions'])247        self._query_grantable_roles = api_callable.create_api_call(248            self.iam_stub.QueryGrantableRoles,249            settings=defaults['query_grantable_roles'])250    # Service calls251    def list_service_accounts(self, name, page_size=0, options=None):252        """253        Lists ``ServiceAccounts`` for a project.254        Example:255          >>> from google.cloud.gapic.iam_admin.v1 import iam_api256          >>> from google.gax import CallOptions, INITIAL_PAGE257          >>> api = iam_api.IAMApi()258          >>> name = api.project_path('[PROJECT]')259          >>>260          >>> # Iterate over all results261          >>> for element in api.list_service_accounts(name):262          >>>   # process element263          >>>   pass264          >>>265          >>> # Or iterate over results one page at a time266          >>> for page in api.list_service_accounts(name, options=CallOptions(page_token=INITIAL_PAGE)):267          >>>   for element in page:268          >>>     # process element269          >>>     pass270        Args:271          name (string): Required. The resource name of the project associated with the service272            accounts, such as ``projects/my-project-123``.273          page_size (int): The maximum number of resources contained in the274            underlying API response. If page streaming is performed per-275            resource, this parameter does not affect the return value. If page276            streaming is performed per-page, this determines the maximum number277            of resources in a page.278          options (:class:`google.gax.CallOptions`): Overrides the default279            settings for this call, e.g, timeout, retries etc.280        Returns:281          A :class:`google.gax.PageIterator` instance. By default, this282          is an iterable of :class:`google.iam.admin.v1.iam_pb2.ServiceAccount` instances.283          This object can also be configured to iterate over the pages284          of the response through the `CallOptions` parameter.285        Raises:286          :exc:`google.gax.errors.GaxError` if the RPC is aborted.287          :exc:`ValueError` if the parameters are invalid.288        """289        request = iam_pb2.ListServiceAccountsRequest(290            name=name, page_size=page_size)291        return self._list_service_accounts(request, options)292    def get_service_account(self, name, options=None):293        """294        Gets a ``ServiceAccount``.295        Example:296          >>> from google.cloud.gapic.iam_admin.v1 import iam_api297          >>> api = iam_api.IAMApi()298          >>> name = api.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]')299          >>> response = api.get_service_account(name)300        Args:301          name (string): The resource name of the service account in the following format:302            ``projects/{project}/serviceAccounts/{account}``.303            Using ``-`` as a wildcard for the project will infer the project from304            the account. The ``account`` value can be the ``email`` address or the305            ``unique_id`` of the service account.306          options (:class:`google.gax.CallOptions`): Overrides the default307            settings for this call, e.g, timeout, retries etc.308        Returns:309          A :class:`google.iam.admin.v1.iam_pb2.ServiceAccount` instance.310        Raises:311          :exc:`google.gax.errors.GaxError` if the RPC is aborted.312          :exc:`ValueError` if the parameters are invalid.313        """314        request = iam_pb2.GetServiceAccountRequest(name=name)315        return self._get_service_account(request, options)316    def create_service_account(self,317                               name,318                               account_id,319                               service_account=None,320                               options=None):321        """322        Creates a ``ServiceAccount``323        and returns it.324        Example:325          >>> from google.cloud.gapic.iam_admin.v1 import iam_api326          >>> api = iam_api.IAMApi()327          >>> name = api.project_path('[PROJECT]')328          >>> account_id = ''329          >>> response = api.create_service_account(name, account_id)330        Args:331          name (string): Required. The resource name of the project associated with the service332            accounts, such as ``projects/my-project-123``.333          account_id (string): Required. The account id that is used to generate the service account334            email address and a stable unique id. It is unique within a project,335            must be 6-30 characters long, and match the regular expression336            ```a-z <https://cloud.google.com[-a-z0-9]*[a-z0-9]>`_`` to comply with RFC1035.337          service_account (:class:`google.iam.admin.v1.iam_pb2.ServiceAccount`): The ``ServiceAccount`` resource to create.338            Currently, only the following values are user assignable:339            ``display_name`` .340          options (:class:`google.gax.CallOptions`): Overrides the default341            settings for this call, e.g, timeout, retries etc.342        Returns:343          A :class:`google.iam.admin.v1.iam_pb2.ServiceAccount` instance.344        Raises:345          :exc:`google.gax.errors.GaxError` if the RPC is aborted.346          :exc:`ValueError` if the parameters are invalid.347        """348        if service_account is None:349            service_account = iam_pb2.ServiceAccount()350        request = iam_pb2.CreateServiceAccountRequest(351            name=name, account_id=account_id, service_account=service_account)352        return self._create_service_account(request, options)353    def update_service_account(self,354                               etag,355                               name='',356                               project_id='',357                               unique_id='',358                               email='',359                               display_name='',360                               oauth2_client_id='',361                               options=None):362        """363        Updates a ``ServiceAccount``.364        Currently, only the following fields are updatable:365        ``display_name`` .366        The ``etag`` is mandatory.367        Example:368          >>> from google.cloud.gapic.iam_admin.v1 import iam_api369          >>> api = iam_api.IAMApi()370          >>> etag = ''371          >>> response = api.update_service_account(etag)372        Args:373          name (string): The resource name of the service account in the following format:374            ``projects/{project}/serviceAccounts/{account}``.375            Requests using ``-`` as a wildcard for the project will infer the project376            from the ``account`` and the ``account`` value can be the ``email`` address or377            the ``unique_id`` of the service account.378            In responses the resource name will always be in the format379            ``projects/{project}/serviceAccounts/{email}``.380          project_id (string): @OutputOnly The id of the project that owns the service account.381          unique_id (string): @OutputOnly The unique and stable id of the service account.382          email (string): @OutputOnly The email address of the service account.383          display_name (string): Optional. A user-specified description of the service account.  Must be384            fewer than 100 UTF-8 bytes.385          etag (bytes): Used to perform a consistent read-modify-write.386          oauth2_client_id (string): @OutputOnly. The OAuth2 client id for the service account.387            This is used in conjunction with the OAuth2 clientconfig API to make388            three legged OAuth2 (3LO) flows to access the data of Google users.389          options (:class:`google.gax.CallOptions`): Overrides the default390            settings for this call, e.g, timeout, retries etc.391        Returns:392          A :class:`google.iam.admin.v1.iam_pb2.ServiceAccount` instance.393        Raises:394          :exc:`google.gax.errors.GaxError` if the RPC is aborted.395          :exc:`ValueError` if the parameters are invalid.396        """397        request = iam_pb2.ServiceAccount(398            etag=etag,399            name=name,400            project_id=project_id,401            unique_id=unique_id,402            email=email,403            display_name=display_name,404            oauth2_client_id=oauth2_client_id)405        return self._update_service_account(request, options)406    def delete_service_account(self, name, options=None):407        """408        Deletes a ``ServiceAccount``.409        Example:410          >>> from google.cloud.gapic.iam_admin.v1 import iam_api411          >>> api = iam_api.IAMApi()412          >>> name = api.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]')413          >>> api.delete_service_account(name)414        Args:415          name (string): The resource name of the service account in the following format:416            ``projects/{project}/serviceAccounts/{account}``.417            Using ``-`` as a wildcard for the project will infer the project from418            the account. The ``account`` value can be the ``email`` address or the419            ``unique_id`` of the service account.420          options (:class:`google.gax.CallOptions`): Overrides the default421            settings for this call, e.g, timeout, retries etc.422        Raises:423          :exc:`google.gax.errors.GaxError` if the RPC is aborted.424          :exc:`ValueError` if the parameters are invalid.425        """426        request = iam_pb2.DeleteServiceAccountRequest(name=name)427        self._delete_service_account(request, options)428    def list_service_account_keys(self, name, key_types=None, options=None):429        """430        Lists ``ServiceAccountKeys``.431        Example:432          >>> from google.cloud.gapic.iam_admin.v1 import iam_api433          >>> api = iam_api.IAMApi()434          >>> name = api.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]')435          >>> response = api.list_service_account_keys(name)436        Args:437          name (string): The resource name of the service account in the following format:438            ``projects/{project}/serviceAccounts/{account}``.439            Using ``-`` as a wildcard for the project, will infer the project from440            the account. The ``account`` value can be the ``email`` address or the441            ``unique_id`` of the service account.442          key_types (list[enum :class:`google.cloud.gapic.iam_admin.v1.enums.ListServiceAccountKeysRequest.KeyType`]): Filters the types of keys the user wants to include in the list443            response. Duplicate key types are not allowed. If no key type444            is provided, all keys are returned.445          options (:class:`google.gax.CallOptions`): Overrides the default446            settings for this call, e.g, timeout, retries etc.447        Returns:448          A :class:`google.iam.admin.v1.iam_pb2.ListServiceAccountKeysResponse` instance.449        Raises:450          :exc:`google.gax.errors.GaxError` if the RPC is aborted.451          :exc:`ValueError` if the parameters are invalid.452        """453        if key_types is None:454            key_types = []455        request = iam_pb2.ListServiceAccountKeysRequest(456            name=name, key_types=key_types)457        return self._list_service_account_keys(request, options)458    def get_service_account_key(self, name, public_key_type=None,459                                options=None):460        """461        Gets the ``ServiceAccountKey``462        by key id.463        Example:464          >>> from google.cloud.gapic.iam_admin.v1 import iam_api465          >>> api = iam_api.IAMApi()466          >>> name = api.key_path('[PROJECT]', '[SERVICE_ACCOUNT]', '[KEY]')467          >>> response = api.get_service_account_key(name)468        Args:469          name (string): The resource name of the service account key in the following format:470            ``projects/{project}/serviceAccounts/{account}/keys/{key}``.471            Using ``-`` as a wildcard for the project will infer the project from472            the account. The ``account`` value can be the ``email`` address or the473            ``unique_id`` of the service account.474          public_key_type (enum :class:`google.cloud.gapic.iam_admin.v1.enums.ServiceAccountPublicKeyType`): The output format of the public key requested.475            X509_PEM is the default output format.476          options (:class:`google.gax.CallOptions`): Overrides the default477            settings for this call, e.g, timeout, retries etc.478        Returns:479          A :class:`google.iam.admin.v1.iam_pb2.ServiceAccountKey` instance.480        Raises:481          :exc:`google.gax.errors.GaxError` if the RPC is aborted.482          :exc:`ValueError` if the parameters are invalid.483        """484        if public_key_type is None:485            public_key_type = enums.ServiceAccountPublicKeyType.TYPE_NONE486        request = iam_pb2.GetServiceAccountKeyRequest(487            name=name, public_key_type=public_key_type)488        return self._get_service_account_key(request, options)489    def create_service_account_key(self,490                                   name,491                                   private_key_type=None,492                                   key_algorithm=None,493                                   options=None):494        """495        Creates a ``ServiceAccountKey``496        and returns it.497        Example:498          >>> from google.cloud.gapic.iam_admin.v1 import iam_api499          >>> api = iam_api.IAMApi()500          >>> name = api.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]')501          >>> response = api.create_service_account_key(name)502        Args:503          name (string): The resource name of the service account in the following format:504            ``projects/{project}/serviceAccounts/{account}``.505            Using ``-`` as a wildcard for the project will infer the project from506            the account. The ``account`` value can be the ``email`` address or the507            ``unique_id`` of the service account.508          private_key_type (enum :class:`google.cloud.gapic.iam_admin.v1.enums.ServiceAccountPrivateKeyType`): The output format of the private key. ``GOOGLE_CREDENTIALS_FILE`` is the509            default output format.510          key_algorithm (enum :class:`google.cloud.gapic.iam_admin.v1.enums.ServiceAccountKeyAlgorithm`): Which type of key and algorithm to use for the key.511            The default is currently a 4K RSA key.  However this may change in the512            future.513          options (:class:`google.gax.CallOptions`): Overrides the default514            settings for this call, e.g, timeout, retries etc.515        Returns:516          A :class:`google.iam.admin.v1.iam_pb2.ServiceAccountKey` instance.517        Raises:518          :exc:`google.gax.errors.GaxError` if the RPC is aborted.519          :exc:`ValueError` if the parameters are invalid.520        """521        if private_key_type is None:522            private_key_type = enums.ServiceAccountPrivateKeyType.TYPE_UNSPECIFIED523        if key_algorithm is None:524            key_algorithm = enums.ServiceAccountKeyAlgorithm.KEY_ALG_UNSPECIFIED525        request = iam_pb2.CreateServiceAccountKeyRequest(526            name=name,527            private_key_type=private_key_type,528            key_algorithm=key_algorithm)529        return self._create_service_account_key(request, options)530    def delete_service_account_key(self, name, options=None):531        """532        Deletes a ``ServiceAccountKey``.533        Example:534          >>> from google.cloud.gapic.iam_admin.v1 import iam_api535          >>> api = iam_api.IAMApi()536          >>> name = api.key_path('[PROJECT]', '[SERVICE_ACCOUNT]', '[KEY]')537          >>> api.delete_service_account_key(name)538        Args:539          name (string): The resource name of the service account key in the following format:540            ``projects/{project}/serviceAccounts/{account}/keys/{key}``.541            Using ``-`` as a wildcard for the project will infer the project from542            the account. The ``account`` value can be the ``email`` address or the543            ``unique_id`` of the service account.544          options (:class:`google.gax.CallOptions`): Overrides the default545            settings for this call, e.g, timeout, retries etc.546        Raises:547          :exc:`google.gax.errors.GaxError` if the RPC is aborted.548          :exc:`ValueError` if the parameters are invalid.549        """550        request = iam_pb2.DeleteServiceAccountKeyRequest(name=name)551        self._delete_service_account_key(request, options)552    def sign_blob(self, name, bytes_to_sign, options=None):553        """554        Signs a blob using a service account's system-managed private key.555        Example:556          >>> from google.cloud.gapic.iam_admin.v1 import iam_api557          >>> api = iam_api.IAMApi()558          >>> name = api.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]')559          >>> bytes_to_sign = ''560          >>> response = api.sign_blob(name, bytes_to_sign)561        Args:562          name (string): The resource name of the service account in the following format:563            ``projects/{project}/serviceAccounts/{account}``.564            Using ``-`` as a wildcard for the project will infer the project from565            the account. The ``account`` value can be the ``email`` address or the566            ``unique_id`` of the service account.567          bytes_to_sign (bytes): The bytes to sign.568          options (:class:`google.gax.CallOptions`): Overrides the default569            settings for this call, e.g, timeout, retries etc.570        Returns:571          A :class:`google.iam.admin.v1.iam_pb2.SignBlobResponse` instance.572        Raises:573          :exc:`google.gax.errors.GaxError` if the RPC is aborted.574          :exc:`ValueError` if the parameters are invalid.575        """576        request = iam_pb2.SignBlobRequest(577            name=name, bytes_to_sign=bytes_to_sign)578        return self._sign_blob(request, options)579    def get_iam_policy(self, resource, options=None):580        """581        Returns the IAM access control policy for a582        ``ServiceAccount``.583        Example:584          >>> from google.cloud.gapic.iam_admin.v1 import iam_api585          >>> api = iam_api.IAMApi()586          >>> resource = api.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]')587          >>> response = api.get_iam_policy(resource)588        Args:589          resource (string): REQUIRED: The resource for which the policy is being requested.590            ``resource`` is usually specified as a path. For example, a Project591            resource is specified as ``projects/{project}``.592          options (:class:`google.gax.CallOptions`): Overrides the default593            settings for this call, e.g, timeout, retries etc.594        Returns:595          A :class:`google.iam.v1.policy_pb2.Policy` instance.596        Raises:597          :exc:`google.gax.errors.GaxError` if the RPC is aborted.598          :exc:`ValueError` if the parameters are invalid.599        """600        request = iam_policy_pb2.GetIamPolicyRequest(resource=resource)601        return self._get_iam_policy(request, options)602    def set_iam_policy(self, resource, policy, options=None):603        """604        Sets the IAM access control policy for a605        ``ServiceAccount``.606        Example:607          >>> from google.cloud.gapic.iam_admin.v1 import iam_api608          >>> from google.iam.v1 import policy_pb2609          >>> api = iam_api.IAMApi()610          >>> resource = api.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]')611          >>> policy = policy_pb2.Policy()612          >>> response = api.set_iam_policy(resource, policy)613        Args:614          resource (string): REQUIRED: The resource for which the policy is being specified.615            ``resource`` is usually specified as a path. For example, a Project616            resource is specified as ``projects/{project}``.617          policy (:class:`google.iam.v1.policy_pb2.Policy`): REQUIRED: The complete policy to be applied to the ``resource``. The size of618            the policy is limited to a few 10s of KB. An empty policy is a619            valid policy but certain Cloud Platform services (such as Projects)620            might reject them.621          options (:class:`google.gax.CallOptions`): Overrides the default622            settings for this call, e.g, timeout, retries etc.623        Returns:624          A :class:`google.iam.v1.policy_pb2.Policy` instance.625        Raises:626          :exc:`google.gax.errors.GaxError` if the RPC is aborted.627          :exc:`ValueError` if the parameters are invalid.628        """629        request = iam_policy_pb2.SetIamPolicyRequest(630            resource=resource, policy=policy)631        return self._set_iam_policy(request, options)632    def test_iam_permissions(self, resource, permissions, options=None):633        """634        Tests the specified permissions against the IAM access control policy635        for a ``ServiceAccount``.636        Example:637          >>> from google.cloud.gapic.iam_admin.v1 import iam_api638          >>> api = iam_api.IAMApi()639          >>> resource = api.service_account_path('[PROJECT]', '[SERVICE_ACCOUNT]')640          >>> permissions = []641          >>> response = api.test_iam_permissions(resource, permissions)642        Args:643          resource (string): REQUIRED: The resource for which the policy detail is being requested.644            ``resource`` is usually specified as a path. For example, a Project645            resource is specified as ``projects/{project}``.646          permissions (list[string]): The set of permissions to check for the ``resource``. Permissions with647            wildcards (such as '*' or 'storage.*') are not allowed. For more648            information see649            `IAM Overview <https://cloud.google.com/iam/docs/overview#permissions>`_.650          options (:class:`google.gax.CallOptions`): Overrides the default651            settings for this call, e.g, timeout, retries etc.652        Returns:653          A :class:`google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse` instance.654        Raises:655          :exc:`google.gax.errors.GaxError` if the RPC is aborted.656          :exc:`ValueError` if the parameters are invalid.657        """658        request = iam_policy_pb2.TestIamPermissionsRequest(659            resource=resource, permissions=permissions)660        return self._test_iam_permissions(request, options)661    def query_grantable_roles(self, full_resource_name, options=None):662        """663        Queries roles that can be granted on a particular resource.664        A role is grantable if it can be used as the role in a binding for a policy665        for that resource.666        Example:667          >>> from google.cloud.gapic.iam_admin.v1 import iam_api668          >>> api = iam_api.IAMApi()669          >>> full_resource_name = ''670          >>> response = api.query_grantable_roles(full_resource_name)671        Args:672          full_resource_name (string): Required. The full resource name to query from the list of grantable roles.673            The name follows the Google Cloud Platform resource format.674            For example, a Cloud Platform project with id ``my-project`` will be named675            ``//cloudresourcemanager.googleapis.com/projects/my-project``.676          options (:class:`google.gax.CallOptions`): Overrides the default677            settings for this call, e.g, timeout, retries etc.678        Returns:679          A :class:`google.iam.admin.v1.iam_pb2.QueryGrantableRolesResponse` instance.680        Raises:681          :exc:`google.gax.errors.GaxError` if the RPC is aborted.682          :exc:`ValueError` if the parameters are invalid.683        """684        request = iam_pb2.QueryGrantableRolesRequest(685            full_resource_name=full_resource_name)...spin.py
Source:spin.py  
1import sys2import base643from modules import rest_api4from modules import auth as Auth5from modules import args_parser6from modules.logging import log7from modules import spin_pipe as pipeline8from modules import spin_exec as execution9import requests10from time import sleep11def wait_for_start(config, iam_api, execution_id, args):12    log.info("Checking Execution Status")13    execution_status = "NOT STARTED"14    while(execution_status != "RUNNING"):15        url = '{}/executions?executionIds={}'.format(config['gate']['endpoint'], execution_id)16        headers = {'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Bearer {}'.format(iam_api)}17        response = requests.get(url, headers=headers, verify=False)18        if response.status_code != 200:19           log.error(f'Error while fetching execution status from server {url}')20           sys.exit(1)21        response_json = response.json()22        execution_status = response_json[0]['status']23        if execution_status != 'RUNNING':24            log.info("Pipeline not started yet. Waiting {} sec".format(args.delay))25            sleep(args.delay)26    log.info("Pipeline Status is %s" % execution_status)27def check_execution_status(config, iam_api, execution_id, args):28    log.info("Checking Execution Status")29    excepted_statuses = ['SUSPENDED', 'SUCCEEDED', 'TERMINAL', 'CANCELED', 'STOPPED']30    execution_status = "RUNNING"31    while(execution_status not in excepted_statuses):32        url = '{}/executions?executionIds={}'.format(config['gate']['endpoint'], execution_id)33        headers = {'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Bearer {}'.format(iam_api)}34        response = requests.get(url, headers=headers, verify=False)35        if response.status_code != 200:36            log.error('Error while fetching execution status from server {url}')37            sys.exit(1)38        response_json = response.json()39        execution_status = response_json[0]['status']40        if execution_status not in excepted_statuses:41            log.info("Pipeline is in {} state. Waiting {} sec".format(execution_status, args.delay))42            sleep(args.delay)43    log.info("Pipeline Status is %s" % execution_status)44def main():45    args = args_parser.parse_args()46    config = args_parser.read_config(args)47    iam_api, iam_refresh = Auth.get_iam_api_key(config)48    if args.Operation == 'wait_for_start':49        pipeline_id = pipeline.get_pipelineId(config, args, iam_api)50        execution_id = execution.get_executionId(config, args, iam_api)51        wait_for_start(config, iam_api, execution_id, args)52    elif args.Operation == 'check_status':53        pipeline_id = pipeline.get_pipelineId(config, args, iam_api)54        execution_id = execution.get_executionId(config, args, iam_api)55        check_execution_status(config, iam_api, execution_id, args)56if __name__ == '__main__':...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
