延续先前使用gitlab的CI流程,这次加入PowerShell完成后续CD的流程,笔记一下这次的内容
神父
这次为yml档加上deploy的stage,很单纯的只呼叫ps1做事,
专案有两个ps1,皆放在资料夹Ps1中
-
stages:
-
- deploy
-
-
before_script:
-
- chcp 65001
-
-
deploy:
-
stage: deploy
-
script:
-
- dotnet publish ./MyProject/ -c release -o ./output
-
- ./Ps1/PreDeploy.ps1 $env:DeployAccount_Stage $env:DeployPassword_Stage
dotnet发布./MyProject/ -c版本-o ./output
指定release组态发布,并且指定发布的位置在“./output”
$ env:DeployAccount_Stage
PowerShell取得环境变数的方式,相关值会存在gitlab的“Settings > Variables”
./Ps1/PreDeploy.ps1 $ env:DeployAccount_Stage $ env:DeployPassword_Stage
执行PreDeploy.ps1,并且传入两个值
PreDeploy.ps1(GitLab Runner)
-
$account = $args[0]
-
$password = $args[1]
-
<# 取的傳入的參數值 #>
-
$serverName = "192.168.1.1"
-
<# 要部署的server位置 #>
-
-
$projectName = "MyProject"
-
$version = Get-Date -Format "yyyyMMddHHmmss"
-
$location = $(PWD)
-
<# 取得當下的絕對路徑,Get-Location的別名 #>
-
$publishPath = "$location\output"
-
-
$deployPsPath = "$location\Ps1\Deploy.ps1"
-
$remoteDeployPath = "C:\Deploy\"
-
-
<# 將publish的結果壓縮為.zip #>
-
echo "Compress files"
-
$zipDir = "$location\$projectName\"
-
if ((Test-Path $zipDir -PathType Any) -eq 0)
-
{
-
new-item $zipDir -itemtype directory
-
}
-
-
$zipFilePath = "$zipDir$version.zip";
-
$compress = @{
-
Path = $publishPath
-
CompressionLevel = "Fastest"
-
DestinationPath = $zipFilePath
-
}
-
Compress-Archive @compress -Update
-
if(!$?) { throw $LASTEXITCODE }
-
echo "Compress files $zipFilePath"
-
-
-
-
<# 遠端連線到目標主機 *註1 #>
-
echo "Get Session"
-
$pw = convertto-securestring -AsPlainText -Force -String $password
-
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $account, $pw
-
$session = New-PSSession -ComputerName $serverName -Credential $cred
-
if(!$?) { throw $LASTEXITCODE }
-
echo "Get Session done"
-
<# 遠端連線失敗則中斷script,並且返回錯誤訊息 #>
-
-
-
-
<# 將zip檔複製到遠端主機上 #>
-
echo "copy zip file"
-
$targetDir = "C:\Deploy\Zip\"
-
if ((Test-Path $targetDir -PathType Any) -eq 0)
-
{
-
Invoke-Command -Session $session -Command { New-Item $args[0] -ItemType directory -force } -Args $targetDir
-
}
-
$publishZipFile = "$targetDir$version.zip"
-
Copy-Item -path $zipFilePath -Destination $targetDir -ToSession $session
-
if(!$?) { throw $LASTEXITCODE }
-
echo "copy zip file $publishZipFile"
-
<# 複製失敗則中斷 #>
-
-
-
-
<# 將 deploy.ps1 複製到遠端主機,遠端主機的部署流程會放在這 #>
-
Copy-Item -path $deployPsPath -Destination $remoteDeployPath -ToSession $session
-
if(!$?) { throw $LASTEXITCODE }
-
<# 複製失敗則中斷 #>
-
-
-
-
<# 呼叫遠端主機執行 Deploy.ps1 #>
-
Invoke-Command -Session $session -scriptblock {
-
C:\deploy\Deploy.ps1 $args[0] $args[1]
-
} -ArgumentList $publishZipFile, $version
-
-
-
<# 關閉遠端連線 #>
-
$session | Remove-PSSession
Deploy.ps1(目标服务器)
*注1
远端前需要开启相关功能及设定,由gitlab执行时需要为服务"gitlab-runner"指定登入身份,否则可能会遇到无法远端连线的讯息。
阅读(2247) | 评论(0) | 转发(1) |