首页 > 解决方案 > 使用 ansible 将文件从远程主机复制到 vagrant 实例

问题描述

之前也有人问过类似的问题,但没有一个问题得到回答,也没有一个是 Vagrant 特有的。

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

- 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,我可以从 Vagrant 来宾发出以下命令:

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.

如何将这些文件复制到我的 vagrant 实例?

标签: ansiblevagrantrsync

解决方案


“syschronize” Ansible 模块“在运行 Ansible 的本地主机上运行并源自”(来自手册页的引用)。所以它是从本地复制到远程的。您想要做的是从远程 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 }}

推荐阅读