Created
February 4, 2020 20:25
-
-
Save syedhassaanahmed/dd4fdd3171ee5f8f8a5dfd53ea50633c 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
stages: | |
- stage: cleanupAcr | |
displayName: Cleanup ACR Images for PR | |
pool: | |
vmImage: ubuntu-latest | |
jobs: | |
- job: cleanupAcr | |
variables: | |
prMergeMessage: 'Merged PR ' | |
serviceConnection: myAzureServiceConnection | |
containerRegistry: myacr | |
imageRepository: testservice | |
steps: | |
- task: AzureCLI@1 | |
# Build.SourceVersionMessage is only available on step level and not on job or stage level. | |
# The message is not extracted until the job has started and checked out the code | |
condition: and(succeeded(), startsWith(variables['Build.SourceVersionMessage'], variables.prMergeMessage)) | |
inputs: | |
azureSubscription: $(serviceConnection) | |
scriptLocation: inlineScript | |
inlineScript: | | |
# Parse PR ID from merge commit message e.g. 'Merged PR 66' | |
PR_ID=$(echo "$(Build.SourceVersionMessage)" | grep -Eo "$(prMergeMessage)[0-9]+" | awk '{print $3}') | |
if [ -z "$PR_ID" ]; then | |
echo "Couldn't parse PR ID from commit message: '$(Build.SourceVersionMessage)'" | |
else | |
PR_URL="$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/git/pullrequests/$PR_ID?api-version=5.1" | |
PR_RESPONSE=$(curl -s -H "Authorization:Bearer $(System.AccessToken)" $PR_URL) | |
# Parse PR branch name, e.g. 'feature/my-pr-branch' should be parsed as 'my-pr-branch' | |
PR_BRANCH=$(basename $(echo $PR_RESPONSE | jq -r ".sourceRefName")) | |
MERGE_STATUS=$(echo $PR_RESPONSE | jq -r ".mergeStatus") | |
if [ "$MERGE_STATUS" == "succeeded" ]; then | |
# Container image tags are assumed to be in format <REPOSITORY>:<BUILD_ID>-<PR_BRANCH_NAME> | |
# If your format is different, please modify the regex below in acr purge filter | |
az acr run --registry $(containerRegistry) --timeout 3600 --cmd "acr purge --filter '$(imageRepository):.*-$PR_BRANCH' --ago 1m" /dev/null | |
else | |
echo "PR is not merged, status: '$MERGE_STATUS'" | |
fi | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment