之前發布了 《.Net Core DevOps -免費用Azure四步實現自動化發布(CI/CD)》之后,有很多朋友私信我說如何替換 appsettings 里面的
ConnectionStrings
的問題。我的解決方案是通過Shell在編譯前替換需要替換的字符串。以下是具體步驟:
1.項目添加 appsettings.Production.json
添加占位符例如{Writable},用於Shell腳本替換用
2. 打開解決方案的 azure-pipelines.yml
添加一個新的Task
注:```ls``` 列出目錄(主要是看azure 的 devops 的目錄結構,可以不寫)
#sed 將文件內所有的 {Writable} 替換成Azure的 $(Writable)
sed -i 's/{Writable}/$(Writable)/g' WebNotebook/appsettings.Production.json
3.將yml的$(Writable)
配置到Azure的 Variables
里面
4.提交代碼,查看是否替換成功
檢查Job執行情況
進入docker查看appsettings,替換成功
root@iZs9kgd0x5xmhaZ:~# docker exec -it 715afabf4ac7 bash
root@715afabf4ac7:/app# ls
WebNotebook.Views.dll WebNotebook.dll WebNotebook.runtimeconfig.json appsettings.json
WebNotebook.Views.pdb WebNotebook.pdb appsettings.Development.json web.config
WebNotebook.deps.json WebNotebook.runtimeconfig.dev.json appsettings.Production.json wwwroot
root@715afabf4ac7:/app# cat appsettings.Production.json
{
"ConnectionStrings": {
"Writable": "Server=127.0.0.1;Database=Demo;Integrated Security=true;",
"ReadOnly": "Server=127.0.0.1;Database=Demo;Integrated Security=true;"
},
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
root@715afabf4ac7:/app#