利用PowerShell+Jenkins,实现项目的自动化部署

假如把开发工作流程分为以下几个阶段:

编码 -> 构建 -> 集成 -> 测试 -> 交付 -> 部署

《利用PowerShell+Jenkins,实现项目的自动化部署》 开发工作流程
《利用PowerShell+Jenkins,实现项目的自动化部署》 Continuous Integration

持续集成是指软件个人研发的部分向软件整体部分交付,频繁进行集成以便更快地发现其中的错误。“持续集成”源自于极限编程(XP),是 XP 最初的 12 种实践之一。

《利用PowerShell+Jenkins,实现项目的自动化部署》 Continuous Delivery

持续交付在持续集成的基础上,将集成后的代码部署到更贴近真实运行环境的「类生产环境」(production-like environments)中。持续交付优先于整个产品生命周期的软件部署,建立在高水平自动化持续集成之上。

《利用PowerShell+Jenkins,实现项目的自动化部署》 Continuous Delivery

持续部署是指当交付的代码通过评审之后,自动部署到生产环境中。持续部署是持续交付的最高阶段。这意味着,所有通过了一系列的自动化测试的改动都将自动部署到生产环境。它也可以被称为“Continuous Release”。

「持续集成(Continuous Integration)」、「持续交付(Continuous Delivery)」和「持续部署(Continuous Deployment)」提供了一个优秀的 DevOps 环境,对于整个团队来说,好处与挑战并行。无论如何,频繁部署、快速交付以及开发测试流程自动化都将成为未来软件工程的重要组成部分。

Jenkins2.107.3版本修改启动端口号(Windows)

可能有一些原因,8080端口被占用了,无法使用时需要修改jenkins的启动端口号。
如果首次安装,建议先停止原有系统的8080端口占用,等jenkins安装完成后,再进行修改,然后该回8080的原系统端口。
先停止jenkins服务

net stop jenkins

打开"C:\Program Files (x86)\Jenkins\jenkins.xml"

修改

<!--
The MIT License

Copyright (c) 2004-2017, Sun Microsystems, Inc., Kohsuke Kawaguchi, Oleg Nenashev, and other Jenkins contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-->

<!--
  Windows service definition for Jenkins.

  To uninstall, run "jenkins.exe stop" to stop the service, then "jenkins.exe uninstall" to uninstall the service.
  Both commands don't produce any output if the execution is successful. 
-->
<service>
  <id>Jenkins</id>
  <name>Jenkins</name>
  <description>This service runs Jenkins automation server.</description>
  <env name="JENKINS_HOME" value="%BASE%"/>
  <!--
    if you'd like to run Jenkins with a specific version of Java, specify a full path to java.exe.
    The following value assumes that you have java in your PATH.
  -->
  <executable>%BASE%\jre\bin\java</executable>
  <arguments>-Xrs -Xmx256m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\jenkins.war" --httpPort=9003 --webroot="%BASE%\war"</arguments>
  <!--
    interactive flag causes the empty black Java window to be displayed.
    I'm still debugging this.
  <interactive />
  -->
  <logmode>rotate</logmode>

  <onfailure action="restart" />
  
  <!-- 
    In the case WinSW gets terminated and leaks the process, we want to abort
    these runaway JAR processes on startup to prevent corruption of JENKINS_HOME.
    So this extension is enabled by default.
  -->
  <extensions>
    <!-- This is a sample configuration for the RunawayProcessKiller extension. -->
    <extension enabled="true" 
               className="winsw.Plugins.RunawayProcessKiller.RunawayProcessKillerExtension"
               id="killOnStartup">
      <pidfile>%BASE%\jenkins.pid</pidfile>
      <stopTimeout>10000</stopTimeout>
      <stopParentFirst>false</stopParentFirst>
    </extension>
  </extensions>
  
  <!-- See the referenced examples for more options -->
  
</service>

重新启动jenkins服务

net start jenkins

安装插件

之所以要安装插件是我们以后的操作都要用到插件。没有的话,基本干不了活。
因为我们是要使用GitHub,所以需要用到Git plugin、和GitHub plugin.
我们进入:系统管理 –>管理插件 —>可选插件

  • Git client plugin
    Utility plugin for Git support in Jenkins

  • Git plugin
    This plugin integrates Git with Jenkins.

  • MSBuild Plugin
    This plugin makes it possible to build a Visual Studio project (.proj) and solution files (.sln).

配置Git

系统管理 —>Global Tool Configuration 点击git安装,注意:是git文件夹中的cmd文件夹中的git.exe。

《利用PowerShell+Jenkins,实现项目的自动化部署》 Git installations

配置GitHub

GitHub webhooks 设置

webhook是通知Jenkins时的请求地址,用来填写到GitHub上,这样GitHub就能通过该地址通知到Jenkins;
假设Jenkins所在服务器的地址是:192.168.0.1,端口为8080,那么webhook地址就是http://192.168.0.1:8080/github-webhook

再次提醒,上述地址必须是外网也能访问的,否则GitHub无法访问到Jenkins;

