diff options
author | Michael DeHaan <michael.dehaan@gmail.com> | 2014-09-26 09:23:50 -0400 |
---|---|---|
committer | Michael DeHaan <michael.dehaan@gmail.com> | 2014-09-26 09:23:50 -0400 |
commit | 73123b69fa5c15babaf28b2e5980b946ead1ace5 (patch) | |
tree | c757a913f95f26d08ebca9e2fbe586ccb1e45e7e /source_control | |
parent | b2b5cc032caf22ece54852dc023b888baf109c8b (diff) | |
download | ansible-modules-core-73123b69fa5c15babaf28b2e5980b946ead1ace5.tar.gz |
Move modules into subdirectory.
Diffstat (limited to 'source_control')
-rw-r--r-- | source_control/bzr | 198 | ||||
-rw-r--r-- | source_control/git | 607 | ||||
-rw-r--r-- | source_control/github_hooks | 178 | ||||
-rw-r--r-- | source_control/hg | 238 | ||||
-rw-r--r-- | source_control/subversion | 231 |
5 files changed, 0 insertions, 1452 deletions
diff --git a/source_control/bzr b/source_control/bzr deleted file mode 100644 index 996150a3..00000000 --- a/source_control/bzr +++ /dev/null @@ -1,198 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- - -# (c) 2013, André Paramés <git@andreparames.com> -# Based on the Git module by Michael DeHaan <michael.dehaan@gmail.com> -# -# This file is part of Ansible -# -# Ansible is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# Ansible is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with Ansible. If not, see <http://www.gnu.org/licenses/>. - -DOCUMENTATION = u''' ---- -module: bzr -author: André Paramés -version_added: "1.1" -short_description: Deploy software (or files) from bzr branches -description: - - Manage I(bzr) branches to deploy files or software. -options: - name: - required: true - aliases: [ 'parent' ] - description: - - SSH or HTTP protocol address of the parent branch. - dest: - required: true - description: - - Absolute path of where the branch should be cloned to. - version: - required: false - default: "head" - description: - - What version of the branch to clone. This can be the - bzr revno or revid. - force: - required: false - default: "yes" - choices: [ 'yes', 'no' ] - description: - - If C(yes), any modified files in the working - tree will be discarded. - executable: - required: false - default: null - version_added: "1.4" - description: - - Path to bzr executable to use. If not supplied, - the normal mechanism for resolving binary paths will be used. -''' - -EXAMPLES = ''' -# Example bzr checkout from Ansible Playbooks -- bzr: name=bzr+ssh://foosball.example.org/path/to/branch dest=/srv/checkout version=22 -''' - -import re - - -class Bzr(object): - def __init__(self, module, parent, dest, version, bzr_path): - self.module = module - self.parent = parent - self.dest = dest - self.version = version - self.bzr_path = bzr_path - - def _command(self, args_list, cwd=None, **kwargs): - (rc, out, err) = self.module.run_command([self.bzr_path] + args_list, cwd=cwd, **kwargs) - return (rc, out, err) - - def get_version(self): - '''samples the version of the bzr branch''' - - cmd = "%s revno" % self.bzr_path - rc, stdout, stderr = self.module.run_command(cmd, cwd=self.dest) - revno = stdout.strip() - return revno - - def clone(self): - '''makes a new bzr branch if it does not already exist''' - dest_dirname = os.path.dirname(self.dest) - try: - os.makedirs(dest_dirname) - except: - pass - if self.version.lower() != 'head': - args_list = ["branch", "-r", self.version, self.parent, self.dest] - else: - args_list = ["branch", self.parent, self.dest] - return self._command(args_list, check_rc=True, cwd=dest_dirname) - - def has_local_mods(self): - - cmd = "%s status -S" % self.bzr_path - rc, stdout, stderr = self.module.run_command(cmd, cwd=self.dest) - lines = stdout.splitlines() - - lines = filter(lambda c: not re.search('^\\?\\?.*$', c), lines) - return len(lines) > 0 - - def reset(self, force): - ''' - Resets the index and working tree to head. - Discards any changes to tracked files in the working - tree since that commit. - ''' - if not force and self.has_local_mods(): - self.module.fail_json(msg="Local modifications exist in branch (force=no).") - return self._command(["revert"], check_rc=True, cwd=self.dest) - - def fetch(self): - '''updates branch from remote sources''' - if self.version.lower() != 'head': - (rc, out, err) = self._command(["pull", "-r", self.version], cwd=self.dest) - else: - (rc, out, err) = self._command(["pull"], cwd=self.dest) - if rc != 0: - self.module.fail_json(msg="Failed to pull") - return (rc, out, err) - - def switch_version(self): - '''once pulled, switch to a particular revno or revid''' - if self.version.lower() != 'head': - args_list = ["revert", "-r", self.version] - else: - args_list = ["revert"] - return self._command(args_list, check_rc=True, cwd=self.dest) - -# =========================================== - -def main(): - module = AnsibleModule( - argument_spec = dict( - dest=dict(required=True), - name=dict(required=True, aliases=['parent']), - version=dict(default='head'), - force=dict(default='yes', type='bool'), - executable=dict(default=None), - ) - ) - - dest = os.path.abspath(os.path.expanduser(module.params['dest'])) - parent = module.params['name'] - version = module.params['version'] - force = module.params['force'] - bzr_path = module.params['executable'] or module.get_bin_path('bzr', True) - - bzrconfig = os.path.join(dest, '.bzr', 'branch', 'branch.conf') - - rc, out, err, status = (0, None, None, None) - - bzr = Bzr(module, parent, dest, version, bzr_path) - - # if there is no bzr configuration, do a branch operation - # else pull and switch the version - before = None - local_mods = False - if not os.path.exists(bzrconfig): - (rc, out, err) = bzr.clone() - - else: - # else do a pull - local_mods = bzr.has_local_mods() - before = bzr.get_version() - (rc, out, err) = bzr.reset(force) - if rc != 0: - module.fail_json(msg=err) - (rc, out, err) = bzr.fetch() - if rc != 0: - module.fail_json(msg=err) - - # switch to version specified regardless of whether - # we cloned or pulled - (rc, out, err) = bzr.switch_version() - - # determine if we changed anything - after = bzr.get_version() - changed = False - - if before != after or local_mods: - changed = True - - module.exit_json(changed=changed, before=before, after=after) - -# import module snippets -from ansible.module_utils.basic import * -main() diff --git a/source_control/git b/source_control/git deleted file mode 100644 index a5d94e3d..00000000 --- a/source_control/git +++ /dev/null @@ -1,607 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- - -# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com> -# -# This file is part of Ansible -# -# Ansible is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# Ansible is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with Ansible. If not, see <http://www.gnu.org/licenses/>. - -DOCUMENTATION = ''' ---- -module: git -author: Michael DeHaan -version_added: "0.0.1" -short_description: Deploy software (or files) from git checkouts -description: - - Manage I(git) checkouts of repositories to deploy files or software. -options: - repo: - required: true - aliases: [ name ] - description: - - git, SSH, or HTTP protocol address of the git repository. - dest: - required: false - description: - - Absolute path of where the repository should be checked out to. - This parameter is required, unless C(update) is set to C(no) - This change was made in version 1.8. Prior to this version, the - C(dest) parameter was always required. - version: - required: false - default: "HEAD" - description: - - What version of the repository to check out. This can be the - full 40-character I(SHA-1) hash, the literal string C(HEAD), a - branch name, or a tag name. - accept_hostkey: - required: false - default: "no" - choices: [ "yes", "no" ] - version_added: "1.5" - description: - - if C(yes), adds the hostkey for the repo url if not already - added. If ssh_args contains "-o StrictHostKeyChecking=no", - this parameter is ignored. - ssh_opts: - required: false - default: None - version_added: "1.5" - description: - - Creates a wrapper script and exports the path as GIT_SSH - which git then automatically uses to override ssh arguments. - An example value could be "-o StrictHostKeyChecking=no" - key_file: - required: false - default: None - version_added: "1.5" - description: - - Specify an optional private key file to use for the checkout. - reference: - required: false - default: null - version_added: "1.4" - description: - - Reference repository (see "git clone --reference ...") - remote: - required: false - default: "origin" - description: - - Name of the remote. - force: - required: false - default: "yes" - choices: [ "yes", "no" ] - version_added: "0.7" - description: - - If C(yes), any modified files in the working - repository will be discarded. Prior to 0.7, this was always - 'yes' and could not be disabled. - depth: - required: false - default: null - version_added: "1.2" - description: - - Create a shallow clone with a history truncated to the specified - number or revisions. The minimum possible value is C(1), otherwise - ignored. - update: - required: false - default: "yes" - choices: [ "yes", "no" ] - version_added: "1.2" - description: - - If C(no), just returns information about the repository without updating. - executable: - required: false - default: null - version_added: "1.4" - description: - - Path to git executable to use. If not supplied, - the normal mechanism for resolving binary paths will be used. - bare: - required: false - default: "no" - choices: [ "yes", "no" ] - version_added: "1.4" - description: - - if C(yes), repository will be created as a bare repo, otherwise - it will be a standard repo with a workspace. - - recursive: - required: false - default: "yes" - choices: [ "yes", "no" ] - version_added: "1.6" - description: - - if C(no), repository will be cloned without the --recursive - option, skipping sub-modules. -notes: - - "If the task seems to be hanging, first verify remote host is in C(known_hosts). - SSH will prompt user to authorize the first contact with a remote host. To avoid this prompt, - one solution is to add the remote host public key in C(/etc/ssh/ssh_known_hosts) before calling - the git module, with the following command: ssh-keyscan -H remote_host.com >> /etc/ssh/ssh_known_hosts." -''' - -EXAMPLES = ''' -# Example git checkout from Ansible Playbooks -- git: repo=git://foosball.example.org/path/to/repo.git - dest=/srv/checkout - version=release-0.22 - -# Example read-write git checkout from github -- git: repo=ssh://git@github.com/mylogin/hello.git dest=/home/mylogin/hello - -# Example just ensuring the repo checkout exists -- git: repo=git://foosball.example.org/path/to/repo.git dest=/srv/checkout update=no -''' - -import re -import tempfile - -def get_submodule_update_params(module, git_path, cwd): - - #or: git submodule [--quiet] update [--init] [-N|--no-fetch] - #[-f|--force] [--rebase] [--reference <repository>] [--merge] - #[--recursive] [--] [<path>...] - - params = [] - - # run a bad submodule command to get valid params - cmd = "%s submodule update --help" % (git_path) - rc, stdout, stderr = module.run_command(cmd, cwd=cwd) - lines = stderr.split('\n') - update_line = None - for line in lines: - if 'git submodule [--quiet] update ' in line: - update_line = line - if update_line: - update_line = update_line.replace('[','') - update_line = update_line.replace(']','') - update_line = update_line.replace('|',' ') - parts = shlex.split(update_line) - for part in parts: - if part.startswith('--'): - part = part.replace('--', '') - params.append(part) - - return params - -def write_ssh_wrapper(): - module_dir = get_module_path() - try: - # make sure we have full permission to the module_dir, which - # may not be the case if we're sudo'ing to a non-root user - if os.access(module_dir, os.W_OK|os.R_OK|os.X_OK): - fd, wrapper_path = tempfile.mkstemp(prefix=module_dir + '/') - else: - raise OSError - except (IOError, OSError): - fd, wrapper_path = tempfile.mkstemp() - fh = os.fdopen(fd, 'w+b') - template = """#!/bin/sh -if [ -z "$GIT_SSH_OPTS" ]; then - BASEOPTS="" -else - BASEOPTS=$GIT_SSH_OPTS -fi - -if [ -z "$GIT_KEY" ]; then - ssh $BASEOPTS "$@" -else - ssh -i "$GIT_KEY" $BASEOPTS "$@" -fi -""" - fh.write(template) - fh.close() - st = os.stat(wrapper_path) - os.chmod(wrapper_path, st.st_mode | stat.S_IEXEC) - return wrapper_path - -def set_git_ssh(ssh_wrapper, key_file, ssh_opts): - - if os.environ.get("GIT_SSH"): - del os.environ["GIT_SSH"] - os.environ["GIT_SSH"] = ssh_wrapper - - if os.environ.get("GIT_KEY"): - del os.environ["GIT_KEY"] - - if key_file: - os.environ["GIT_KEY"] = key_file - - if os.environ.get("GIT_SSH_OPTS"): - del os.environ["GIT_SSH_OPTS"] - - if ssh_opts: - os.environ["GIT_SSH_OPTS"] = ssh_opts - -def get_version(module, git_path, dest, ref="HEAD"): - ''' samples the version of the git repo ''' - - cmd = "%s rev-parse %s" % (git_path, ref) - rc, stdout, stderr = module.run_command(cmd, cwd=dest) - sha = stdout.rstrip('\n') - return sha - -def clone(git_path, module, repo, dest, remote, depth, version, bare, - reference, recursive): - ''' makes a new git repo if it does not already exist ''' - dest_dirname = os.path.dirname(dest) - try: - os.makedirs(dest_dirname) - except: - pass - cmd = [ git_path, 'clone' ] - if bare: - cmd.append('--bare') - else: - cmd.extend([ '--origin', remote ]) - if recursive: - cmd.extend([ '--recursive' ]) - if is_remote_branch(git_path, module, dest, repo, version) \ - or is_remote_tag(git_path, module, dest, repo, version): - cmd.extend([ '--branch', version ]) - if depth: - cmd.extend([ '--depth', str(depth) ]) - if reference: - cmd.extend([ '--reference', str(reference) ]) - cmd.extend([ repo, dest ]) - module.run_command(cmd, check_rc=True, cwd=dest_dirname) - if bare: - if remote != 'origin': - module.run_command([git_path, 'remote', 'add', remote, repo], check_rc=True, cwd=dest) - -def has_local_mods(module, git_path, dest, bare): - if bare: - return False - - cmd = "%s status -s" % (git_path) - rc, stdout, stderr = module.run_command(cmd, cwd=dest) - lines = stdout.splitlines() - lines = filter(lambda c: not re.search('^\\?\\?.*$', c), lines) - - return len(lines) > 0 - -def reset(git_path, module, dest): - ''' - Resets the index and working tree to HEAD. - Discards any changes to tracked files in working - tree since that commit. - ''' - cmd = "%s reset --hard HEAD" % (git_path,) - return module.run_command(cmd, check_rc=True, cwd=dest) - -def get_remote_head(git_path, module, dest, version, remote, bare): - cloning = False - cwd = None - if remote == module.params['repo']: - cloning = True - else: - cwd = dest - if version == 'HEAD': - if cloning: - # cloning the repo, just get the remote's HEAD version - cmd = '%s ls-remote %s -h HEAD' % (git_path, remote) - else: - head_branch = get_head_branch(git_path, module, dest, remote, bare) - cmd = '%s ls-remote %s -h refs/heads/%s' % (git_path, remote, head_branch) - elif is_remote_branch(git_path, module, dest, remote, version): - cmd = '%s ls-remote %s -h refs/heads/%s' % (git_path, remote, version) - elif is_remote_tag(git_path, module, dest, remote, version): - cmd = '%s ls-remote %s -t refs/tags/%s' % (git_path, remote, version) - else: - # appears to be a sha1. return as-is since it appears - # cannot check for a specific sha1 on remote - return version - (rc, out, err) = module.run_command(cmd, check_rc=True, cwd=cwd) - if len(out) < 1: - module.fail_json(msg="Could not determine remote revision for %s" % version) - rev = out.split()[0] - return rev - -def is_remote_tag(git_path, module, dest, remote, version): - cmd = '%s ls-remote %s -t refs/tags/%s' % (git_path, remote, version) - (rc, out, err) = module.run_command(cmd, check_rc=True, cwd=dest) - if version in out: - return True - else: - return False - -def get_branches(git_path, module, dest): - branches = [] - cmd = '%s branch -a' % (git_path,) - (rc, out, err) = module.run_command(cmd, cwd=dest) - if rc != 0: - module.fail_json(msg="Could not determine branch data - received %s" % out) - for line in out.split('\n'): - branches.append(line.strip()) - return branches - -def get_tags(git_path, module, dest): - tags = [] - cmd = '%s tag' % (git_path,) - (rc, out, err) = module.run_command(cmd, cwd=dest) - if rc != 0: - module.fail_json(msg="Could not determine tag data - received %s" % out) - for line in out.split('\n'): - tags.append(line.strip()) - return tags - -def is_remote_branch(git_path, module, dest, remote, version): - cmd = '%s ls-remote %s -h refs/heads/%s' % (git_path, remote, version) - (rc, out, err) = module.run_command(cmd, check_rc=True, cwd=dest) - if version in out: - return True - else: - return False - -def is_local_branch(git_path, module, dest, branch): - branches = get_branches(git_path, module, dest) - lbranch = '%s' % branch - if lbranch in branches: - return True - elif '* %s' % branch in branches: - return True - else: - return False - -def is_not_a_branch(git_path, module, dest): - branches = get_branches(git_path, module, dest) - for b in branches: - if b.startswith('* ') and 'no branch' in b: - return True - return False - -def get_head_branch(git_path, module, dest, remote, bare=False): - ''' - Determine what branch HEAD is associated with. This is partly - taken from lib/ansible/utils/__init__.py. It finds the correct - path to .git/HEAD and reads from that file the branch that HEAD is - associated with. In the case of a detached HEAD, this will look - up the branch in .git/refs/remotes/<remote>/HEAD. - ''' - if bare: - repo_path = dest - else: - repo_path = os.path.join(dest, '.git') - # Check if the .git is a file. If it is a file, it means that we are in a submodule structure. - if os.path.isfile(repo_path): - try: - gitdir = yaml.safe_load(open(repo_path)).get('gitdir') - # There is a posibility the .git file to have an absolute path. - if os.path.isabs(gitdir): - repo_path = gitdir - else: - repo_path = os.path.join(repo_path.split('.git')[0], gitdir) - except (IOError, AttributeError): - return '' - # Read .git/HEAD for the name of the branch. - # If we're in a detached HEAD state, look up the branch associated with - # the remote HEAD in .git/refs/remotes/<remote>/HEAD - f = open(os.path.join(repo_path, "HEAD")) - if is_not_a_branch(git_path, module, dest): - f.close() - f = open(os.path.join(repo_path, 'refs', 'remotes', remote, 'HEAD')) - branch = f.readline().split('/')[-1].rstrip("\n") - f.close() - return branch - -def fetch(git_path, module, repo, dest, version, remote, bare): - ''' updates repo from remote sources ''' - (rc, out0, err0) = module.run_command([git_path, 'remote', 'set-url', remote, repo], cwd=dest) - if rc != 0: - module.fail_json(msg="Failed to set a new url %s for %s: %s" % (repo, remote, out0 + err0)) - if bare: - (rc, out1, err1) = module.run_command([git_path, 'fetch', remote, '+refs/heads/*:refs/heads/*'], cwd=dest) - else: - (rc, out1, err1) = module.run_command("%s fetch %s" % (git_path, remote), cwd=dest) - if rc != 0: - module.fail_json(msg="Failed to download remote objects and refs") - - if bare: - (rc, out2, err2) = module.run_command([git_path, 'fetch', remote, '+refs/tags/*:refs/tags/*'], cwd=dest) - else: - (rc, out2, err2) = module.run_command("%s fetch --tags %s" % (git_path, remote), cwd=dest) - if rc != 0: - module.fail_json(msg="Failed to download remote objects and refs") - (rc, out3, err3) = submodule_update(git_path, module, dest) - return (rc, out1 + out2 + out3, err1 + err2 + err3) - -def submodule_update(git_path, module, dest): - ''' init and update any submodules ''' - - # get the valid submodule params - params = get_submodule_update_params(module, git_path, dest) - - # skip submodule commands if .gitmodules is not present - if not os.path.exists(os.path.join(dest, '.gitmodules')): - return (0, '', '') - cmd = [ git_path, 'submodule', 'sync' ] - (rc, out, err) = module.run_command(cmd, check_rc=True, cwd=dest) - if 'remote' in params: - cmd = [ git_path, 'submodule', 'update', '--init', '--recursive' ,'--remote' ] - else: - cmd = [ git_path, 'submodule', 'update', '--init', '--recursive' ] - (rc, out, err) = module.run_command(cmd, cwd=dest) - if rc != 0: - module.fail_json(msg="Failed to init/update submodules: %s" % out + err) - return (rc, out, err) - -def switch_version(git_path, module, dest, remote, version, recursive): - ''' once pulled, switch to a particular SHA, tag, or branch ''' - cmd = '' - if version != 'HEAD': - if is_remote_branch(git_path, module, dest, remote, version): - if not is_local_branch(git_path, module, dest, version): - cmd = "%s checkout --track -b %s %s/%s" % (git_path, version, remote, version) - else: - (rc, out, err) = module.run_command("%s checkout --force %s" % (git_path, version), cwd=dest) - if rc != 0: - module.fail_json(msg="Failed to checkout branch %s" % version) - cmd = "%s reset --hard %s/%s" % (git_path, remote, version) - else: - cmd = "%s checkout --force %s" % (git_path, version) - else: - branch = get_head_branch(git_path, module, dest, remote) - (rc, out, err) = module.run_command("%s checkout --force %s" % (git_path, branch), cwd=dest) - if rc != 0: - module.fail_json(msg="Failed to checkout branch %s" % branch) - cmd = "%s reset --hard %s" % (git_path, remote) - (rc, out1, err1) = module.run_command(cmd, cwd=dest) - if rc != 0: - if version != 'HEAD': - module.fail_json(msg="Failed to checkout %s" % (version)) - else: - module.fail_json(msg="Failed to checkout branch %s" % (branch)) - if recursive: - (rc, out2, err2) = submodule_update(git_path, module, dest) - out1 += out2 - err1 += err1 - return (rc, out1, err1) - -# =========================================== - -def main(): - module = AnsibleModule( - argument_spec = dict( - dest=dict(), - repo=dict(required=True, aliases=['name']), - version=dict(default='HEAD'), - remote=dict(default='origin'), - reference=dict(default=None), - force=dict(default='yes', type='bool'), - depth=dict(default=None, type='int'), - update=dict(default='yes', type='bool'), - accept_hostkey=dict(default='no', type='bool'), - key_file=dict(default=None, required=False), - ssh_opts=dict(default=None, required=False), - executable=dict(default=None), - bare=dict(default='no', type='bool'), - recursive=dict(default='yes', type='bool'), - ), - supports_check_mode=True - ) - - dest = module.params['dest'] - repo = module.params['repo'] - version = module.params['version'] - remote = module.params['remote'] - force = module.params['force'] - depth = module.params['depth'] - update = module.params['update'] - bare = module.params['bare'] - reference = module.params['reference'] - git_path = module.params['executable'] or module.get_bin_path('git', True) - key_file = module.params['key_file'] - ssh_opts = module.params['ssh_opts'] - - gitconfig = None - if not dest and update: - module.fail_json(msg="the destination directory must be specified unless update=no") - elif dest: - dest = os.path.abspath(os.path.expanduser(dest)) - if bare: - gitconfig = os.path.join(dest, 'config') - else: - gitconfig = os.path.join(dest, '.git', 'config') - - # create a wrapper script and export - # GIT_SSH=<path> as an environment variable - # for git to use the wrapper script - ssh_wrapper = None - if key_file or ssh_opts: - ssh_wrapper = write_ssh_wrapper() - set_git_ssh(ssh_wrapper, key_file, ssh_opts) - module.add_cleanup_file(path=ssh_wrapper) - - # add the git repo's hostkey - if module.params['ssh_opts'] is not None: - if not "-o StrictHostKeyChecking=no" in module.params['ssh_opts']: - add_git_host_key(module, repo, accept_hostkey=module.params['accept_hostkey']) - else: - add_git_host_key(module, repo, accept_hostkey=module.params['accept_hostkey']) - - recursive = module.params['recursive'] - - rc, out, err, status = (0, None, None, None) - - before = None - local_mods = False - if gitconfig and not os.path.exists(gitconfig) or not gitconfig and not update: - # if there is no git configuration, do a clone operation unless the - # user requested no updates or we're doing a check mode test (in - # which case we do a ls-remote), otherwise clone the repo - if module.check_mode or not update: - remote_head = get_remote_head(git_path, module, dest, version, repo, bare) - module.exit_json(changed=True, before=before, after=remote_head) - # there's no git config, so clone - clone(git_path, module, repo, dest, remote, depth, version, bare, reference, recursive) - elif not update: - # Just return having found a repo already in the dest path - # this does no checking that the repo is the actual repo - # requested. - before = get_version(module, git_path, dest) - module.exit_json(changed=False, before=before, after=before) - else: - # else do a pull - local_mods = has_local_mods(module, git_path, dest, bare) - before = get_version(module, git_path, dest) - if local_mods: - # failure should happen regardless of check mode - if not force: - module.fail_json(msg="Local modifications exist in repository (force=no).") - # if force and in non-check mode, do a reset - if not module.check_mode: - reset(git_path, module, dest) - # exit if already at desired sha version - remote_head = get_remote_head(git_path, module, dest, version, remote, bare) - if before == remote_head: - if local_mods: - module.exit_json(changed=True, before=before, after=remote_head, - msg="Local modifications exist") - elif is_remote_tag(git_path, module, dest, repo, version): - # if the remote is a tag and we have the tag locally, exit early - if version in get_tags(git_path, module, dest): - module.exit_json(changed=False, before=before, after=remote_head) - else: - module.exit_json(changed=False, before=before, after=remote_head) - if module.check_mode: - module.exit_json(changed=True, before=before, after=remote_head) - fetch(git_path, module, repo, dest, version, remote, bare) - - # switch to version specified regardless of whether - # we cloned or pulled - if not bare: - switch_version(git_path, module, dest, remote, version, recursive) - - # determine if we changed anything - after = get_version(module, git_path, dest) - changed = False - - if before != after or local_mods: - changed = True - - # cleanup the wrapper script - if ssh_wrapper: - os.remove(ssh_wrapper) - - module.exit_json(changed=changed, before=before, after=after) - -# import module snippets -from ansible.module_utils.basic import * -from ansible.module_utils.known_hosts import * - -main() diff --git a/source_control/github_hooks b/source_control/github_hooks deleted file mode 100644 index 6a8d1ced..00000000 --- a/source_control/github_hooks +++ /dev/null @@ -1,178 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- - -# (c) 2013, Phillip Gentry <phillip@cx.com> -# -# This file is part of Ansible -# -# Ansible is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. - -# Ansible is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with Ansible. If not, see <http://www.gnu.org/licenses/>. - -import json -import base64 - -DOCUMENTATION = ''' ---- -module: github_hooks -short_description: Manages github service hooks. -description: - - Adds service hooks and removes service hooks that have an error status. -version_added: "1.4" -options: - user: - description: - - Github username. - required: true - oauthkey: - description: - - The oauth key provided by github. It can be found/generated on github under "Edit Your Profile" >> "Applications" >> "Personal Access Tokens" - required: true - repo: - description: - - "This is the API url for the repository you want to manage hooks for. It should be in the form of: https://api.github.com/repos/user:/repo:. Note this is different than the normal repo url." - required: true - hookurl: - description: - - When creating a new hook, this is the url that you want github to post to. It is only required when creating a new hook. - required: false - action: - description: - - This tells the githooks module what you want it to do. - required: true - choices: [ "create", "cleanall" ] - validate_certs: - description: - - If C(no), SSL certificates for the target repo will not be validated. This should only be used - on personally controlled sites using self-signed certificates. - required: false - default: 'yes' - choices: ['yes', 'no'] - -author: Phillip Gentry, CX Inc -''' - -EXAMPLES = ''' -# Example creating a new service hook. It ignores duplicates. -- github_hooks: action=create hookurl=http://11.111.111.111:2222 user={{ gituser }} oauthkey={{ oauthkey }} repo=https://api.github.com/repos/pcgentry/Github-Auto-Deploy - -# Cleaning all hooks for this repo that had an error on the last update. Since this works for all hooks in a repo it is probably best that this would be called from a handler. -- local_action: github_hooks action=cleanall user={{ gituser }} oauthkey={{ oauthkey }} repo={{ repo }} -''' - -def list(module, hookurl, oauthkey, repo, user): - url = "%s/hooks" % repo - auth = base64.encodestring('%s:%s' % (user, oauthkey)).replace('\n', '') - headers = { - 'Authorization': 'Basic %s' % auth, - } - response, info = fetch_url(module, url, headers=headers) - if info['status'] != 200: - return False, '' - else: - return False, response.read() - -def clean504(module, hookurl, oauthkey, repo, user): - current_hooks = list(hookurl, oauthkey, repo, user)[1] - decoded = json.loads(current_hooks) - - for hook in decoded: - if hook['last_response']['code'] == 504: - # print "Last response was an ERROR for hook:" - # print hook['id'] - delete(module, hookurl, oauthkey, repo, user, hook['id']) - - return 0, current_hooks - -def cleanall(module, hookurl, oauthkey, repo, user): - current_hooks = list(hookurl, oauthkey, repo, user)[1] - decoded = json.loads(current_hooks) - - for hook in decoded: - if hook['last_response']['code'] != 200: - # print "Last response was an ERROR for hook:" - # print hook['id'] - delete(module, hookurl, oauthkey, repo, user, hook['id']) - - return 0, current_hooks - -def create(module, hookurl, oauthkey, repo, user): - url = "%s/hooks" % repo - values = { - "active": True, - "name": "web", - "config": { - "url": "%s" % hookurl, - "content_type": "json" - } - } - data = json.dumps(values) - auth = base64.encodestring('%s:%s' % (user, oauthkey)).replace('\n', '') - headers = { - 'Authorization': 'Basic %s' % auth, - } - response, info = fetch_url(module, url, data=data, headers=headers) - if info['status'] != 200: - return 0, '[]' - else: - return 0, response.read() - -def delete(module, hookurl, oauthkey, repo, user, hookid): - url = "%s/hooks/%s" % (repo, hookid) - auth = base64.encodestring('%s:%s' % (user, oauthkey)).replace('\n', '') - headers = { - 'Authorization': 'Basic %s' % auth, - } - response, info = fetch_url(module, url, data=data, headers=headers, method='DELETE') - return response.read() - -def main(): - module = AnsibleModule( - argument_spec=dict( - action=dict(required=True), - hookurl=dict(required=False), - oauthkey=dict(required=True), - repo=dict(required=True), - user=dict(required=True), - validate_certs=dict(default='yes', type='bool'), - ) - ) - - action = module.params['action'] - hookurl = module.params['hookurl'] - oauthkey = module.params['oauthkey'] - repo = module.params['repo'] - user = module.params['user'] - - if action == "list": - (rc, out) = list(module, hookurl, oauthkey, repo, user) - - if action == "clean504": - (rc, out) = clean504(module, hookurl, oauthkey, repo, user) - - if action == "cleanall": - (rc, out) = cleanall(module, hookurl, oauthkey, repo, user) - - if action == "create": - (rc, out) = create(module, hookurl, oauthkey, repo, user) - - if rc != 0: - module.fail_json(msg="failed", result=out) - - module.exit_json(msg="success", result=out) - - -# import module snippets -from ansible.module_utils.basic import * -from ansible.module_utils.urls import * - -main() diff --git a/source_control/hg b/source_control/hg deleted file mode 100644 index 1b95bcd5..00000000 --- a/source_control/hg +++ /dev/null @@ -1,238 +0,0 @@ -#!/usr/bin/python -#-*- coding: utf-8 -*- - -# (c) 2013, Yeukhon Wong <yeukhon@acm.org> -# -# This module was originally inspired by Brad Olson's ansible-module-mercurial -# <https://github.com/bradobro/ansible-module-mercurial>. This module tends -# to follow the git module implementation. -# -# This file is part of Ansible -# -# Ansible is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# Ansible is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with Ansible. If not, see <http://www.gnu.org/licenses/>. - -import ConfigParser - -DOCUMENTATION = ''' ---- -module: hg -short_description: Manages Mercurial (hg) repositories. -description: - - Manages Mercurial (hg) repositories. Supports SSH, HTTP/S and local address. -version_added: "1.0" -author: Yeukhon Wong -options: - repo: - description: - - The repository address. - required: true - default: null - aliases: [ name ] - dest: - description: - - Absolute path of where the repository should be cloned to. - required: true - default: null - revision: - description: - - Equivalent C(-r) option in hg command which could be the changeset, revision number, - branch name or even tag. - required: false - default: "default" - aliases: [ version ] - force: - description: - - Discards uncommitted changes. Runs C(hg update -C). - required: false - default: "yes" - choices: [ "yes", "no" ] - purge: - description: - - Deletes untracked files. Runs C(hg purge). - required: false - default: "no" - choices: [ "yes", "no" ] - executable: - required: false - default: null - version_added: "1.4" - description: - - Path to hg executable to use. If not supplied, - the normal mechanism for resolving binary paths will be used. -notes: - - "If the task seems to be hanging, first verify remote host is in C(known_hosts). - SSH will prompt user to authorize the first contact with a remote host. To avoid this prompt, - one solution is to add the remote host public key in C(/etc/ssh/ssh_known_hosts) before calling - the hg module, with the following command: ssh-keyscan remote_host.com >> /etc/ssh/ssh_known_hosts." -requirements: [ ] -''' - -EXAMPLES = ''' -# Ensure the current working copy is inside the stable branch and deletes untracked files if any. -- hg: repo=https://bitbucket.org/user/repo1 dest=/home/user/repo1 revision=stable purge=yes -''' - -class Hg(object): - - def __init__(self, module, dest, repo, revision, hg_path): - self.module = module - self.dest = dest - self.repo = repo - self.revision = revision - self.hg_path = hg_path - - def _command(self, args_list): - (rc, out, err) = self.module.run_command([self.hg_path] + args_list) - return (rc, out, err) - - def _list_untracked(self): - args = ['purge', '--config', 'extensions.purge=', '-R', self.dest, '--print'] - return self._command(args) - - def get_revision(self): - """ - hg id -b -i -t returns a string in the format: - "<changeset>[+] <branch_name> <tag>" - This format lists the state of the current working copy, - and indicates whether there are uncommitted changes by the - plus sign. Otherwise, the sign is omitted. - - Read the full description via hg id --help - """ - (rc, out, err) = self._command(['id', '-b', '-i', '-t', '-R', self.dest]) - if rc != 0: - self.module.fail_json(msg=err) - else: - return out.strip('\n') - - def has_local_mods(self): - now = self.get_revision() - if '+' in now: - return True - else: - return False - - def discard(self): - before = self.has_local_mods() - if not before: - return False - - (rc, out, err) = self._command(['update', '-C', '-R', self.dest]) - if rc != 0: - self.module.fail_json(msg=err) - - after = self.has_local_mods() - if before != after and not after: # no more local modification - return True - - def purge(self): - # before purge, find out if there are any untracked files - (rc1, out1, err1) = self._list_untracked() - if rc1 != 0: - self.module.fail_json(msg=err1) - - # there are some untrackd files - if out1 != '': - args = ['purge', '--config', 'extensions.purge=', '-R', self.dest] - (rc2, out2, err2) = self._command(args) - if rc2 != 0: - self.module.fail_json(msg=err2) - return True - else: - return False - - def cleanup(self, force, purge): - discarded = False - purged = False - - if force: - discarded = self.discard() - if purge: - purged = self.purge() - if discarded or purged: - return True - else: - return False - - def pull(self): - return self._command( - ['pull', '-R', self.dest, self.repo]) - - def update(self): - return self._command(['update', '-R', self.dest]) - - def clone(self): - return self._command(['clone', self.repo, self.dest, '-r', self.revision]) - - def switch_version(self): - return self._command(['update', '-r', self.revision, '-R', self.dest]) - -# =========================================== - -def main(): - module = AnsibleModule( - argument_spec = dict( - repo = dict(required=True, aliases=['name']), - dest = dict(required=True), - revision = dict(default="default", aliases=['version']), - force = dict(default='yes', type='bool'), - purge = dict(default='no', type='bool'), - executable = dict(default=None), - ), - ) - repo = module.params['repo'] - dest = os.path.expanduser(module.params['dest']) - revision = module.params['revision'] - force = module.params['force'] - purge = module.params['purge'] - hg_path = module.params['executable'] or module.get_bin_path('hg', True) - hgrc = os.path.join(dest, '.hg/hgrc') - - # initial states - before = '' - changed = False - cleaned = False - - hg = Hg(module, dest, repo, revision, hg_path) - - # If there is no hgrc file, then assume repo is absent - # and perform clone. Otherwise, perform pull and update. - if not os.path.exists(hgrc): - (rc, out, err) = hg.clone() - if rc != 0: - module.fail_json(msg=err) - else: - # get the current state before doing pulling - before = hg.get_revision() - - # can perform force and purge - cleaned = hg.cleanup(force, purge) - - (rc, out, err) = hg.pull() - if rc != 0: - module.fail_json(msg=err) - - (rc, out, err) = hg.update() - if rc != 0: - module.fail_json(msg=err) - - hg.switch_version() - after = hg.get_revision() - if before != after or cleaned: - changed = True - module.exit_json(before=before, after=after, changed=changed, cleaned=cleaned) - -# import module snippets -from ansible.module_utils.basic import * -main() diff --git a/source_control/subversion b/source_control/subversion deleted file mode 100644 index 6709a8c3..00000000 --- a/source_control/subversion +++ /dev/null @@ -1,231 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- - -# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com> -# -# This file is part of Ansible -# -# Ansible is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# Ansible is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with Ansible. If not, see <http://www.gnu.org/licenses/>. - -DOCUMENTATION = ''' ---- -module: subversion -short_description: Deploys a subversion repository. -description: - - Deploy given repository URL / revision to dest. If dest exists, update to the specified revision, otherwise perform a checkout. -version_added: "0.7" -author: Dane Summers, njharman@gmail.com -notes: - - Requires I(svn) to be installed on the client. -requirements: [] -options: - repo: - description: - - The subversion URL to the repository. - required: true - aliases: [ name, repository ] - default: null - dest: - description: - - Absolute path where the repository should be deployed. - required: true - default: null - revision: - description: - - Specific revision to checkout. - required: false - default: HEAD - aliases: [ version ] - force: - description: - - If C(yes), modified files will be discarded. If C(no), module will fail if it encounters modified files. - required: false - default: "yes" - choices: [ "yes", "no" ] - username: - description: - - --username parameter passed to svn. - required: false - default: null - password: - description: - - --password parameter passed to svn. - required: false - default: null - executable: - required: false - default: null - version_added: "1.4" - description: - - Path to svn executable to use. If not supplied, - the normal mechanism for resolving binary paths will be used. - export: - required: false - default: "no" - choices: [ "yes", "no" ] - version_added: "1.6" - description: - - If C(yes), do export instead of checkout/update. -''' - -EXAMPLES = ''' -# Checkout subversion repository to specified folder. -- subversion: repo=svn+ssh://an.example.org/path/to/repo dest=/src/checkout - -# Export subversion directory to folder -- subversion: repo=svn+ssh://an.example.org/path/to/repo dest=/src/export export=True -''' - -import re -import tempfile - - -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 - - 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() - - 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''' - self._exec(["export", "-r", self.revision, self.repo, self.dest]) - - 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 - - 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 - - -# =========================================== - -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='yes', 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 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() - 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, )) - - 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() |