Skip to content

Instantly share code, notes, and snippets.

@Wind010
Forked from igoravl/azure-pipelines.yml
Created May 13, 2023 00:23
Show Gist options
  • Save Wind010/324a6ffca7836e5d51f4dd7c14d64db6 to your computer and use it in GitHub Desktop.
Save Wind010/324a6ffca7836e5d51f4dd7c14d64db6 to your computer and use it in GitHub Desktop.
Whitelist build agent on demand when pushing to ACR with firewall enabled
trigger:
- master
resources:
- repo: self
variables:
azureSubscription: '<azure-subscription>'
dockerRegistryServiceConnection: '<service-connection>'
imageRepository: '<repository-name>'
containerRegistry: '<registry>.azurecr.io'
dockerfilePath: '$(Build.SourcesDirectory)/Dockerfile'
tag: '$(Build.BuildId)'
vmImageName: 'ubuntu-latest'
stages:
- stage: Build
displayName: Build and push stage
jobs:
- job: Build
displayName: Build
pool:
vmImage: $(vmImageName)
steps:
- task: AzureCLI@2
name:
displayName: 'Add agent IP to firewall whitelist'
inputs:
azureSubscription: $(azureSubscription)
scriptType: 'bash'
scriptLocation: 'inlineScript'
inlineScript: |
AGENT_IP="$(dig +short myip.opendns.com @resolver1.opendns.com)"
if [ -z "$(az acr network-rule list --name $(containerRegistry) | grep ${AGENT_IP})"]
then
echo "Adding agent IP '${AGENT_IP}' to Azure Container Registry '$(containerRegistry)' firewall whitelist"
az acr network-rule add --name $(containerRegistry) --ip-address $AGENT_IP
else
echo "Agent is already whitelisted; skipping."
fi
- task: Docker@2
displayName: Build and push an image to container registry
inputs:
command: buildAndPush
repository: $(imageRepository)
dockerfile: $(dockerfilePath)
containerRegistry: $(dockerRegistryServiceConnection)
tags: |
$(tag)
- task: AzureCLI@2
displayName: 'Remove agent IP from firewall whitelist'
condition: always()
inputs:
azureSubscription: $(azureSubscription)
scriptType: 'bash'
scriptLocation: 'inlineScript'
inlineScript: |
AGENT_IP="$(dig +short myip.opendns.com @resolver1.opendns.com)"
echo "Removing agent IP '${AGENT_IP}' from Azure Container Registry '$(containerRegistry)' firewall whitelist"
az acr network-rule remove --name $(containerRegistry) --ip-address $AGENT_IP --only-show-errors --output none
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment