设为首页 收藏本站
查看: 1369|回复: 0

[经验分享] 利用Fabric+Capistrano实现Python自动化部署

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2016-9-2 09:10:20 | 显示全部楼层 |阅读模式
Fabric是一个用于应用(批量)部署和系统(批量)管理的Python库和命令行工具,关于Fabric的介绍请参考:http://www.fabfile.org/。  Capistrano是一个用Ruby语言编写的远程服务器自动化和部署工具,关于Capistrano的介绍请参考:http://capistranorb.com/
  本文仅使用Python语言和部分Linux或Windows系统命令,借助Fabric模块和Capistrano的部署思路,实现在Linux平台和Windows平台的自动化部批量署应用或实现批量系统管理(批量执行命令,批量上传文件等),其中Fabric部分利用Fabric的模块,Capistrano部分用Python语言按照Capistrano的部署思路“重写(Python实现Capistrano)”。
  关于Capistrano的“重写”说明。Capistrano使用Ruby语言写的,在部署很多应用上有很大的优势,个人认为它设计最好的部分就是它的目录结构。目录结构的详细信息可以参考:http://capistranorb.com/documentation/getting-started/structure/#。有了这个目录结构可以轻松实现每一个部署版本的备份与回滚,之前用Bash Shell“重写”过一次,可以参考本文《Linux Shell脚本之远程自动化部署java maven项目 》,这次相当于用Python重写一下(Capistrano还有大量精髓的东西,本文算是抛砖引玉,其他的日后再发掘),毕竟Shell脚本不容易实现像Fabric那样的批量操作。
  本文的demo是将https://github.com/DingGuodong/GoogleHostsFileForLinux.git 中的用于翻墙访问Google的脚本上传到指定的服务器,以在Windows操作为例,先在本地生成Capistrano目录结构,再把git项目clone到本地,将脚本文件从repo目录下抽出,放到current目录下,current是release目录下某个时间戳的软链接(Windows下测试可能有些奇怪,因为Windows下没法做软连接,用Python创建快捷方式暂时没有找到方法),再将此脚本通过Fabric的put命令上传到指定的远程服务器上。
  demo在脚本中的位置可以从TODO中找到,由于fabric需要通过fab命令+脚本执行,因此在脚本的最后使用了terminal_debug()函数实现脚本执行,如果对python和fabric很熟悉,那么将下文的脚本放到pycharm中打开,略微看看脚本,即时没有注释(有人曾说,好的代码是不写注释的,虽然代码写的不好,但至少要朝着这个目标努力)也能看的很明白。其实在真正了解了Fabric和Capistrano后,重新阅读这个脚本或者看这篇文章一定觉得确实写的很普(渣)通(渣)。
  脚本的部分说明(时间原因就不展开写了,可以等熟悉了Fabric和Capistrano后再看):
  • 此脚本文件的开始几行配置有名字为config的字典,主要用于声明deploy_to、repo_url和branch以及keep_releases;
  • env变量用于向Fabric声明主机信息。

运行结果:
wKioL1fH_crAQZkUAACepNCzna8931.jpg
与Capistrano相同的目录结构:
wKiom1fH_cvCuc26AABcZjS6dK0381.jpg
模仿Capistrano生成的相同格式的日志:
wKiom1fH_czwSPgTAABH1FfFhNg475.jpg
脚本内容可以从GitHub上获取:https://github.com/DingGuodong/L ... elf/pyCapistrano.py
脚本内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
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
188
189
190
191
192
193
194
195
196
197
198
199
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
242
243
244
245
246
247
248
249
250
251
252
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
#!/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
"""
Created by PyCharm.
File:               LinuxBashShellScriptForOps:TestGit.py
User:               Guodong
Create Date:        2016/8/24
Create Time:        9:40
"""
from fabric.api import *
from fabric.main import main
from fabric.colors import *
from fabric.context_managers import *
from fabric.contrib.console import confirm
import os
import sys
import re
import getpass

config = {
    "deploy_to": '/var/www/my_app_name',
    "scm": 'git',
    "repo_url": 'https://github.com/DingGuodong/GoogleHostsFileForLinux.git',
    "branch": 'master',
    "log_level": 'debug',
    "keep_releases": 10
}

env.roledefs = {
    'test': ['root@10.6.28.28:22', ],
    'nginx': ['root@10.6.28.46:22', 'root@10.6.28.27:22', ],
    'db': ['root@10.6.28.35:22', 'root@10.6.28.93:22', ],
    'sit': ['root@10.6.28.46:22', 'root@10.6.28.135:22', 'root@10.6.28.35:22', ],
    'uat': ['root@10.6.28.27:22', 'root@10.6.28.125:22', 'root@10.6.28.93:22', ],
    'all': ["10.6.28.27", "10.6.28.28", "10.6.28.35", "10.6.28.46", "10.6.28.93", "10.6.28.125", "10.6.28.135"]
}

