Skip to content

Instantly share code, notes, and snippets.

@qrtt1
Created October 18, 2016 17:36
Show Gist options
  • Save qrtt1/292235fcef43908349258a341520de1f to your computer and use it in GitHub Desktop.
Save qrtt1/292235fcef43908349258a341520de1f to your computer and use it in GitHub Desktop.
ansible module for versioning_copy
#!/usr/bin/python
DOCUMENTATION = '''
---
module: versioning_copy
short_description: Copies the file with datetime versioning name
description:
- The versioning_copy module copies a file on remote locations. It designed for the tomcat's parallel deploy feature
options:
war:
description:
- the source path of war
required: true
webapps:
description:
- the directory for the webapps of tomcat
required: true
context:
description:
- the target context name
required: true
'''
EXAMPLES = '''
# copy the foo.war into the "/var/tomcat/webapps" directory and renaming to bar.war with the datetime version. For example: bar##20160807235959.war
- versioning_copy: war="foo.war" webapps="/var/tomcat/webapps" context="bar"
'''
from ansible.module_utils.basic import *
def main():
fields = {
"war" : {"required": True, "type": "str"},
"webapps" : {"required": True, "type": "str"},
"context" : {"required": True, "type": "str"}
}
module = AnsibleModule(argument_spec=fields)
import os, os.path
from datetime import datetime
war = module.params['war'].strip()
version = datetime.today().strftime("%Y%m%d%H%M%S")
webapps = os.path.abspath(module.params['webapps'])
prefix = "{}##".format(module.params['context'])
# the context deployed perviously
def to_version(x):
try:
return int(x.split("##")[1].replace(".war", ""))
except:
return -1
olders = [ x for x in os.listdir(webapps) if x.startswith(prefix) and x.endswith(".war") ]
olders = sorted(olders, key=to_version, reverse=True)
deploy_path = os.path.join(webapps, "{}{}.war".format(prefix, version))
import shutil
shutil.copy2(war, deploy_path)
if len(olders) > 1:
removed = []
for c in olders[1:]:
p = os.path.join(webapps, c)
try:
os.unlink(p)
removed.append(p)
except:
pass
module.exit_json(changed=False, output={"deploy": deploy_path, "olders": olders, "removed": removed})
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment