问题
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.
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.
回答1:
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:
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 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.
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
Here is the script:
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"
回答2:
Try the command below for Az
, my repository is public, it works fine on my side.
$gitrepo="your git repository url"
$webappname="joyazapp"
$location="centralus"
New-AzResourceGroup -Name joyazgroup -Location $location
New-AzAppServicePlan -Name joyazplan -Location $location -ResourceGroupName joyazgroup -Tier Free
New-AzWebApp -Name joyazapp -Location $location -AppServicePlan joyazplan -ResourceGroupName joyazgroup
$PropertiesObject = @{
repoUrl = "$gitrepo";
branch = "master";
isManualIntegration = $false
}
Set-AzResource -PropertyObject $PropertiesObject -ResourceGroupName joyazgroup -ResourceType Microsoft.Web/sites/sourcecontrols -ResourceName $webappname/web -ApiVersion 2018-02-01 -Force
来源:https://stackoverflow.com/questions/53813615/deploy-code-from-gitlab-repository-to-azure-web-app-using-powershell-and-azure-c