env.user = "root"
env.hosts = ["10.6.28.27", "10.6.28.28", "10.6.28.35", "10.6.28.46", "10.6.28.93", "10.6.28.125", "10.6.28.135"]


def win_or_linux():
    # os.name ->(sames to) sys.builtin_module_names
    if 'posix' in sys.builtin_module_names:
        os_type = 'Linux'
    elif 'nt' in sys.builtin_module_names:
        os_type = 'Windows'
    return os_type


def is_windows():
    if "windows" in win_or_linux().lower():
        return True
    else:
        return False


def is_linux():
    if "linux" in win_or_linux().lower():
        return True
    else:
        return False


class Capistrano(object):
    class SCM(object):
        class Git(object):
            def __init__(self):
                self.repo_url = None
                self.name = None
                self.branch = None
                self.repo_path = None
                self.user = None

            def set(self, repo_url, branch=None, repo_path=None):
                if repo_url is None:
                    abort("You must specify a repository to clone.")
                else:
                    self.repo_url = repo_url
                if branch is None:
                    self.branch = "master"
                else:
                    self.branch = branch

                pattern = re.compile(r"(\w+)(?=\.git$)")
                match = pattern.search(repo_url)
                if match:
                    paths = match.group()
                else:
                    paths = None
                if repo_path is not None and not os.path.exists(repo_path):
                    try:
                        os.mkdir(repo_path)
                    except IOError:
                        repo_path = os.path.join(os.path.dirname(__file__), paths)
                elif repo_path is None:
                    repo_path = ""
                self.repo_path = os.path.abspath(repo_path)

            def clone(self):
                local("git clone --branch %s %s %s" % (self.branch, self.repo_url, self.repo_path))

            def check(self):
                with lcd(self.repo_path):
                    return local("git ls-remote --heads %s" % self.repo_url, capture=True)

            def pull(self):
                with lcd(self.repo_path):
                    if os.path.exists(os.path.join(self.repo_path, ".git")):
                        local("git pull origin %s" % self.branch)
                    else:
                        self.clone()
                        self.pull()

            def update(self):
                pass

            def status(self):
                with lcd(self.repo_path):
                    local("git status")

            def branch(self):
                with lcd(self.repo_path):
                    local("git rev-parse --abbrev-ref HEAD", capture=True)

            def long_id(self):
                with lcd(self.repo_path):
                    return local("git rev-parse HEAD", capture=True)

            def short_id(self):
                with lcd(self.repo_path):
                    return local("git rev-parse --short HEAD", capture=True)

            def fetch_revision(self):
                with lcd(self.repo_path):
                    return local("git rev-list --max-count=1 %s" % self.branch, capture=True)

            def user(self):
                if is_linux():
                    self.user = "%s(%s)" % (os.getlogin(), os.getuid())
                if is_windows():
                    import getpass
                    self.user = getpass.getuser()

    class DSL(object):
        class Paths(object):
            def __init__(self):
                self.deploy_to = config['deploy_to']
                self.current = None

            # TODO(Guodong Ding) fetch 'deploy_to' from config file or dict
            def deploy_path(self):
                return os.path.abspath(self.deploy_to)

            def current_path(self):
                current_directory = "current"
                return os.path.join(self.deploy_path(), current_directory)

            def releases_path(self):
                return os.path.join(self.deploy_path(), "releases")

            def set_release_path(self):
                import datetime
                timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
                self.current = os.path.join(self.releases_path(), timestamp)
                return os.path.join(self.releases_path(), timestamp)

            def shared_path(self):
                return os.path.join(self.deploy_path(), "shared")

            def repo_path(self):
                return os.path.join(self.deploy_path(), "repo")

            def revision_log(self):
                return os.path.join(self.deploy_path(), "revisions.log")

            def __paths(self):
                return self.releases_path(), self.repo_path(), self.shared_path()

            def makepaths(self):
                for directory in self.__paths():
                    if not os.path.exists(directory):
                        os.makedirs(directory)

            def make_release_dirs(self):
                os.makedirs(self.set_release_path())

            def make_current(self):
                if is_linux():
                    if os.path.exists(self.current_path()) and os.path.islink(self.current_path()):
                        os.unlink(self.current_path())
                    os.symlink(self.current, self.current_path())
                if is_windows():
                    if os.path.exists(self.current_path()):
                        import shutil
                        shutil.rmtree(self.current_path())
                    try:
                        local("ln -sd %s %s" % (self.current, self.current_path()))
                    except Exception:
                        raise NotImplementedError

            def update_revision_log(self, branch=None, sid=None, release=None, by=None):
                print blue("Log details of the deploy")
                with open(self.revision_log(), 'a') as f:
                    f.write("Branch %s (at %s) deployed as release %s by %s\n" % (branch, sid, release, by))

            def cleanup(self):
                keep_releases = config['keep_releases']
                releases = local("ls -xtr %s" % self.releases_path(), capture=True).split()
                # print releases[-keep_releases:]
                if len(releases) > keep_releases:
                    for release in releases[0:(len(releases) - keep_releases)]:
                        local("rm -rf %s" % os.path.join(self.releases_path(), release))

            @staticmethod
            def __get_file_last_line(inputfile):
                filesize = os.path.getsize(inputfile)
                blocksize = 1024
                with open(inputfile, 'rb') as f:
                    last_line = ""
                    if filesize > blocksize:
                        maxseekpoint = (filesize // blocksize)
                        f.seek((maxseekpoint - 1) * blocksize)
                    elif filesize:
                        f.seek(0, 0)
                    lines = f.readlines()
                    if lines:
                        lineno = 1
                        while last_line == "":
                            last_line = lines[-lineno].strip()
                            lineno += 1
                    return last_line

            def rollback(self):
                print blue("Revert to previous release timestamp")
                revision_log_message = self.__get_file_last_line(self.revision_log())
                last_release = None
                import re
                s = re.compile(r"release (.*) by")
                match = s.search(revision_log_message)
                if match:
                    last_release = match.groups()[0]
                else:
                    abort("Can NOT found rollback release in revision log files, %s." % self.revision_log())
                if os.path.exists(last_release):
                    print yellow("Symlink previous release to current")
                else:
                    abort("Can NOT found rollback release on filesystem.")
                if is_linux():
                    if os.path.exists(self.current_path()) and os.path.islink(self.current_path()):
                        os.unlink(self.current_path())
                    os.symlink(last_release, self.current_path())
                if is_windows():
                    if os.path.exists(self.current_path()):
                        import shutil
                        shutil.rmtree(self.current_path())
                    try:
                        local("ln -sd %s %s" % (last_release, self.current_path()))
                    except Exception:
                        raise NotImplementedError

    class Application(object):
        class Deploy(object):
            def __init__(self):
                self.P = Capistrano.DSL.Paths()
                self.G = Capistrano.SCM.Git()

            def deploy(self):
                # TODO(Guodong Ding): core job here, this is a deploy demo
                with lcd(self.P.current_path()):
                    try:
                        src = os.path.join(self.P.repo_path(), "replaceLocalHostsFileAgainstGfw.sh")
                        local_path = os.path.join(self.P.current_path(), "hosts")
                        remote_path = "/tmp/replaceLocalHostsFileAgainstGfw.sh"
                        with open(src, 'r') as f:
                            content = f.read()
                        with open(local_path, "w") as f:
                            f.write(content)
                        if os.path.getsize(local_path):
                            print red("upload files to remote hosts")
                            put(local_path, remote_path)
                            run("chmod +x %s" % remote_path)
                            run("ls -al %s" % remote_path)
                            print red("deploy test demo successfully!")
                    except IOError:
                        raise NotImplementedError

            def run(self):
                print blue("Do deploy procedure.")
                self.P.makepaths()
                self.G.set(config["repo_url"], repo_path=self.P.repo_path())
                self.G.pull()

                self.P.make_release_dirs()
                self.P.make_current()
                self.deploy()
                self.P.update_revision_log(self.G.branch, self.G.short_id(), self.P.current, getpass.getuser())
                self.P.cleanup()
                print green("Deploy successfully!")


@roles("test")
def test_deploy():
    c = Capistrano.Application.Deploy()
    c.run()


def terminal_debug(defName):
    command = "fab -i c:\Users\Guodong\.ssh\exportedkey201310171355\
                -f %s \
                %s" % (__file__, defName)
    os.system(command)
    sys.exit(0)


if __name__ == '__main__':
    if len(sys.argv) == 1 and is_windows():
        terminal_debug("test_deploy")

    sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
    print red("Please use 'fab -f %s'" % " ".join(str(x) for x in sys.argv[0:]))
    sys.exit(1)



关于Fabric的进一步使用可以参考GitHub上的另一个文件:https://github.com/DingGuodong/L ... thonSelf/fabfile.py 此文件有更多关于Fabric的示例,可以更好的说明Fabric的用途。
最后,不得不说Python是优秀的编程、脚本语言,用在运维上确实很方便,只需短短的几天时间就可以编写出有用的脚本。作为运维人员不必排斥编程,编程是为了更好的运维。如果觉得本文有用,可以继续关注这个GitHub项目(https://github.com/DingGuodong/LinuxBashShellScriptForOps),这个项目会持续完善,积累更多有用的Shell、Python编程和运维的相关知识和文件。
--end--


运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-266436-1-1.html 上篇帖子: 升级python以及安装anaconda 下篇帖子: python根据文件更改日期删除指定文件夹下面文件
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表