简体   繁体   中英

ansible synchronize via ssh if inventory_hostname is different

I like to use the synchronize module in Ansible to synchronize files from one server to some other servers via SSH

    - name: Copy files to all servers
      synchronize:
        src: /source/path/
        dest: "rsync://{{ ansible_nodename }}:/destination/path/"
      delegate_to: src-host

So by default this module would use the inventory_name, but from the src-host the hostname is a different one. Only way I found so far was to use rsync://{{ ansible_nodename }} , but then it seems this is not happening via SSH anymore and I get a No route to host (113)\\nrsync error: error in socket IO (code 10) at clientserver.c(128) [sender=3.1.0]

I tried also to overwrite inventory_hostname just for this one task, with no luck so far.

So for example I imagine something like this

    - name: Copy custom config to all servers
      synchronize:
        src: /opt/app/dir/
        dest: /opt/app/dir/
      delegate_to: src-host
      vars:
        inventory_hostname: "{{ ansible_nodename }}"

But of course it fails when manipulating the inventory_hostname with following message

An exception occurred during task execution. To see the full traceback, use -vvv. The error was: jinja2.exceptions.UndefinedError: "hostvars['{{ ansible_nodename }}']" is undefined
fatal: [my-host]: FAILED! => {"msg": "Unexpected failure during module execution.", "stdout": ""}

If you want to template target string based on some hostname, you can use:

If you want to copy something

  • from serverA
  • to serverB
  • using serverB's interface eth4 address, it should be like this:
 - name: Copy custom config from serverA serverB over
   synchronize:
     src: "/path/to/source/on/serverA/machine"
     dest: "rsync://{{ hostvars[serverB]['ansible_facts']['ansible_eth0']['ipv4']['address'] }} }}/path/where/to/put/files/on/serverB/machines"
   delegate_to: serverA

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM