Skip to content

Instantly share code, notes, and snippets.

@chrisns
Forked from 6be709c0/updateSecret.sh
Last active January 14, 2020 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chrisns/3b10035acac131904bc1d28a80fb02df to your computer and use it in GitHub Desktop.
Save chrisns/3b10035acac131904bc1d28a80fb02df to your computer and use it in GitHub Desktop.
A simple command to finally update the docker secret !
#!/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
@chrisns
Copy link
Author

chrisns commented Sep 28, 2017

this version uses a file rather than a value

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment