Skip to content

Instantly share code, notes, and snippets.

@claflico
Created February 12, 2020 21:47
Show Gist options
  • Save claflico/295d522e164498594324f0a660abcc9b to your computer and use it in GitHub Desktop.
Save claflico/295d522e164498594324f0a660abcc9b to your computer and use it in GitHub Desktop.
Artifactory Cleanup
#BELOW IS USED TO SET EXPIRATION DATE OF IMAGE DURING DEPLOYMENT
# Check if image has been deployed to production before
ARTIFACT_PROD_TEST=$(curl -sS -X POST -u$API_USER:$API_KEY ${API_URL}/search/aql -H "Content-Type: text/plain" -d 'items.find({ "@production": {"$eq" : "true"}, "path": {"$eq" : "'${PROJECT_NAME}-${ROLE_NAME}/${TAG_NAME}'"}, "name": {"$eq" : "'manifest.json'"}}).include("name","repo","path")' | grep path | wc -l)
if [ "$ARTIFACT_PROD_TEST" -eq 0 ] || [[ "x${DEPLOY_OVERRIDE}" == "xtrue" ]]; then
# Push the docker image
docker push $PROJECT_NAME-$REPO_HOST/$PROJECT_NAME-$ROLE_NAME:$TAG_NAME
if [[ "x${TIER}" == "xprd" ]]; then
ARTIFACT_PROPERTIES="production=true;"
EXPIRE_DAYS=546
elif [[ "x${TAG_NAME}" != "xlatest" ]]; then
EXPIRE_DAYS=14
fi
if [ ${EXPIRE_DAYS} -ne 0 ]; then
EXPIRE_DATE=$(date +%Y%m%d -d "+ $EXPIRE_DAYS days")
echo "Setting Artifactory expiration at: ${EXPIRE_DATE}"
curl -sS -X PUT -u$API_USER:$API_KEY "${API_URL}/storage/${PROJECT_NAME}-docker/${PROJECT_NAME}-${ROLE_NAME}/${TAG_NAME}?properties=${ARTIFACT_PROPERTIES}expire=${EXPIRE_DATE}"
fi
else
echo "NOTICE: Image previously deployed to production. Not overwriting Artifactory image..."
fi
#BELOW IS USED TO DELETE THE ARTIFACTS THAT EXPIRE TODAY
API_PASS=$ARTIFACTORY_PASSWORD
ARTIFACTORY_URL=${ARTIFACTORY_URL:-"https://artifactory.<SANITIZED>/artifactory"}
API_USER=$ARTIFACTORY_USERNAME
function delete_artifacts() {
results=$(jq -r '.results[] | "\(.repo)\/\(.path)\/\(.name)"' results.json)
for key in ${results}; do
echo $ARTIFACTORY_URL/$key
#Delete the artifact
curl -Ss -u$API_USER:$API_PASS -X DELETE $ARTIFACTORY_URL/$key
sleep 1
done
rm -rf results.json
}
IFS=$'\n'
#Get the artifacts with expire date of today
EXP_DATE=$(date +%Y%m%d)
#echo $EXP_DATE
curl -Ss -u${API_USER}:${API_PASS} -X POST ${ARTIFACTORY_URL}/api/search/aql -H "Content-Type: text/plain" -d "items.find({ \"@expire\": {\"\$match\" : \"${EXP_DATE}\"}}).include(\"name\",\"repo\",\"path\")" > results.json
delete_artifacts
unset IFS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment