-
-
Save dmitriysafronov/992930da4b66803a7eda9de70b82a6e2 to your computer and use it in GitHub Desktop.
A simple command to finally update the docker secret !
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
#!/usr/bin/env bash | |
# HOW TO USE | |
# based on https://gist.github.com/MLescaudron/e8248d32d3a5b8caaf622c1a829cf067 | |
# ./updateSecret.sh secretName newFile | |
# It's that simple ! | |
if [ "$#" -ne 2 ]; | |
then | |
echo "#####" | |
echo "You must supplied secretName newFile" | |
echo "ex : ./updateSecret.sh mongo_url \"newsecret.txt" | |
echo "#####" | |
exit | |
fi | |
secretName=$1 | |
newFile=$2 | |
dateNow=$(date +%s%N) | |
sourceSecretName="$secretName"_"$dateNow" | |
# Check which service is using the secret name | |
function whoUseMySecret { | |
local names="" | |
# Loop into each service to catch IDS using that secret | |
for name in $(docker service ls -q --format "{{.Name}}") | |
do | |
usingMySecret=$(docker service inspect $name | grep "\"$secretName\"" -c) | |
if [ $usingMySecret -gt 0 ]; then | |
names="$names:$name" | |
fi | |
done | |
echo ${names#":"} | |
} | |
function getAllSecretsBeginWith { | |
local names="" | |
# Get all secrets name begin with the secret name | |
# Useful to remove the oldests | |
for name in $(docker secret ls -qf name="$secretName" --format "{{.Name}}") | |
do | |
names="$names:$name" | |
done | |
echo ${names#":"} | |
} | |
function updateSecret { | |
local svNames=$1 | |
local scNames=$2 | |
# Transform into array | |
svNames=(${svNames//:/ }) | |
scNames=(${scNames//:/ }) | |
# string to delete multiple secrets on a service | |
deleteSecretsString="" | |
for name in "${scNames[@]}" | |
do | |
deleteSecretsString="$deleteSecretsString --secret-rm $name" | |
done | |
# Update all services, remove the old secret, and then set the new, with the same target | |
for name in "${svNames[@]}" | |
do | |
docker service update \ | |
$deleteSecretsString \ | |
--secret-add src="$sourceSecretName",target=$secretName \ | |
$name --detach=false | |
done | |
# Remove the oldests secrets | |
for name in "${scNames[@]}" | |
do | |
docker secret rm $name | |
done | |
} | |
function main { | |
serviceNames=$(whoUseMySecret) | |
echo "serviceNames = $serviceNames" | |
secretsName=$(getAllSecretsBeginWith) | |
docker secret create $sourceSecretName $newFile | |
updateSecret $serviceNames $secretsName | |
} | |
main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment