本文介绍在不同的Azure Container Registry同步Image。
原理:
用户push image 到source ACR;
source ACR 通过 webhook向外发布通知(通知中包含用户上传的image名称,tag等);
target 中构建functions接受通知(解析得到 image host,image name,image tag等);
functions 中使用powershell脚本执行 Import-AzContainerRegistryImage 命令从source 导入到target ACR中;
functions至少同时可以连接 source ACR和target ACR,对于source ACR,本例子使用用户名和密码连接,对于 target ACR使用service principal;
Azure Functions(PowerShell)示例代码:
using namespace System.Net
# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)
# Write to the Azure Functions log stream.
Write-Host "PowerShell HTTP trigger function processed a request."
$SourceRepository =$request.Body.target.repository
$SourceTag=$request.Body.target.tag
$SourceHost=$request.Body.request.host
$SourceImage=$SourceRepository+":"+$SourceTag
$SourceAcrAdminuser="sourceacrsean";
$SourceAcrPassword="3olIJxxx";
$TargetRegistryName="targetacrsean"
$TargetResourceGroupName="targetresourcegroupname"
$ServicePrincipalAppId="xxx"
$TenantId="cxxx"
$ServicePrincipalSecret="xxx"
$TargetSubscriptionId="xxx"
#Write-Output ‘Azure Function PowerShell Module’
#$modules = Get-Module -ListAvailable | Select-Object Name, Version | Sort-Object -Property Name | Out-String
#Write-output `n$modules
$SecureStringPwd = $ServicePrincipalSecret | ConvertTo-SecureString -AsPlainText -Force
$pscredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $ServicePrincipalAppId, $SecureStringPwd
Connect-AzAccount -ServicePrincipal -Credential $pscredential -Tenant $tenantId
Set-AzContext -SubscriptionId $TargetSubscriptionId
Import-AzContainerRegistryImage -RegistryName $TargetRegistryName -ResourceGroupName $TargetResourceGroupName -SourceRegistryUri $SourceHost -SourceImage $SourceImage -Username $SourceAcrAdminuser -Password $SourceAcrPassword
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
StatusCode = [HttpStatusCode]::OK
})
在代码中使用了Connect-AzAccount 等Powershell AZ module, 因此我们必须在Functions中启用 AZ module,操作如下:
在requirements.psd1中,取消 AZ的注释:
操作演示: