Ansible源码分析之svn模块

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 指定模块参数,每个模块的参数不同

repo 指定svn的URL

dest 指定代码checkout或者export的绝对路径

username 指定用户名

password 指定密码

export 指定导出而不是checkout或者update

force 强制执行


如果执行过程有以下错误

"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",

解决办法就是:

将系统的字符编号和ansible的字符编号都设置成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中设置的默认字符编码就是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和一些类参数


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()

定义类函数_exec,调用module_utils/basic.py中的run_command 函数

 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函数,分别执行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相关的函数

    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


两个函数执行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函数,先判断是export还是checkout,再判断dest指定的目录是否存在,再判断版本有没有更新










参考文档:

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