index.html 35.0 KB
Newer Older
LinuxSuRen's avatar
LinuxSuRen 已提交
1 2 3 4 5
<!DOCTYPE html>
<html class="no-js" lang="zh-CN">
  <head>
    <meta charset="utf-8">
    
LinuxSuRen's avatar
LinuxSuRen 已提交
6 7 8
    <link rel="preload" href="https://jenkins-zh.cn/files/muli-latin-200.woff2" as="font" type="font/woff2" crossorigin>
    <link rel="preload" href="https://jenkins-zh.cn/files/muli-latin-400.woff2" as="font" type="font/woff2" crossorigin>
    <link rel="preload" href="https://jenkins-zh.cn/files/muli-latin-800.woff2" as="font" type="font/woff2" crossorigin>
LinuxSuRen's avatar
LinuxSuRen 已提交
9 10 11 12 13 14

    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
     
    <title>使用 Jenkins &#43; Ansible 实现自动化部署 Nginx | Jenkins 中文社区</title>
    <meta name="HandheldFriendly" content="True">
    <meta name="MobileOptimized" content="320">
LinuxSuRen's avatar
LinuxSuRen 已提交
15 16
    <meta name="description" content="共建开放、包容、活跃的 Jenkins 社区">
    <meta name="keywords" content="Jenkins,Jenkins中文社区,Jenkins官方公众号,持续集成,持续交付,开源社区,DevOps">
LinuxSuRen's avatar
LinuxSuRen 已提交
17 18

    <meta name="viewport" content="width=device-width,minimum-scale=1">
LinuxSuRen's avatar
LinuxSuRen 已提交
19
     <meta name="generator" content="Hugo 0.54.0" />
LinuxSuRen's avatar
LinuxSuRen 已提交
20 21

      
LinuxSuRen's avatar
LinuxSuRen 已提交
22
        <META NAME="ROBOTS" CONTENT="INDEX, FOLLOW">
LinuxSuRen's avatar
LinuxSuRen 已提交
23 24 25 26 27 28 29 30 31 32 33 34
      

    <link href='/dist/main.css' rel='stylesheet' type="text/css" /><script src="/js/chart.js"></script>
<style>
  img.avatar {
    width: 32px;
    display: inline;
  }
</style>
<meta property="og:title" content="使用 Jenkins &#43; Ansible 实现自动化部署 Nginx" />
<meta property="og:description" content="使用 Jenkins &#43; Ansible 实现自动化部署 Nginx" />
<meta property="og:type" content="article" />
LinuxSuRen's avatar
LinuxSuRen 已提交
35
<meta property="og:url" content="https://jenkins-zh.cn/wechat/articles/2019/04/2019-04-25-jenkins-ansible-nginx/" />
LinuxSuRen's avatar
LinuxSuRen 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
<meta property="article:published_time" content="2019-04-25T00:00:00&#43;00:00"/>
<meta property="article:modified_time" content="2019-04-25T00:00:00&#43;00:00"/>

<meta itemprop="name" content="使用 Jenkins &#43; Ansible 实现自动化部署 Nginx">
<meta itemprop="description" content="使用 Jenkins &#43; Ansible 实现自动化部署 Nginx">


<meta itemprop="datePublished" content="2019-04-25T00:00:00&#43;00:00" />
<meta itemprop="dateModified" content="2019-04-25T00:00:00&#43;00:00" />
<meta itemprop="wordCount" content="451">



<meta itemprop="keywords" content="jenkins,ansible,nginx," />
<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="使用 Jenkins &#43; Ansible 实现自动化部署 Nginx"/>
<meta name="twitter:description" content="使用 Jenkins &#43; Ansible 实现自动化部署 Nginx"/>

LinuxSuRen's avatar
LinuxSuRen 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
        
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-4216293-5"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-4216293-5');



var trackOutboundLink = function(id, url) {
  console.log("track:", id, url)
  gtag('event', 'click', {
    'event_category': 'outbound',
    'event_label': id,
    'transport_type': 'beacon',
    'event_callback': function(){document.location = url;}
  });
}

</script>

      
LinuxSuRen's avatar
LinuxSuRen 已提交
78 79 80 81 82 83 84 85 86
      <script>
        var _hmt = _hmt || [];
        (function() {
          var hm = document.createElement("script");
          hm.src = "https://hm.baidu.com/hm.js?6db234f713318730f0e5f6a95bdd8d47";
          var s = document.getElementsByTagName("script")[0]; 
          s.parentNode.insertBefore(hm, s);
        })();
      </script>
LinuxSuRen's avatar
LinuxSuRen 已提交
87 88 89 90 91 92 93 94
  </head>
  <body class="ma0 sans-serif bg-primary-color-light">
    
<nav class="bg-primary-color-dark pv4 w-100" role="navigation">

  <div class="center flex-ns flex-wrap items-center justify-start mw9">

    <h1 class="dim f3 lh-solid ml0-ns mr0 mr4-l mv0 pl3 pl4-ns">
LinuxSuRen's avatar
LinuxSuRen 已提交
95
      <a href="https://jenkins-zh.cn/" class="link white">
LinuxSuRen's avatar
LinuxSuRen 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
         Jenkins 中文社区
      </a>
    </h1>
    <ul class="list ma0 pa0 dn dib-l">
      
        <li class="f5 dib mr4" role="menuitem">
            
            
          <a href="/wechat/" class="dim link light-silver"
            >
            微信
              
            
          </a>
        </li>
      
        <li class="f5 dib mr4" role="menuitem">
            
            
          <a href="/event/" class="dim link light-silver"
            >
            活动
              
            
          </a>
        </li>
      
        <li class="f5 dib mr4" role="menuitem">
            
            
          <a href="/about/" class="dim link light-silver"
            >
            关于我们
              
            
          </a>
        </li>
      
        <li class="f5 dib mr4" role="menuitem">
            
            
          <a href="http://jenkins.io/zh" class="dim link light-silver"
            target="_blank">
            Jenkins 官网
              
            
              <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="10" height="10" viewBox="0 0 32 32" class="fill-current v-base" aria-label="External Link">
