title: Can't connect to Azure Postgresql with a Python Function App
body: <p>I've followed <a href="https://stackoverflow.com/questions/62919973/obtain-access-token-for-the-connection-to-postgresql-in-azure-functions">this</a>, <a href="https://stackoverflow.com/questions/61867652/use-managed-identity-to-authenticate-azure-app-service-to-sql-database">this</a> and <a href="https://stackoverflow.com/questions/62455511/error-getting-managed-identity-access-token-from-azure-function">this</a> and a lot of other resources and still can't get connected to the database. That's why I've opened this question. I'm beyond frustrated. Hopefully someone can steer me into the right direction. Below is the steps that I've done.</p>
  <ol>
  <li>I did steps 1-3 from this <a href="https://techcommunity.microsoft.com/t5/azure-database-for-postgresql/connect-from-function-app-with-managed-identity-to-azure/ba-p/1517032" rel="nofollow noreferrer">article</a>. By the way should I use the Application ID of the azure function or the Principal ID of the System Assigned Identity when creating a role for the function in the database? I've used the Application ID.</li>
  <li>I've added all the possible outbound ip addresses of the azure function to pass the database firewall.</li>
  <li>Function is on Linux Consumption plan. According to this <a href="https://docs.microsoft.com/en-us/azure/app-service/overview-managed-identity?tabs=python#obtain-tokens-for-azure-resources" rel="nofollow noreferrer">article</a> you need to use the 2017-09-01 api version if function is on Linux Consumption plan.</li>
  </ol>
  <p>I did not find anything in the function properties/configuration on os.environ[&quot;MSI_ENDPOINT&quot;], os.environ[&quot;MSI_SECRET&quot;] so I'm assuming that these are being assigned by microsoft when the function gets executed. Here's the Exception that I'm getting when running the function:</p>
  <p>&quot;Exception while executing function: Functions.FunctionTrigger Result: Failure
  Exception: UnboundLocalError: local variable 'connection' referenced before assignment. if connection:&quot;</p>
  <p>Furthermore, I can not see any logs even though I'm writing them in the function body. Not in the function insights nor in the storage account that is defined for the function. So basically I'm flying blind. Moreover, initially I was using psycopg2 and I was receiving the exception in <a href="https://stackoverflow.com/questions/61975311/how-to-install-python-module-in-azure-function-linux-app">here</a>. Then I switched to psycopg2-binary and the exception went away. Any help would be appreciated.</p>
  <pre><code>import logging
  import os
  import azure.functions as func
  import psycopg2
  from psycopg2 import Error
  import requests
  
  def main(mytimer: func.TimerRequest) -&gt; None:
      utc_timestamp = datetime.datetime.utcnow().replace(
          tzinfo=datetime.timezone.utc).isoformat()
  
      if mytimer.past_due:
          logging.info('The timer is past due!')
  
      logging.info('Python timer trigger function ran at %s', utc_timestamp)
  
      try:
          #get access token
          # identity_endpoint = os.environ[&quot;IDENTITY_ENDPOINT&quot;]
          # identity_header = os.environ[&quot;IDENTITY_HEADER&quot;]
          # resource_uri=&quot;https://database.windows.net/&quot;
          # token_auth_uri = f&quot;{identity_endpoint}?resource={resource_uri}&amp;api-version=2019-08-01&quot;
          # head_msi = {'X-IDENTITY-HEADER':identity_header}
          # resp = requests.get(token_auth_uri, headers=head_msi)
          # access_token = resp.json()['access_token']
          msi_endpoint = os.environ[&quot;MSI_ENDPOINT&quot;]
          msi_header = os.environ[&quot;MSI_SECRET&quot;]
          # resource_uri=&quot;https://database.windows.net/&quot;
          resource_uri=&quot;https://ossrdbms-aad.database.windows.net&quot;
          token_auth_uri = f&quot;{msi_endpoint}?resource={resource_uri}&amp;api-version=2017-09-01&quot;
          head_msi = {'secret':msi_header}
          resp = requests.get(token_auth_uri, headers=head_msi)
          access_token = resp.json()['access_token']
  
          logging.info(msi_endpoint)
          logging.info(msi_header)
          logging.info(access_token)
          
          USER = 'name of the role that I created for the function'
          connection = psycopg2.connect(
              user = USER,
              password = access_token,
              host = HOST,
              database = DB,
              port = '5432'
          )
  
          cursor = connection.cursor()
  
          query = &quot;SELECT * FROM table;&quot;
          cursor.execute(query)
  
  
      except (Exception, Error) as error:
          print(error)
          logging.info(error)
  
      finally:
          if connection:
              cursor.close()
              connection.close()
              print(&quot;PostgreSQL connection is closed&quot;)
  </code></pre>