def create_service_account()

in python-cli/mft_cli/airavata_mft_cli/storage/gcs.py [0:0]


def create_service_account(project_id, name, display_name, credentials):
    """Creates a service account."""

    service = googleapiclient.discovery.build('iam', 'v1', credentials=credentials)
    my_service_account = service.projects().serviceAccounts().create(
        name='projects/' + project_id,
        body={
            'accountId': name,
            'serviceAccount': {
                'displayName': display_name
            }
        }).execute()

    print('Created service account: ' + my_service_account['email'])

    resource_service = googleapiclient.discovery.build('cloudresourcemanager', 'v1', credentials=credentials)
    policy = resource_service.projects().getIamPolicy(resource=project_id).execute()
    account_handle = f"serviceAccount:{my_service_account['email']}"

    # Add policy
    modified = False
    roles = [role["role"] for role in policy["bindings"]]
    target_role = "roles/storage.admin"  # Service account role which can transfer GCS files
    if target_role not in roles:
        for role in policy["bindings"]:
            if role["role"] == target_role:
                if account_handle not in role["members"]:
                    role["members"].append(account_handle)
                    modified = True

    else:  # role does not exist
        policy["bindings"].append({"role": target_role, "members": [account_handle]})
        modified = True

    if modified:  # execute policy change
        resource_service.projects().setIamPolicy(resource=project_id, body={"policy": policy}).execute()

    # Generate a Service account key
    get_service_account_key(credentials, my_service_account['email'])
    return my_service_account