溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Ansible源碼分析之svn模塊

發(fā)布時間:2020-07-21 07:10:45 來源:網(wǎng)絡(luò) 閱讀:3045 作者:自由linux 欄目:開發(fā)技術(shù)

Ansible的svn模塊代碼路徑

/usr/lib/python2.6/site-packages/ansible/modules/core/source_control


模塊使用:

# ansible localhost -m subversion -a "repo=https://code.svn.com/project1/patch_04 dest=~/test username=test password=test123   export=yes force=yes"


-m subversion表示指定subversion模塊,這里的模塊名稱都是modules目錄下的腳本名稱

-a 指定模塊參數(shù),每個模塊的參數(shù)不同

repo 指定svn的URL

dest 指定代碼checkout或者export的絕對路徑

username 指定用戶名

password 指定密碼

export 指定導(dǎo)出而不是checkout或者update

force 強(qiáng)制執(zhí)行


如果執(zhí)行過程有以下錯誤

"msg": "svn: Can't convert string from 'UTF-8' to native encoding:\nsvn: /root/john/test/web/WebRoot/html/?\\230?\\181?\\160?\\239?\\189?\\135?\\230?\\130?\\138",

解決辦法就是:

將系統(tǒng)的字符編號和ansible的字符編號都設(shè)置成en_US.UTF-8

# echo $LANG
en_US.UTF-8
# cat /etc/ansible/ansible.cfg|grep module_lang
module_lang    = en_US.UTF-8


同時在subversion.py中設(shè)置的默認(rèn)字符編碼就是C

os.environ['LANG'] = 'C'


class Subversion(object):
    def __init__(
            self, module, dest, repo, revision, username, password, svn_path):
        self.module = module
        self.dest = dest
        self.repo = repo
        self.revision = revision
        self.username = username
        self.password = password
        self.svn_path = svn_path


定義一個Python類Subversion和一些類參數(shù)


def _exec(self, args):
        bits = [
            self.svn_path,
            '--non-interactive',
            '--trust-server-cert',
            '--no-auth-cache',
        ]
        if self.username:
            bits.extend(["--username", self.username])
        if self.password:
            bits.extend(["--password", self.password])
        bits.extend(args)
        rc, out, err = self.module.run_command(bits, check_rc=True)
        return out.splitlines()

定義類函數(shù)_exec,調(diào)用module_utils/basic.py中的run_command 函數(shù)

 def checkout(self):
        '''Creates new svn working directory if it does not already exist.'''
        self._exec(["checkout", "-r", self.revision, self.repo, self.dest])

 def export(self, force=False):
        '''Export svn repo to directory'''
        cmd = ["export"]
        if force:
            cmd.append("--force")
        cmd.extend(["-r", self.revision, self.repo, self.dest])

        self._exec(cmd)


定義checkout和export函數(shù),分別執(zhí)行svn checkout 或者svn export 


    def switch(self):
        '''Change working directory's repo.'''
        # switch to ensure we are pointing at correct repo.
        self._exec(["switch", self.repo, self.dest])

    def update(self):
        '''Update existing svn working directory.'''
        self._exec(["update", "-r", self.revision, self.dest])

    def revert(self):
        '''Revert svn working directory.'''
        self._exec(["revert", "-R", self.dest])

    def get_revision(self):
        '''Revision and URL of subversion working directory.'''
        text = '\n'.join(self._exec(["info", self.dest]))
        rev = re.search(r'^Revision:.*$', text, re.MULTILINE).group(0)
        url = re.search(r'^URL:.*$', text, re.MULTILINE).group(0)
        return rev, url


定義svn switch, svn update,svn revert,svn get_revision相關(guān)的函數(shù)

    def has_local_mods(self):
        '''True if revisioned files have been added or modified. Unrevisioned files are ignored.'''
        lines = self._exec(["status", self.dest])
        # Match only revisioned files, i.e. ignore status '?'.
        regex = re.compile(r'^[^?]')
        # Has local mods if more than 0 modifed revisioned files.
        return len(filter(regex.match, lines)) > 0

    def needs_update(self):
        curr, url = self.get_revision()
        out2 = '\n'.join(self._exec(["info", "-r", "HEAD", self.dest]))
        head = re.search(r'^Revision:.*$', out2, re.MULTILINE).group(0)
        rev1 = int(curr.split(':')[1].strip())
        rev2 = int(head.split(':')[1].strip())
        change = False
        if rev1 < rev2:
            change = True
        return change, curr, head


兩個函數(shù)執(zhí)行svn status 和svn info



def main():
    module = AnsibleModule(
        argument_spec=dict(
            dest=dict(required=True),
            repo=dict(required=True, aliases=['name', 'repository']),
            revision=dict(default='HEAD', aliases=['rev', 'version']),
            force=dict(default='no', type='bool'),
            username=dict(required=False),
            password=dict(required=False),
            executable=dict(default=None),
            export=dict(default=False, required=False, type='bool'),
        ),
        supports_check_mode=True
    )

    dest = os.path.expanduser(module.params['dest'])
    repo = module.params['repo']
    revision = module.params['revision']
    force = module.params['force']
    username = module.params['username']
    password = module.params['password']
    svn_path = module.params['executable'] or module.get_bin_path('svn', True)
    export = module.params['export']

    os.environ['LANG'] = 'C'
    svn = Subversion(module, dest, repo, revision, username, password, svn_path)

    if export or not os.path.exists(dest):
        before = None
        local_mods = False
        if module.check_mode:
            module.exit_json(changed=True)
        if not export:
            svn.checkout()
        else:
            svn.export(force=force)
    elif os.path.exists("%s/.svn" % (dest, )):
        # Order matters. Need to get local mods before switch to avoid false
        # positives. Need to switch before revert to ensure we are reverting to
        # correct repo.
        if module.check_mode:
            check, before, after = svn.needs_update()
            module.exit_json(changed=check, before=before, after=after)
        before = svn.get_revision()
        local_mods = svn.has_local_mods()
        svn.switch()
        if local_mods:
            if force:
                svn.revert()
            else:
                module.fail_json(msg="ERROR: modified files exist in the repository.")
        svn.update()
    else:
        module.fail_json(msg="ERROR: %s folder already exists, but its not a subversion repository." % (dest, ))

    if export:
        module.exit_json(changed=True)
    else:
        after = svn.get_revision()
        changed = before != after or local_mods
        module.exit_json(changed=changed, before=before, after=after)

# import module snippets
from ansible.module_utils.basic import *
main()


這里就是svn模塊的main函數(shù),先判斷是export還是checkout,再判斷dest指定的目錄是否存在,再判斷版本有沒有更新










參考文檔:

https://github.com/ansible/ansible/issues/6737#ref-commit-42aa6ff


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI