Skip to content

Instantly share code, notes, and snippets.

@dvu4
Created November 28, 2022 21:41
Show Gist options
  • Save dvu4/d3af8af295b944af9ee6d436296f7a9e to your computer and use it in GitHub Desktop.
Save dvu4/d3af8af295b944af9ee6d436296f7a9e to your computer and use it in GitHub Desktop.
this script will connect to a storage table via string connection and insert an entity into that table
import typer
from azure.identity import DefaultAzureCredential
from azure.mgmt.storage import StorageManagementClient
from azure.data.tables import TableServiceClient
from azure.core.exceptions import HttpResponseError
TABLE_NAME = "my_table"
SUBSCRIPTION_ID = "subscription_id"
RESOURCE_GROUP = "resource_group"
STORAGE_ACCOUNT_NAME = "storage_account_name"
def main():
entity = {
'PartitionKey': "prodfix",
'RowKey': "p-prodfix-ds-tmleng-svcp",
'keyvault_name': "prodfixdstmlengeus2kv01",
"key_id": "108080",
"creation_date": "2022-01-14 15:51:38.368",
"expiry_date": "2023-01-15T20:56:24Z"
}
credential = DefaultAzureCredential(additionally_allowed_tenants=['*'])
storage_client = StorageManagementClient(credential, SUBSCRIPTION_ID)
# get Primary key for storage account
keys = storage_client.storage_accounts.list_keys(RESOURCE_GROUP, STORAGE_ACCOUNT_NAME)
print(f"Primary key for storage account: {keys.keys[0].value}")
# get Connection string
connection_string = f"DefaultEndpointsProtocol=https;EndpointSuffix=core.windows.net;AccountName={STORAGE_ACCOUNT_NAME};AccountKey={keys.keys[0].value}"
print(f"Connection string: {connection_string}")
table_service_client = TableServiceClient.from_connection_string(conn_str=connection_string)
table = table_service_client.get_table_client(table_name=TABLE_NAME)
try:
table.create_entity(entity=entity)
except HttpResponseError:
print("Entity already exists")
if __name__ == '__main__':
typer.run(main)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment