Created
September 3, 2018 14:22
-
-
Save abdulapopoola/75170fdd5243831b187cb599ad9a3f8e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Backup script for BASH relying on Az CLI | |
containerName=azureBlobStorageContainerName | |
storageAccountName=storageAccountName | |
subscription=subscriptionId | |
resourceGroup=resourceGroupName | |
file="${1,,}" | |
now=$(date +"%F.%T"); | |
backupFileName="BACKUP ON $now" | |
parse_json () | |
{ | |
echo $1 | \ | |
sed -e 's/[{}]/''/g' | \ | |
sed -e 's/", "/'\",\"'/g' | \ | |
sed -e 's/" ,"/'\",\"'/g' | \ | |
sed -e 's/" , "/'\",\"'/g' | \ | |
sed -e 's/","/'\"---SEPERATOR---\"'/g' | \ | |
awk -F=':' -v RS='---SEPERATOR---' "\$1~/\"$2\"/ {print}" | \ | |
sed -e "s/\"$2\"://" | \ | |
tr -d "\n\t" | \ | |
sed -e 's/\\"/"/g' | \ | |
sed -e 's/\\\\/\\/g' | \ | |
sed -e 's/^[ \t]*//g' | \ | |
sed -e 's/^"//' -e 's/"$//' | |
} | |
# Get token | |
echo "Retrieving token from AAD" | |
payload="$(curl http://localhost:50342/oauth2/token --data "resource=https://management.azure.com/" -H Metadata:true;)" | |
# Parse Token | |
echo "Parsing access_token from AAD response" | |
token="$(parse_json $payload access_token)" | |
echo "Setting 5 minute token expiry time" | |
tokenExpiryTime=$(date -ud "now + 5 minutes" +%FT%T.%3NZ) | |
echo $tokenExpiryTime | |
# Get SAS Token | |
echo "Exchanging AAD token for SAS token" | |
sasTokenPayload=$(curl https://management.azure.com/subscriptions/$subscription/resourceGroups/$resourceGroup/providers/Microsoft.Storage/storageAccounts/$storageAccountName/listServiceSas/?api-version=2017-06-01 -X POST -d "{\"canonicalizedResource\":\"/blob/$storageAccountName/$containerName\",\"signedResource\":\"c\",\"signedPermission\":\"rcw\",\"signedProtocol\":\"https\",\"signedExpiry\":\"$tokenExpiryTime\"}" -H "Authorization: Bearer $token") | |
# Parse SAS Token | |
echo "Parsing SAS Token" | |
sasToken="$(parse_json $sasTokenPayload serviceSasToken)" | |
# Upload Blob | |
echo "Uploading the file..." | |
az storage blob upload --container-name $containerName --file $file --name $backupFileName --account-name $storageAccountName --sas-token $sasToken | |
echo "Done" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment