dotnet项目执行shell脚本实现简单的自动化部署
不要k8s、不要docker、不要Jenkins,只要一个部署脚本,只是一个小项目单台服务器,实现提交代码自动执行脚本,拉代码构建部署项目。
创建一个web api 项目,作为webhook,实现接收web请求后执行shell脚本
项目代码:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
namespace ShellHandler.Controllers
{
[ApiController]
[Route("[controller]")]
public class HandlerController : ControllerBase
{
private readonly ILogger<HandlerController> _logger;
public HandlerController(ILogger<HandlerController> logger)
{
_logger = logger;
}
[HttpPost]
public string Execute(string fileName)
{
try
{
var processStartInfo = new ProcessStartInfo($"./{fileName}") { RedirectStandardOutput = true };
var process = Process.Start(processStartInfo);
if (process == null)
{
Console.WriteLine("Can not run shell .");
}
else
{
using (var sr = process.StandardOutput)
{
while (!sr.EndOfStream)
{
var str = sr.ReadLine();
Console.WriteLine(str);
}
if (!process.HasExited)
{
process.Kill();
}
}
}
return "ok";
}
catch (Exception ex)
{
_logger.LogInformation(ex.Message);
return ex.Message;
}
}
}
}
在服务器部署当前项目
nohup dotnet ShellHandler.dll --urls http://0.0.0.0:8080 &
在项目根目录创建部署脚本publish.sh
#!/bin/bash#杀死占用8081端口的进程kill -9 $(lsof -i:8081 -t)cd /home/web/web-demo/#拉取代码git pull#发布项目到publish文件夹dotnet publish -o publishcd publish/#后台运行项目nohup dotnet WebDemo.dll --urls http://0.0.0.0:8081 &
添加执行权限
chmod a+x publish.sh
创建一个Demo项目部署到服务器,托管到gitee
把webhook地址添加到gitee的WebHooks,并指定脚本文件名项目
出处:https://www.tnblog.net/17801418352/article/details/6382