Skip to content

Instantly share code, notes, and snippets.

@salman2learn
Last active May 2, 2023 18:54
Show Gist options
  • Save salman2learn/f87db96b95d16a2cb4a81d4e426ed562 to your computer and use it in GitHub Desktop.
Save salman2learn/f87db96b95d16a2cb4a81d4e426ed562 to your computer and use it in GitHub Desktop.
Bash script to secure azure storage accounts including existing containers (secure by default, remove anonymous access, restrict to cidrs/ip). Runs from Azure CLI or cloudshell.
set -ex # fail on first exception
#az login
#az account show
subs="My-Subs-Name"
az account set --subscription "$subs"
rg=$1
# Or use a fixed value of rg
rg=my-rg-name
# space-delimited cidr and/or IPv4s
WHITELIST="1.2.3.4/24 2.3.4.5 6.7.8.9/12"
echo "Getting storage accounts for rg: $rg Or get the list from a text file"
#for acct in `cat storageaccts.txt`
for acct in `az storage account list -g $rg --query "[].{name:name}" -o tsv`
do
echo "===================================================="
echo "Storage Acct: " $acct
echo "Setting defaults. This does not changes existing containers, so we will have to iterate over them later."
az storage account update -g $rg -n $acct --allow-blob-public-access false --bypass Logging Metrics AzureServices
echo "Changing firewall"
az storage account update -g $rg --name $acct --default-action allow
echo "Sleeping for 10s (for fw changes to take effect)"
sleep 10
echo "Get storage account key"
key=`az storage account keys list -g $rg -n $acct --query "[].{v: value}" -o tsv | head -n 1`
echo "Getting all containers in storage account: $acct"
for cont in `az storage container list --account-name $acct --account-key "$key" --query "[].{nm: name}" -o tsv`
do
echo "Storage account: $acct, Container: $cont -- denying public access"
az storage container set-permission --name $cont --account-name $acct --account-key "$key" --public-access off -o table
done
echo "Acct::set deny network"
az storage account update -g $rg --name $acct --default-action deny -o table
for cidr in $WHITELIST
do
echo "Allowing cidr: " $cidr " on acct: " $acct
az storage account network-rule add -g $rg --account-name $acct --ip-address $cidr --query "{nm: name}" -o tsv
done
break # break on first iteration # enable for trying out
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment