Skip to content

Instantly share code, notes, and snippets.

@aseigneurin
Last active January 5, 2024 19:06
Show Gist options
  • Save aseigneurin/4902819f17218340d11f to your computer and use it in GitHub Desktop.
Save aseigneurin/4902819f17218340d11f to your computer and use it in GitHub Desktop.
Ansible module to copy a file if the MD5 sum of the target is different
#!/usr/bin/python
DOCUMENTATION = '''
---
module: copy_remotely
short_description: Copies a file from the remote server to the remote server.
description:
- Copies a file but, unlike the M(file) module, the copy is performed on the
remote server.
The copy is only performed if the source and destination files are different
(different MD5 sums) or if the destination file does not exist.
The destination directory is created if missing.
version_added: ""
options:
src:
description:
- Path to the file to copy.
required: true
default: null
dest:
description:
- Path to the destination file.
required: true
default: null
'''
EXAMPLES = '''
- copy_remotely: src=/tmp/foo.conf dest=/etc/foo.conf
'''
import shutil
def main():
module = AnsibleModule(
argument_spec = dict(
src = dict(required=True),
dest = dict(required=True),
)
)
src = module.params['src']
dest = module.params['dest']
if not os.path.exists(src):
module.fail_json(msg="Source file not found: %s" % src)
src_md5 = module.md5(src)
dest_md5 = module.md5(dest)
changed = False
# create the target directory if missing
dest_dir = os.path.dirname(dest)
if not os.path.isdir(dest_dir):
os.makedirs(dest_dir)
changed = True
# copy the file if newer
if src_md5 != dest_md5:
shutil.copyfile(src, dest)
changed = True
module.exit_json(changed=changed, src_md5=src_md5, dest_md5=dest_md5)
from ansible.module_utils.basic import *
main()
@16hands
Copy link

16hands commented Apr 10, 2016

Ansible will use the 'library' directory relative to you playbooks, so if you save this in /library/copy_remotely and set it executable by the user you run Ansible as it should be found. Lorien's fabulous book explains this well: http://www.ansiblebook.com

@shaikabdulm
Copy link

shaikabdulm commented Oct 17, 2019

When I try to run the playbook with the above module got below error:
FAILED! => {"changed": false, "msg": "Source file not found: /ansible/awx/ntp/ntp.conf"}
Source server is ansible server and file exists at the path /ansible/awx/ntp/ntp.conf and destination is a different server.
could you tell what am I doing wrong?
playbook:
tasks:

  • copy_remotely:
    src: /ansible/awx/ntp/ntp.conf
    dest: /etc/ntp.conf

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment