googleads / googleads-python-lib

The Python client library for Google's Ads APIs

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Method to authenticate via environment variables

j0nes2k opened this issue · comments

The basic setup of getting access to the Admanager API involves using a googleads.yml file including a path to a private key file. For security reasons, I do not want to store the private key file on my disk, but instead get the contents from the key file from environment. I have already achieved this basic setup and now I want to access the Admanager API using the contents of the key file.

Is there a way to authenticate against the Admanager API in the way mentioned above? Or do I have to write this to a temporary file on disk and delete it afterwards?

Note that I am aware on how to insert the YAML file contents via LoadFromString, but I am looking for a way to insert the private key contents in the same way.

Pseudocode of what I would expect is:

        service_account_pk = os.environ["MY_PRIVATE_KEY_CONTENTS"]
        credentials = json.loads(service_account_pk)
        client = ad_manager.AdManagerClient.LoadFromDict(credentials)

Yes this is possible. The googleads.oauth2 module is largely a wrapper around the general google.oauth2 modules.

You can create any Credentials object and use it to create an Ad Manager client:
https://github.com/googleads/googleads-python-lib/blob/main/googleads/oauth2.py#L215

The google.oauth2.service_account module has a method for constructing a Credential from a dict.

In pseudocode:

service_account_info = json.loads(service_account_pk)
credentials = service_account.Credentials.from_service_account_info(
    service_account_info)
oauth2_client = oauth2.GoogleCredentialsClient(credentials)
ad_manager_client = ad_manager.AdManagerClient(oauth2_client, application_name)