<path d="M25.152 16.576v5.696q0 2.144-1.504 3.648t-3.648 1.504h-14.848q-2.144 0-3.648-1.504t-1.504-3.648v-14.848q0-2.112 1.504-3.616t3.648-1.536h12.576q0.224 0 0.384 0.16t0.16 0.416v1.152q0 0.256-0.16 0.416t-0.384 0.16h-12.576q-1.184 0-2.016 0.832t-0.864 2.016v14.848q0 1.184 0.864 2.016t2.016 0.864h14.848q1.184 0 2.016-0.864t0.832-2.016v-5.696q0-0.256 0.16-0.416t0.416-0.16h1.152q0.256 0 0.416 0.16t0.16 0.416zM32 1.152v9.12q0 0.48-0.352 0.8t-0.8 0.352-0.8-0.352l-3.136-3.136-11.648 11.648q-0.16 0.192-0.416 0.192t-0.384-0.192l-2.048-2.048q-0.192-0.16-0.192-0.384t0.192-0.416l11.648-11.648-3.136-3.136q-0.352-0.352-0.352-0.8t0.352-0.8 0.8-0.352h9.12q0.48 0 0.8 0.352t0.352 0.8z"></path>
</svg>

            
          </a>
        </li>
      
    </ul>

    <div class="db dib-ns pl3"><form id="site-search-form" action="" role="search">
  <fieldset class="bn ma0 pa0">
    <label class="clip" for="email-address">Search</label>
    <input type="search" id="search-input" class="needs-js bg-left bg-transparent bn f5 input-reset lh-solid mt3 mt0-ns pl4 pv2 w5 white"
      placeholder="搜索文档" type="text"
      name="email-address" value="" style="background-image:url('/images/icon-search.png');background-size:16px 16px;">
  </fieldset>
</form>
</div>

    <div class="list ma0 pa0 dn dib-l"></div>

    <span class="absolute mt1 mt2-l pr3 right-0 top-0">

<a class="github-button needs-js link primary-color-dark" href="https://github.com/jenkins-zh/jenkins-zh/" data-size="large" data-show-count="false" aria-label="Star Jenkins WeChat GitHub">Star</a>
</span>

  </div>
</nav>

    
    <main role="main" class="content-with-sidebar min-vh-100 pb7 pb0-ns">
      
<main>
  <article class="w-100 ph4 pb5 pb6-ns pt1 pt5-ns">
    <div class="flex-l">
      

      <div class="order-2 w-100 w-20-l ph5-m ph0-l mb4 sticky">



  <aside class="mw5 br3 mv3 nested-links">
    
    
      
LinuxSuRen's avatar
LinuxSuRen 已提交
188 189 190 191 192 193 194 195 196 197
        <h3 class="f4 dib">
            翟志军
        </h3>

      
      
        <p class="lh-copy measure center mt0 f6 black-60">
          《Jenkins 2.x实践指南》作者,购买地址:https://item.jd.com/12512889.html?dist=jd

        </p>
LinuxSuRen's avatar
LinuxSuRen 已提交
198
      
LinuxSuRen's avatar
LinuxSuRen 已提交
199
      <a href="https://github.com/zacker330" target="_blank" class="link dim v-mid dib">
LinuxSuRen's avatar
LinuxSuRen 已提交
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
        <svg version="1.1" fill="gray" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="16" height="18" viewBox="0 0 27 32">
<path d="M9.28 21.44q0.064-0.128-0.064-0.256-0.16-0.128-0.256-0.032-0.064 0.128 0.064 0.224 0.16 0.128 0.256 0.064zM8.768 20.704q-0.096-0.128-0.224-0.096-0.096 0.096 0 0.224 0.128 0.16 0.224 0.096t0-0.224zM8.032 19.968q0.032-0.064-0.096-0.128-0.128-0.032-0.128 0.032-0.064 0.096 0.064 0.16 0.16 0.032 0.16-0.064zM8.416 20.384q0.032 0 0.032-0.064t-0.064-0.096q-0.128-0.128-0.192-0.064t0.032 0.192q0.096 0.096 0.192 0.032zM9.952 21.728q0.032-0.128-0.16-0.192-0.16-0.064-0.224 0.064t0.16 0.192q0.16 0.064 0.224-0.064zM10.688 21.792q0-0.16-0.192-0.16t-0.192 0.16 0.192 0.128 0.192-0.128zM11.392 21.664q-0.032-0.128-0.224-0.096t-0.16 0.16q0.032 0.16 0.192 0.096t0.192-0.16zM22.848 16q0-3.776-2.656-6.464t-6.464-2.688-6.464 2.688-2.688 6.464q0 2.976 1.76 5.376t4.48 3.296q0.32 0.064 0.48-0.096t0.16-0.352q0-0.928-0.032-1.696-0.096 0.032-0.256 0.064t-0.64 0.032-0.864-0.096-0.768-0.352-0.544-0.736q-0.416-1.056-1.024-1.312-0.032-0.032-0.064-0.064l-0.16-0.16t-0.096-0.16 0.064-0.128 0.352-0.064q0.096 0 0.256 0.032t0.544 0.288 0.576 0.64q0.288 0.48 0.672 0.736t0.768 0.256 0.704-0.064 0.512-0.16q0.128-0.864 0.608-1.248-0.896-0.096-1.536-0.32t-1.312-0.704-0.992-1.344-0.352-2.144q0-1.408 0.96-2.464-0.448-1.088 0.096-2.4 0.32-0.128 0.96 0.128t1.088 0.512l0.448 0.288q1.056-0.288 2.304-0.288t2.272 0.288q0.192-0.128 0.512-0.32t0.992-0.448 1.024-0.16q0.512 1.312 0.096 2.4 0.928 1.056 0.928 2.464 0 1.024-0.256 1.792t-0.64 1.248-0.928 0.8-1.12 0.448-1.216 0.224q0.608 0.544 0.608 1.696 0 0.704 0 1.6t-0.032 0.896q0 0.224 0.16 0.352t0.48 0.096q2.752-0.928 4.512-3.296t1.728-5.376zM27.424 7.424v17.152q0 2.112-1.504 3.616t-3.648 1.536h-17.12q-2.144 0-3.648-1.536t-1.504-3.616v-17.152q0-2.112 1.504-3.616t3.648-1.536h17.12q2.144 0 3.648 1.536t1.504 3.616z"></path>
</svg>

      </a>
  </aside>


<aside class="fixed-lTK mw5-l right-0 f6 bl-l b--moon-gray pv4 pv0-ns ph4-l nested-list-reset nested-links nested-copy-line-height">
	
		<p class="b">此页面上的内容</p>
  	<nav id="TableOfContents">
<ul>
<li>
<ul>
<li><a href="#1-实验环境介绍">1. 实验环境介绍</a></li>
<li><a href="#2-启动实验环境">2. 启动实验环境</a></li>
<li><a href="#3-在-jenkins-上创建部署任务">3. 在 Jenkins 上创建部署任务</a></li>
<li><a href="#4-手工触发一次自动化构建">4. 手工触发一次自动化构建</a></li>
<li><a href="#5-代码讲解">5. 代码讲解</a>
<ul>
<li><a href="#5-1流水线逻辑">5.1流水线逻辑</a></li>
<li><a href="#5-2-部署逻辑">5.2 部署逻辑</a></li>
<li><a href="#5-3-配置管理">5.3 配置管理</a></li>
<li><a href="#总结">总结</a></li>
<li><a href="#附录">附录</a></li>
</ul></li>
</ul></li>
</ul>
</nav>
	

	<div date-pref>
		<a href=".." class="dib f6 pl1 hover-bg-light-gray br-100">
			<svg class="fill-current" height="30px" viewBox="0 0 24 24" width="30px" xmlns="http://www.w3.org/2000/svg">
      <path transform="rotate(90 11.704999923706055,12.000000000000002) " d="m15.41,7.41l-1.41,-1.41l-6,6l6,6l1.41,-1.41l-4.58,-4.59l4.58,-4.59z" id="svg_1"/>
    <path d="M0 0h24v24H0z" fill="none"/>
</svg>

		</a>
		
		
LinuxSuRen's avatar
LinuxSuRen 已提交
242
			<a href="https://jenkins-zh.cn/wechat/articles/2019/04/2019-04-26-progressive-delivery-with-jenkins-x/" class="dib f6 pl1 hover-bg-light-gray br-100" title="使用 Jenkins X 渐进式交付 ">
LinuxSuRen's avatar
LinuxSuRen 已提交
243 244 245 246 247 248 249
				<svg class="fill-current" height="30px" viewBox="0 0 24 24" width="30px" xmlns="http://www.w3.org/2000/svg">
    <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/>
    <path d="M0 0h24v24H0z" fill="none"/>
</svg>

			</a>
		
LinuxSuRen's avatar
LinuxSuRen 已提交
250 251

		
LinuxSuRen's avatar
LinuxSuRen 已提交
252
			<a href="https://jenkins-zh.cn/wechat/articles/2019/04/2019-04-24-progressive-delivery-in-kubernetes-blue-green-and-canary-deployments/" class="dib f6 pr1 hover-bg-light-gray br-100" title="Kubernetes 中的渐进式交付:蓝绿部署和金丝雀部署">
LinuxSuRen's avatar
LinuxSuRen 已提交
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
			<svg class="fill-current" height="30px" viewBox="0 0 24 24" width="30px" xmlns="http://www.w3.org/2000/svg">
    <path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/>
    <path d="M0 0h24v24H0z" fill="none"/>
</svg>

			</a>
		
	</div>

</aside>
</div>

      <div class="order-1 w-80-l mw8 ph0 ph5-ns mid-gray nested-copy-line-height no-underline nested-links nested-img nested-copy-seperator nested-blockquote mt0-ns" style="flex-grow:1;">
        <div class="documentation-copy center mw8">
          <div id="readout" class="fixed right-0 bottom-0">
          </div>
          <header class="flex-none w-100">
  
  <h1 class="lh-title mb3 mv0 pt3 primary-color-dark">使用 Jenkins &#43; Ansible 实现自动化部署 Nginx</h1>
</header>

<aside class="bt bw1 pt3 mt2 mid-gray b--mid-gray fn w-100">
  
    <div class="f4 fw4 lh-copy">
      使用 Jenkins + Ansible 实现自动化部署 Nginx
    </div>
  

  
</aside>



<div class="prose" id="prose">



<p>本文介绍如何使用 Jenkins + Ansible 实现对 Nginx 的自动化部署。最终达到的效果有如下几点:
1. 只要你将 Nginx 的配置推送到 GitHub 中,Jenkins 就会自动执行部署,然后目标服务器的 Nginx 配置自动生效。这个过程是幂等(idempotent)的,只要代码不变,执行多少遍,最终效果不变。
2. 如果目标机器没有安装 Nginx,则会自动安装 Nginx。
3. 自动设置服务器防火墙规则。</p>

<h2 id="1-实验环境介绍">1. 实验环境介绍</h2>

<p>本次实验使用 Docker Compose 搭建 Jenkins 及 Jenkins agent。使用 Vagrant 启动一台虚拟机,用于部署 Nginx。使用 Vagrant 是可选的,读者可以使用 VirtualBox 启动一个虚拟机。使用 Vagrant 完全是为了自动化搭建实验环境。</p>

<p>以下是整个实验环境的架构图:
LinuxSuRen's avatar
LinuxSuRen 已提交
300
<img src="../../../images/articles/2019/04/2019-04-25-jenkins-ansible-nginx/pc1.png" alt="Jenkins Ansible Nginx" /></p>
LinuxSuRen's avatar
LinuxSuRen 已提交
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332

<p>注意,图中的 <code>5123 &lt;-&gt; 80</code> 代表将宿主机的 5123 端口请求转发到虚拟机中的 80 端口。</p>

<ul>
<li><a href="https://vagrantup.com">Vagrant</a>:虚拟机管理工具,通过它,我们可以使用文本来定义、管理虚拟机。</li>
<li><a href="https://www.ansible.com/">Ansible</a>:自动化运维工具</li>
<li><a href="https://docs.docker.com/compose/">Docker Compose</a>:它是一个用于定义和运行多容器 Docker 应用程序的工具。可以使用 YAML 文件来配置应用程序的服务。</li>
</ul>

<h2 id="2-启动实验环境">2. 启动实验环境</h2>

<ol>
<li>克隆代码并进入文件夹
<code>bash
git clone https://github.com/zacker330/jenkins-ansible-nginx.git
cd jenkins-ansible-nginx
</code></li>
<li>构建 Jenkins agent 的镜像
 需要自定义 Jenkins agent 镜像有两个原因:

<ol>
<li>本次实验,使用 Swarm 插件实现 Jenkins master  与 agent 之间的通信,所以 Jenkins agent 需要启动 swarm 客户端。</li>
<li>Jenkins agent 必须支持 Ansible。
<code>bash
docker build -f JenkinsSlaveAnsibleDockerfile -t jenkins-swarm-ansible .
</code></li>
</ol></li>
<li>启动 Jenkins master 及 Jenkins agent
<code>bash
docker-compose up -d
</code>
通过 <code>http://localhost:8080</code> 访问 Jenkins master,如果出现“解锁密码”页面,如下图,则执行命令 <code>docker-compose logs jenkins</code> 查看 Jenkins master 启动日志。将日志中的解锁密码输入到表单中。然后就一步步按提示安装即可。
LinuxSuRen's avatar
LinuxSuRen 已提交
333
<img src="../../../images/articles/2019/04/2019-04-25-jenkins-ansible-nginx/pc2.png" alt="解锁Jenkins" /></li>
LinuxSuRen's avatar
LinuxSuRen 已提交
334 335 336 337 338 339 340 341 342 343 344 345
<li>安装 Jenkins 插件
本次实验需要安装以下插件:

<ul>
<li>Pipeline 2.6:<a href="https://plugins.jenkins.io/workflow-aggregator">https://plugins.jenkins.io/workflow-aggregator</a></li>
<li>Swarm 3.15:<a href="https://plugins.jenkins.io/swarm">https://plugins.jenkins.io/swarm</a>
用于 实现 Jenkins master 与 Jenkins agent 自动连接</li>
<li>Git 3.9.3:<a href="https://plugins.jenkins.io/git">https://plugins.jenkins.io/git</a></li>
</ul></li>

<li><p>配置 Jenkins master 不执行任务
进入页面:<a href="http://localhost:8080/computer/(master)/configure">http://localhost:8080/computer/(master)/configure</a>,如下图所示设置:
LinuxSuRen's avatar
LinuxSuRen 已提交
346
<img src="../../../images/articles/2019/04/2019-04-25-jenkins-ansible-nginx/pc9.png" alt="image.png" /></p></li>
LinuxSuRen's avatar
LinuxSuRen 已提交
347 348 349

<li><p>确认 Jenkins 安全配置有打开端口,以供 Jenkins agent 连接。
我们设置 Jenkins master 开放的端口,端口可以是固定的 50000 ,也可以设置为随机。设置链接:<a href="http://localhost:8080/configureSecurity/">http://localhost:8080/configureSecurity/</a>
LinuxSuRen's avatar
LinuxSuRen 已提交
350
<img src="../../../images/articles/2019/04/2019-04-25-jenkins-ansible-nginx/pc3.png" alt="image.png" /></p></li>
LinuxSuRen's avatar
LinuxSuRen 已提交
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366

<li><p>启动目标机器,用于部署 Nginx
在命令行中执行以下命令:</p>

<pre><code class="language-bash">vagrant up 
</code></pre>

<p>注意,Vagrantfile 文件中的 <code>config.vm.box</code> 值必须改成你的 vagrant box 。</p></li>
</ol>

<p>至此,实验环境已经搭建好了。接下来就可以新建 Jenkins 任务了。</p>

<h2 id="3-在-jenkins-上创建部署任务">3. 在 Jenkins 上创建部署任务</h2>

<ol>
<li>新建流水线任务
LinuxSuRen's avatar
LinuxSuRen 已提交
367
<img src="../../../images/articles/2019/04/2019-04-25-jenkins-ansible-nginx/pc4.png" alt="新建流水线任务" /></li>
LinuxSuRen's avatar
LinuxSuRen 已提交
368 369 370

<li><p>配置流水线
配置 Jenkins 任务从远程仓库拉取 Jenkinsfile,如下图所示:
LinuxSuRen's avatar
LinuxSuRen 已提交
371
<img src="../../../images/articles/2019/04/2019-04-25-jenkins-ansible-nginx/pc5.png" alt="配置流水线" />
LinuxSuRen's avatar
LinuxSuRen 已提交
372 373 374 375 376
除此之外,不需要其它配置了,是不是很简单?</p>

<h2 id="4-手工触发一次自动化构建">4. 手工触发一次自动化构建</h2>

<p>点击“立即构建”:
LinuxSuRen's avatar
LinuxSuRen 已提交
377
<img src="../../../images/articles/2019/04/2019-04-25-jenkins-ansible-nginx/pc6.png" alt="image.png" />
LinuxSuRen's avatar
LinuxSuRen 已提交
378
最终执行日志如下:
LinuxSuRen's avatar
LinuxSuRen 已提交
379
<img src="../../../images/articles/2019/04/2019-04-25-jenkins-ansible-nginx/pc7.png" alt="部署日志" /></p></li>
LinuxSuRen's avatar
LinuxSuRen 已提交
380 381 382 383 384 385
</ol>

<p>至此,部署已经完成。以后修改 Nginx 的配置,只需要修改代码,然后推送到远程仓库,就会自动化部署。不需要手工登录到目标机器手工修改了。</p>

<p>最后,我们可以通过访问 <code>http://localhost:5123</code>,如果出现如下页面说明部署成功:</p>

LinuxSuRen's avatar
LinuxSuRen 已提交
386
<p><img src="../../../images/articles/2019/04/2019-04-25-jenkins-ansible-nginx/pc8.png" alt="部署成功" /></p>
LinuxSuRen's avatar
LinuxSuRen 已提交
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500

<h2 id="5-代码讲解">5. 代码讲解</h2>

<p>以上步骤并不能看出自动化部署真正做了什么。那是因为我们所有的逻辑都写在代码中。是的,可以说是 <strong>everything is code</strong></p>

<p>接下来我们介绍代码仓库。</p>

<pre><code class="language-bash">% tree -L 2
├── JenkinsSlaveAnsibleDockerfile # Jenkins agent 镜像 Dockerfile
├── Jenkinsfile  # 流水线逻辑
├── README.md
├── Vagrantfile # Vagrant 虚拟机定义文件
├── docker-compose.yml # Jenkins 实现环境
├── env-conf # 所有应用配置
│   └── dev   # dev 环境的配置
├── deploy  # Ansible 部署脚本所在文件夹
│   ├── playbook.yaml
│   └── roles
└── swarm-client.sh # Jenkins swarm 插件的客户端
</code></pre>

<h3 id="5-1流水线逻辑">5.1流水线逻辑</h3>

<p>Jenkinsfile 文件用于描述整条流水线的逻辑。代码如下:</p>

<pre><code class="language-groovy">pipeline{
  // 任务执行在具有 ansible 标签的 agent 上
  agent { label &quot;ansible&quot;}
  environment{
     // 设置 Ansible 不检查 HOST_KEY 
    ANSIBLE_HOST_KEY_CHECKING = false
  }
  triggers {
     pollSCM('H/1 * * * *')
  }
  stages{
    stage(&quot;deploy nginx&quot;){
      steps{
        sh &quot;ansible-playbook -i env-conf/dev  deploy/playbook.yaml&quot;
      }
}}}
</code></pre>

<ul>
<li><code>environment</code> 部分:用于定义流水线执行过程中的环境变量。</li>
<li><code>triggers</code> 部分:用于定义流水线的触发机制。<code>pollSCM</code> 定义了每分钟判断一次代码是否有变化,如果有变化则自动执行流水线。</li>
<li><code>agent</code> 部分:用于定义整条流水线的执行环境。</li>
<li><code>stages</code> 部分:流水线的所有阶段,都被定义在这部分。</li>
</ul>

<p>以上只是定义流水线是如何执行的,目前整条流水线只有一个 <code>deploy nginx</code> 阶段,并且只执行了一条 <code>ansible-playbook</code> 命令。但是它并没有告诉我们部署逻辑是怎么样的。</p>

<h3 id="5-2-部署逻辑">5.2 部署逻辑</h3>

<p>所有的部署逻辑,包括 Nginx 的安装启动、配置的更新以及加载,都放在 Ansible 脚本中。对 Ansible 不熟的同学,可以在本文末尾找到介绍 Ansible 的文章。</p>

<p>整个部署逻辑的入口在 <code>deploy/playbook.yaml</code>,代码如下:</p>

<pre><code class="language-yaml">---
- hosts: &quot;nginx&quot;
  become: true
  roles:
    # Nginx 的部署
    - ansible-role-nginx
    # 对防火墙的设置
    - ansible-role-firewall
</code></pre>

<ul>
<li><code>hosts</code>:定义了 playbook 部署的目标主机分组名为 <code>nginx</code></li>
<li><code>roles</code>:包含了两个执行具体部署动作的 role,至于 role 内部逻辑,不在本文讨论范围,有兴趣的同学阅读源码。</li>
</ul>

<h3 id="5-3-配置管理">5.3 配置管理</h3>

<p>谈到部署,就不得不谈配置管理。</p>

<p>回顾前文中流水线中执行的 shell 命令:<code>ansible-playbook -i env-conf/dev  deploy/playbook.yaml</code> 我们通过 <code>-i</code> 参数指定部署时所使用的环境配置。通过这种方式实现环境配置与执行脚本的分离。这样带来以下几个好处:
1. 新增环境时,只需要复制现有的环境,然后将里面的变量的值改成新环境的即可。比如,要对测试环境进行部署,只需要将 <code>-i</code> 参数值改成:<code>env-conf/test</code>
2. 对配置版本化控制。</p>

<p>本次实验中,各个环境的配置放在 <code>env-conf</code> 目录中,目前只有 dev 环境,以下是 <code>env-conf/</code> 目录结构:</p>

<pre><code class="language-bash">% cd env-conf/
% tree
└── dev
    ├── group_vars
    │   └── nginx.yaml
    ├── host_vars
    │   └── 192.168.52.10
    └── hosts
</code></pre>

<ul>
<li>hosts文件:Ansible 中通过“分组”来实现对主机的管理。hosts 文件内容如下:
<code>
[nginx]
192.168.52.10
</code></li>
<li>host_vars 目录:用于存放主机级别的配置变量,本例中 <code>192.168.52.10</code> 是一个 YAML 格式文件。注意文件名是该主机的 IP。我们在文件中放主机相关的配置,比如 Ansible 连接主机时使用到的用户名和密码。</li>
<li>group_vars 目录:用于存放组级别的配置变量。比如 nginx.yaml 对应的就是 <code>nginx</code> 这个组的的配置变量。文件名与 <code>hosts</code> 中的组名对应。</li>
</ul>

<h3 id="总结">总结</h3>

<p>到此,我们完整的自动化部署已经讲解完成。但是还遗留下一些问题:
1. 本文只是安装了一个“空”的 Nginx,但是没有介绍 Nginx 真正配置。
2. 目前主机的连接信息(SSH 密码)是明文写在 <code>host_vars/192.168.52.10</code> 文件中的,存在安全风险。
3. 没有介绍如何当 Java 应用部署时,如何自动更新 Nginx 的配置。</p>

<p>本文属于使用 Jenkins + Ansible 实现自动化部署的入门文章,笔者将根据读者的反馈决定是否写续集。</p>

<p>如果觉得本文讲的 Jenkins 流水线逻辑部分不够过瘾,可以考虑入手一本最近才出版的《Jenkins 2.x实践指南》。长按下图进行扫码购买。</p>

LinuxSuRen's avatar
LinuxSuRen 已提交
501
<p><img src="../../../images/articles/2019/04/2019-04-25-jenkins-ansible-nginx/jenkins-2x-in-practice.jpeg" alt="" /></p>
LinuxSuRen's avatar
LinuxSuRen 已提交
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541

<h3 id="附录">附录</h3>

<ul>
<li>本次实验环境代码:<a href="https://github.com/zacker330/jenkins-ansible-nginx">https://github.com/zacker330/jenkins-ansible-nginx</a></li>
<li>简单易懂 Ansible 系列 —— 解决了什么:<a href="https://showme.codes/2017-06-12/ansible-introduce/">https://showme.codes/2017-06-12/ansible-introduce/</a></li>
<li>Puppet,Chef,Ansible 的共性:<a href="https://showme.codes/2016-01-02/the-nature-of-ansible-puppet-chef/">https://showme.codes/2016-01-02/the-nature-of-ansible-puppet-chef/</a></li>
</ul>

</div>


<aside class="bt bw1 pt3 mt2 mid-gray b--mid-gray fn w-100">

</aside>




<script src="https://utteranc.es/client.js"
        repo="jenkins-zh/jenkins-zh.github.io"
        issue-term="pathname"
        theme="github-light"
        crossorigin="linuxsuren"
        async>
</script>


          

        </div>
      </div>
      

    </div>
  </article>

  <div class="w-100 bg-light-gray">
    <div class="mw7 pa4 center nested-lh-copy lh-copy">
      <h6 class="f4 dark-gray mb2">
LinuxSuRen's avatar
LinuxSuRen 已提交
542
  <a href="https://jenkins-zh.cn/wechat/articles/2019/04/2019-04-25-jenkins-ansible-nginx/" class="hide-child link primary-color">
LinuxSuRen's avatar
LinuxSuRen 已提交
543 544 545
  <span class="nl3 child"><svg class="grow" fill="" height="14px" viewBox="0 0 24 24" width="14px" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"/><path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"/></svg>
</span>
    “使用 Jenkins &#43; Ansible 实现自动化部署 Nginx”
LinuxSuRen's avatar
LinuxSuRen 已提交
546 547 548 549
  </a> 更新于:April 25, 2019
  <div>
    原文作者:<a href="" target="_blank">zacker330</a>
  </div>
LinuxSuRen's avatar
LinuxSuRen 已提交
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
</h6>

      <a href="https://github.com/jenkins-zh/jenkins-zh/edit/master/content/wechat/articles/2019/04/2019-04-25-jenkins-ansible-nginx.md" class="
f6 ph3 pv1 br2 dib  tc ttu mv3 bg-primary-color white hover-bg-green link
" target="_blank">改善此页</a>

      

  
  
  

  <div class="nested-lh-copy">
    <ul class="list dib nested-links ml0 pl0">
      
        <li class="db mb2 b">
          Tags:
        </li>
        
          <li class="db dib-l mr3">
            <a class="tag" href="/tags/jenkins">
              jenkins
            </a>
          </li>
        
          <li class="db dib-l mr3">
            <a class="tag" href="/tags/ansible">
              ansible
            </a>
          </li>
        
          <li class="db dib-l mr3">
            <a class="tag" href="/tags/nginx">
              nginx
            </a>
          </li>
        
              
      
        
        
LinuxSuRen's avatar
LinuxSuRen 已提交
591
          <li class="db dib-l mb2 mr3">
LinuxSuRen's avatar
LinuxSuRen 已提交
592 593
            <a href="/wechat/articles/2019/05/2019-05-20-jenkins-ansible-springboot/" class="link">
              使用 Jenkins &#43; Ansible 实现 Spring Boot 自动化部署101
LinuxSuRen's avatar
LinuxSuRen 已提交
594 595 596
            </a>
          </li>
        
LinuxSuRen's avatar
LinuxSuRen 已提交
597 598 599 600 601 602 603
      
        
          <li class="db b mt4 mb2 mr2">
            Related entries:
          </li>
        
        
LinuxSuRen's avatar
LinuxSuRen 已提交
604 605 606 607 608 609 610 611 612
          <li class="db dib-l mb2 mr3">
            <a href="/wechat/articles/2019/05/2019-05-17-from-jenkins-to-jenkins-x/" class="link">
              从 Jenkins 到 Jenkins X
            </a>
          </li>
        
      
        
        
LinuxSuRen's avatar
LinuxSuRen 已提交
613 614 615 616 617 618 619 620 621
          <li class="db dib-l mb2 mr3">
            <a href="/wechat/articles/2019/05/2019-05-15-gsoc-annoncement/" class="link">
              19年 GSoC 中 Jenkins 的七个项目
            </a>
          </li>
        
      
        
        
LinuxSuRen's avatar
LinuxSuRen 已提交
622 623 624 625 626 627 628 629 630
          <li class="db dib-l mb2 mr3">
            <a href="/wechat/articles/2019/05/2019-05-14-devops-jenkins-credential-manage/" class="link">
              基于 Jenkins 的 DevOps 平台应该如何设计凭证管理
            </a>
          </li>
        
      
        
        
LinuxSuRen's avatar
deploy  
LinuxSuRen 已提交
631 632 633 634 635 636 637 638 639
          <li class="db dib-l mb2 mr3">
            <a href="/wechat/articles/2019/05/2019-05-13-jenkins-book-gift/" class="link">
              Jenkins 公众号送书福利
            </a>
          </li>
        
      
        
        
LinuxSuRen's avatar
LinuxSuRen 已提交
640 641 642 643 644 645 646 647 648
          <li class="db dib-l mb2 mr3">
            <a href="/wechat/articles/2019/05/2019-05-09-jenkins-release/" class="link">
              Jenkins 版本发布
            </a>
          </li>
        
      
        
        
LinuxSuRen's avatar
LinuxSuRen 已提交
649 650 651 652 653 654 655 656 657
          <li class="db dib-l mb2 mr3">
            <a href="/wechat/articles/2019/05/2019-05-08-jenkins-plugin-develop-within-two-days-part02/" class="link">
              Jenkins 插件开发之旅:两天内从 idea 到发布(下篇)
            </a>
          </li>
        
      
        
        
LinuxSuRen's avatar
LinuxSuRen 已提交
658 659 660 661 662 663 664 665 666
          <li class="db dib-l mb2 mr3">
            <a href="/wechat/articles/2019/05/2019-05-07-jenkins-install-plugins-shell/" class="link">
              Jenkins 自动化安装插件
            </a>
          </li>
        
      
        
        
LinuxSuRen's avatar
LinuxSuRen 已提交
667 668 669 670 671 672 673 674 675
          <li class="db dib-l mb2 mr3">
            <a href="/wechat/articles/2019/05/2019-05-06-jenkins-plugin-develop-within-two-days-part01/" class="link">
              Jenkins 插件开发之旅:两天内从 idea 到发布(上篇)
            </a>
          </li>
        
      
        
        
LinuxSuRen's avatar
LinuxSuRen 已提交
676 677 678 679 680 681 682 683 684
          <li class="db dib-l mb2 mr3">
            <a href="/wechat/articles/2019/04/2019-04-29-progressive-delivery-with-jenkins-x-automatic-cana/" class="link">
              使用 Jenkins X 渐进式交付:自动化金丝雀部署
            </a>
          </li>
        
      
        
        
LinuxSuRen's avatar
LinuxSuRen 已提交
685 686 687 688 689 690 691 692 693
          <li class="db dib-l mb2 mr3">
            <a href="/wechat/articles/2019/04/2019-04-26-progressive-delivery-with-jenkins-x/" class="link">
              使用 Jenkins X 渐进式交付
            </a>
          </li>
        
      
        
        
LinuxSuRen's avatar
LinuxSuRen 已提交
694 695 696
      
        
        
LinuxSuRen's avatar
LinuxSuRen 已提交
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
          <li class="db dib-l mb2 mr3">
            <a href="/wechat/articles/2019/04/2019-04-23-jenkins-master-shared-home/" class="link">
              关于 Jenkins master 共享 JENKINS_HOME 目录的实验
            </a>
          </li>
        
      
        
        
          <li class="db dib-l mb2 mr3">
            <a href="/wechat/articles/2019/04/2019-04-19-the-business-value-of-cd/" class="link">
              持续交付的商业价值
            </a>
          </li>
        
      
        
        
          <li class="db dib-l mb2 mr3">
            <a href="/wechat/articles/2019/04/2019-04-15-zabbix-monitor-jenkins/" class="link">
              使用 Zabbix 监控 Jenkins
            </a>
          </li>
        
      
        
        
          <li class="db dib-l mb2 mr3">
            <a href="/wechat/articles/2019/04/2019-04-12-brief-analysis-the-encryption-algorithm-of-the-built-in-jenkins-user-database/" class="link">
              简析 Jenkins 专有用户数据库加密算法
            </a>
          </li>
        
      
        
        
          <li class="db dib-l mb2 mr3">
            <a href="/wechat/articles/2019/04/2019-04-10-getting-started-with-docker-for-java-applications/" class="link">
              Java 应用使用 Docker 的入门指南:建立一个 CI/CD 流水线
            </a>
          </li>
        
      
        
        
          <li class="db dib-l mb2 mr3">
            <a href="/wechat/articles/2019/04/2019-04-08-becoming-contributor-intro/" class="link">
              介绍:成为一名 Jenkins 贡献者的旅程
            </a>
          </li>
        
      
        
        
          <li class="db dib-l mb2 mr3">
            <a href="/wechat/articles/2019/03/2019-03-13-electron-pipeline-demo/" class="link">
              Electron 应用的流水线设计
            </a>
          </li>
        
      
        
        
          <li class="db dib-l mb2 mr3">
            <a href="/wechat/articles/2019/03/2019-03-13-ready-for-cdf/" class="link">
              为 Continuous Delivery Foundation 的成立感到兴奋
            </a>
          </li>
        
      
        
        
          <li class="db dib-l mb2 mr3">
            <a href="/wechat/articles/2019/03/2019-01-08-mpl-modular-pipeline-library/" class="link">
              MPL - 模块化的流水线库
            </a>
          </li>
        
      
        
        
          <li class="db dib-l mb2 mr3">
            <a href="/wechat/articles/2019/02/2019-02-27-jenkins-script-console-in-practice/" class="link">
              批量修改 Jenkins 任务的技巧
            </a>
          </li>
        
      
        
        
          <li class="db dib-l mb2 mr3">
            <a href="/wechat/articles/2019/01/2019-01-16-webhook-firewalls/" class="link">
              在安全防火墙内通过 WebHook 触发构建
            </a>
          </li>
        
      
    </ul>
  </div>


    </div>
  </div>
