使用Ansible将文件从远程主机复制到流浪实例

时间:2018-06-20 22:58:07

标签: ansible vagrant rsync

之前曾问过类似的问题,但没有人回答或针对流浪汉。

我在主机master上有一个目录,我想与我的无所事事实例同步。这是我的剧本:

- hosts: master
  vars:
    backup_dir: /var/backups/projects/civi.common.scot/backups/latest/
    dest_dir: /var/import
  tasks:
    - name: Synchronize directories
      synchronize:
        src: "{{ backup_dir }}"
        dest: "{{ dest_dir }}"
        mode: pull
      delegate_to: default

这是我的库存:

default ansible_host=192.168.121.199 ansible_port=22  ansible_user='vagrant' ansible_ssh_private_key_file='/run/media/daniel/RAIDStore/Workspace/docker/newhume/.vagrant/machines/default/libvirt/private_key'
master ansible_host=hume.common.scot

运行此剧本时,该过程似乎未将任何文件复制到磁盘,但也没有错误或退出。

ssh.config.forward_agent = true中有Vagrantfile的情况下,我可以从无业游民的访客中发出以下命令:

rsync --rsync-path='sudo rsync' -avz -e ssh $remote_user@$remote_host:$remote_path $local_path`

但是,以下剧本不能正常工作(与使用synchronize模块时出现的问题相同):

- name: synchronize directories (bugfix for above)
  command: "rsync --rsync-path='sudo rsync' -avz -e ssh {{ remote_user }}@{{ remote_host }}:{{ backup_directory }} {{ dest_dir }}"

我还尝试使用shell代替command

如何将这些文件复制到流浪实例中?

1 个答案:

答案 0 :(得分:0)

“ syschronize” Ansible模块“正在运行,并且起源于正在运行Ansible的本地主机”(引自联机帮助页)。因此它是从 local remote 的复制。您要执行的操作是将远程A (母版)复制到远程B (默认)。 为了实现这一点,您必须将特定用户的ssh密钥从B交换到A,反之亦然,以交换known_hosts。以下内容将指导您完成该过程:

- hosts: default
  tasks:
    # transfer local pub-key to remote authorized_keys
    - name: fetch local ssh key from root user
      shell: cat /root/.ssh/id_rsa.pub
      register: ssh_keys
      changed_when: false
    - name: deploy ssh key to remote server
      authorized_key:
              user: "root"
              key: "{{ item }}"
      delegate_to: "master"
      with_items:
              - "{{ ssh_keys.stdout }}"

    # fetch remote host key and add to local known_hosts
    # to omit key accept prompt
    - name: fetch ssh rsa host key from remote server
      shell: cat /etc/ssh/ssh_host_rsa_key.pub
      register: ssh_host_rsa_key
      delegate_to: master
      changed_when: false
    - name: create /root/.ssh/ if not existant
      file:
          path: "/root/.ssh/"
          owner: root
          group: root
          mode: 0700
          state: directory
    - name: add hostkey to root known host file
      lineinfile:
          path: "/root/.ssh/known_hosts"
          line: "{{ master.fqdn }} {{ ssh_host_rsa_key.stdout }}"
          mode: 0600
          create: yes
          state: present
      with_items:
          - "{{ ssh_keys.stdout }}"

    # now call rsync to fetch from master
    - name: fetch from remote
      shell: rsync --rsync-path='sudo rsync' -avz -e ssh root@{{ master.fqdn }}:{{ backup_directory }} {{ dest_dir }}