《利用PowerShell+Jenkins,实现项目的自动化部署》 Add webhook

生成Personal access tokens

Jenkins访问GitHub工程的时候,有的操作是需要授权的,所以我们要在GitHub上生成授权的token给Jenkins使用,这就是Personal access tokens,生成步骤如下:

《利用PowerShell+Jenkins,实现项目的自动化部署》 生成Personal access tokens

Jenkins配置GitHub访问权限

GitHub Plugin插件,在”系统管理->管理插件”位置检查此插件是否已经安装,没有的话请先安装;
配置GitHub,点击“系统管理->系统设置”,如下图:
在系统设置页面找到”GitHub”,配置一个”GitHub Server”,如下图,”API URL”填写”https://api.github.com“,”Credentials”位置如下图红框所示,选择”Add->Jenkins”:

《利用PowerShell+Jenkins,实现项目的自动化部署》 Jenkins配置

弹出的页面中,”Kind”选择”Secret text”,”Secret”填入前面在GitHub上生成的Personal access tokens,Description随便写一些描述信息,如下图:

《利用PowerShell+Jenkins,实现项目的自动化部署》 Jenkins配置

填写完毕后,点击右侧的”Test connection”按钮,如果信息没有填错,显示的内容如下图所示:
点击页面最底部的”保存”按钮;

Jenkins新建构建项目

《利用PowerShell+Jenkins,实现项目的自动化部署》 Jenkins新建构建项目01
《利用PowerShell+Jenkins,实现项目的自动化部署》 Jenkins新建构建项目02

  • 选择”Git”;
  • “Repository URL”输入仓库地址:https://github.com/ChenQianPing/Tdf.S01.git
  • “Credentials”创建一个Credentials,Kind选择”Username with password”,Username输入GitHub账号,Password输入GitHub密码;
  • “源码库浏览器”选择”githubweb”;
  • “URL”输入项目主页:https://github.com/ChenQianPing/Tdf.S01
  • “构建触发器”中勾选”GitHub hook trigger for GiTScm polling”;
  • 构建环境设置,如下图所示,勾选”Use secret text(s) or file(s)”,下面的”Credentials”选择我们之前配置过的”Personal access tokens”

PowerShell篇

环境的准备
我选择的PowerShell版本是V5.0。网上搜索一下安装包,下载后在服务器安装即可。作为安装PowerShell的先决条件,.Net Framework 4.5也是必须安装的。
Windows7默认自带的Powershell版本只有2.0,但是很多基于Powershell开发的Module是需要更高版本的,那么我们如何升级Powershell呢?https://www.microsoft.com/en-us/download/details.aspx?id=54616核心功能一样。支持windows 7 sp1

远程访问服务器,首先是利用PowerShell的New-PSSession命令,填写远程服务器的管理员账号密码登陆,获取Session
Get-Credential是个交互函数,执行时会弹出一个用户名密码对话框,因此我们要人为构造一个PSCredential。改写一下方法

$pass=ConvertTo-SecureString -String 'your password' -AsPlainText -Force
$cre=New-Object pscredential('your username', $pass)
$session=New-PSSession -ComputerName $server -Credential $cre

获取Session以后,远程服务器已经完全落入我们的掌心。现在可以通过Invoke-Command远程执行命令,可以用Enter-PSSession直接进入远程会话,可以通过Copy-Item实现文件传输。以下是我在部署过程中遇到的常用的命令。

远程停止Windows Service:

Invoke-Command -Session $session -ScriptBlock{
    Stop-Service -Name 'your service name'
}

远程停止Web

Invoke-Command -Session $session -ScriptBlock{
    import-module webadministration
    set-location IIS:\
    $site=Get-Item 'IIS:\Sites\Ems.Webv2'
    $site.Stop()
}

本地文件拷贝

Copy-Item -Path "D:\\测试用文件.txt" -Destination "D:\\tt" -Force

拷贝本地文件到远程服务器

ls "local folder" | cp -Destination "remote folder" -ToSession $session -Recurse -Force
ls "C:\tmp" | cp -Destination "D:\tt" -ToSession $session -Recurse -Force

将文件打包成zip

Compress-Archive "Folder" -DestinationPath "Zip File Name" -Force
Compress-Archive "D:\tt" -DestinationPath "D:\tt01.zip" -Force

将zip文件解压

Expand-Archive "Zip File Name" -DestinationPath "Folder" -Force
Expand-Archive "D:\tt01.zip" -DestinationPath "D:\tt01" -Force

拷贝远程服务器文件到本地

cp -FromSession $session -Path "Remote File" -Destination "Local Folder" -Recurse -Force
cp -FromSession $session -Path "D:\tt\测试用文件3.txt" -Destination "D:\tt01" -Recurse -Force

查看PowerShell版本信息

$PSVersionTable.PSVersion

释放PSSession

Remove-PSSession -Id $session.Id #使用完毕后一定记得释放PSSesion

Help

get-help Copy-Item -examples

扩展阅读

    原文作者:Bobby0322
    原文地址: https://www.jianshu.com/p/7a0dc4d8c6c3
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