</main>

    </main>

    <footer class="bg-primary-color-dark ph4-ns pt4 relative w-100" role="contentinfo">
  <div class="center flex-ns flex-wrap justify-between mw9 w-90">
    <div class="pb3 pt4 w-100 w-50-ns">

      <div class="b f3  light-gray mb3 nested-links tc">
<a href="https://github.com/jenkins-zh/jenkins-zh/graphs/contributors" target="_blank" class="link">Jenkins 社区贡献者</a> 维护<br/>
      </div>

      <ul class="center f6 list ma0 mv3 pa0 tc" style="display:none"><li class="dib mr3"><a href="https://github.com/jenkins-zh/jenkins-zh/issues/new" class="dim link light-gray pv2">File an Issue</a></li></ul>

      <ul class="center f6 list ma0 mv4 pa0 tc">
        <li class="dib mr3">
          <a href="https://twitter.com/suren69811254" target="_blank" class="dim link light-gray pv2">@suren69811254</a>
        </li>
        <li class="dib mr3">
          <a href="https://www.youtube.com/channel/UC63xz3pq26BBgwB3cnwCoqQ" target="_blank" class="dim link light-gray pv2">YouTube</a>
        </li>
      </ul>

      
    </div>

    <div>
      <a href="https://mp.weixin.qq.com/s/vifdduC3kRGSIMpyL03yVA" target="_blank">
        <img src="https://jenkins.io/images/jenkins-wechat.png" with="100" height="100">
      </a>
    </div>

  </div>

  <div class="f7 gray mb5 mb0-ns ph3 w-100" style="display:none"> 
    <p class="dib mr4">Jenkins&reg; is a registered trademark of <a href="https://www.spi-inc.org/" class="link">Software in the Public Interest, Inc.</a></p>
    <p class="dib">Copyright 2018–2019 the original authors.</p>
  </div>


  <div class="bg-primary-color-dark bottom-0 left-0 right-0 dn-l fixed pb3 ph3 w-100"><div  class="globalmenu mobilemenu pb3 dn">
    

<ul class="list hidden dib ph0 ma0 scrolling-touch tc">
  
    <li  class="tl dib ma0 hover-bg-black w-100">
        <a href="/wechat/" class="ttu f6 link primary-color-light overflow hover-white db brand-font  ma0 w-100 pv3 ph4">
          微信
        </a>
    </li>
  
    <li  class="tl dib ma0 hover-bg-black w-100">
        <a href="/event/" class="ttu f6 link primary-color-light overflow hover-white db brand-font  ma0 w-100 pv3 ph4">
          活动
        </a>
    </li>
  
    <li  class="tl dib ma0 hover-bg-black w-100">
        <a href="/about/" class="ttu f6 link primary-color-light overflow hover-white db brand-font  ma0 w-100 pv3 ph4">
          关于我们
        </a>
    </li>
  
    <li  class="tl dib ma0 hover-bg-black w-100">
        <a href="http://jenkins.io/zh" class="ttu f6 link primary-color-light overflow hover-white db brand-font  ma0 w-100 pv3 ph4">
          Jenkins 官网
        </a>
    </li>
  
</ul>

</div>
<div  class="docsmenu mobilemenu pb3 dn">
    

<ul class="list dib ph0 ma0 scrolling-touch tc">
  
</ul>

</div>

<div class="flex dn-l justify-between">
  <button class="js-toggle flex-auto dib dn-l f6 tc db mt4-ns ph3 pv2 link mr2 white bg-primary-color-dark hover-bg-primary-color ba b--white-40 w-auto" data-target=".globalmenu">Menu</button>

  <button class="js-toggle flex-auto dib dn-l f6 tc db mt4-ns ph3 pv2 link white bg-primary-color-dark hover-bg-primary-color ba b--white-40 w-auto" data-target=".docsmenu">Docs Menu</button>
</div>
</div>

</footer>

    
<link href="/dist/auto-complete.css" rel="stylesheet">
<script type="text/javascript">
    
LinuxSuRen's avatar
LinuxSuRen 已提交
894
        var baseurl = "https:\/\/jenkins-zh.cn\/";
LinuxSuRen's avatar
LinuxSuRen 已提交
895 896 897 898 899 900 901 902 903 904 905 906
    
</script>
<script src="/dist/lunr.js"></script>
<script src="/dist/autocomplete.js"></script>
<script src="/dist/jquery-3.2.1.min.js"></script>
<script src="/dist/search.js"></script>

<script async defer src="https://buttons.github.io/buttons.js"></script>


  </body>
</html>