问题描述
我想使用PowerShell脚本和Azure CLI设置从GitLab存储库到Azure应用的连续部署.使用 Azure RM模块和Windows PowerShell 已经可以解决此问题,但是因为它们是现已弃用,我正在寻找一种专门的解决方案使用新的 Az模块和 PowerShelll核心.
I would like to setup continuous deployment from a GitLab repository to an Azure App using a PowerShell script and the Azure CLI. There is already an answer for doing this using the Azure RM module and Windows PowerShell, but as these are now deprecated, I am looking specifically for a solution that uses the new Az module and PowerShelll Core.
该解决方案应提供一个PowerShell(核心)脚本,以直接从GitLab到Azure设置持续部署.它必须使用 Az模块.运行安装脚本后,随后对GitLab存储库的每个后续提交/合并都应自动部署到Azure.最好,此PowerShell脚本应同时适用于托管在GitLab上的公共和私有存储库,但是我愿意接受仅适用于公共存储库的解决方案.
The solution should give a a PowerShell (Core) script to setup a Continuous Deployment directly from GitLab to Azure. It must make use of the Az module. Once the setup script is run, each subsequent commit/merge to the GitLab repository should then automatically be deployed to Azure. Preferably, this PowerShell script should work for both public and private repositories that are hosted on GitLab, but I'm willing to accept solutions that only work on public repositories.
推荐答案
我在玩gitlab和kudu rest API,并弄清楚了如何自动手动解决方案.唯一的额外步骤是将gitlab api令牌添加到您的代码中,但是您只需对所有项目执行一次即可.您可以从gitlab帐户设置的访问令牌"下获取该证书.其他一些注意事项:
I was playing around with gitlab and kudu rest APIs, and figured out how to automate manual solution you mentioned. The only extra step is to add gitlab api token to your code, but you just do it once for all projects. You can get it from your gitlab account settings under "Access Tokens". Some other notes:
要与kudu api进行交互,脚本将使用自动生成的 部署凭证.但是您可以为创建一个单独的用户 部署并在所有其他项目中使用它(跳过该步骤).你 可以在天蓝色的CLI中做到这一点:
To interact with kudu api the script is using autogenerated deployment credentials. But you can create a separate user for deployment and use it in all other projects (skipping that step). You can do it in azure CLI:
az webapp deployment user set --user-name someUser --password somepassword
GitLab API使用的是项目ID,而不是项目名称.该脚本是 试图从回购URL自动检索项目ID,但是您 可以将其从gitlab的项目常规设置中复制/粘贴为 安全.
GitLab API is using project ID, not the project name. The script is trying to retrieve project id automatically from repo URL, but you might copy/paste it from the project general setting on gitlab to be safe.
此解决方案也适用于私有存储库.您会看到的唯一一件事 创建资源时出现一些错误(因为未设置ssh密钥) 然而).但是脚本完成后应该没问题,因此请忽略 错误.对于公共存储库,您可以完全跳过该密钥设置内容.
This solution works with private repos too. The only thing you'll see some error while creating a resource (because ssh key is not set up yet). But after script is completed it should be fine, so ignore the error. For public repos you can skip that key set up stuff at all
这是脚本:
function log {param($memo); Write-Host "[$((get-date).ToString("HH:mm:ss"))]: $memo" -ForegroundColor Green}
# =============== App and GitLab settings ==============
$webapp="geekscodeStackOverflow"
$resgroup = $webapp + "Group"
$plan = $webapp + "Plan"
$location="centralus"
$gitToken = "yourGitLabTokenHere"
$repoUrl = "https://gitlab.com/MagicAndi/geekscode.net"
# $projID = "99..."
# ============== DEPLOYMENT SCRIPT ==========================#
log "Setting up the app on azure"
New-AzResourceGroup -Name $resgroup -Location $location
New-AzAppServicePlan -Name $plan -Location $location -ResourceGroupName $resgroup -Tier Free
New-AzWebApp -Name $webapp -Location $location -AppServicePlan $plan -ResourceGroupName $resgroup
$appInfo = Get-AzWebApp -Name $webapp
$appRef = @{Name=$appInfo.Name; ResourceGroupName = $appInfo.ResourceGroup}
if(!$appInfo){Write-Host "app deployment failed" -ForegroundColor Red; return} else {Write-Host "App created:" -ForegroundColor Green}
# ================= linking web app to gitlab =========================
# you can do this manually: app dashboard / Deployment Centrer / External / App Service Kudu / git
log "setting up deployment "
$deployment = @{
PropertyObject = @{ repoUrl = $repoUrl; branch = "master"; isMercurial= $false; isManualIntegration = $true }
ResourceGroupName = $appInfo.ResourceGroup
ResourceType = "Microsoft.Web/sites/sourcecontrols"
ResourceName = $appInfo.Name + "/web"
ApiVersion = "2018-02-01"
}
# you'll get error on this step for private repos because the key is not set up yet. You can ignore that error
Set-AzResource @deployment -Force
log "Extracting Deployment credentials"
# you can also create a user credentials in AZ CLI and skip this or manually get it in App's deployment center
$prof = Get-AzWebAppPublishingProfile @appRef | Select-Xml -XPath "//*[@publishMethod='MSDeploy']"
$deployCreds = $prof.node.userName + ":" + $prof.node.userPWD
log "Extracting Deployment key"
# Can skip for public repors
$keyUrl = "https://$webapp.scm.azurewebsites.net/api/sshkey?ensurePublicKey=1"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes($deployCreds))
$head = @{Authorization=("Basic {0}" -f $base64AuthInfo)}
$deployKey = Invoke-RestMethod -Uri $keyUrl -Headers $head -Method Get
#============== Setting Up GIT LAB ================ #
$gitApi = "https://gitlab.com/api/v4"
$gitHead = @{'PRIVATE-TOKEN'= $gitToken; 'Content-Type'='application/json'}
# looking up project id by user/repo name. You can skip that and get the id from project general setting on GitLab
$repo = $repoUrl.Split("/")[-2,-1] -join "%2F"
$project = Invoke-RestMethod -Uri "$gitApi/projects/$repo" -Headers $head
$projID = $project.id
log "Setting up $repoUrl (project id $projID)"
# --- Adding deploy key to GitLab project (public repos can skip) ---
# You can copy the key manually - Go to Project / Settings / Repository / Deploy Keys
log "Adding deploy keys to GitLab project"
$keyBody = @{title="Azure_Key";key=$deployKey; can_push=$true} | ConvertTo-Json
Invoke-RestMethod "$gitApi/projects/$projID/deploy_keys/" -Headers $gitHead -Body $keyBody -Method Post
log "Setting up a webhook"
# this can be set manualy - go to Project / Settings / Integrations.
$whBody = @{url = "https://$deployCreds@$webapp.scm.azurewebsites.net/deploy"} | ConvertTo-Json
Invoke-RestMethod -Uri "$gitApi/projects/$projID/hooks/" -Headers $gitHead -Body $whBody -Method Post
log "deployment completed `ncheck out your app at https://$webapp.azurewebsites.net"
这篇关于使用PowerShell和Azure CLI将代码从GitLab存储库部署到Azure Web App的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!