ansible - 使用 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 实例?
解决方案
“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 }}
推荐阅读
- amazon-s3 - 如何在 AWS Glue 脚本中将数据写入 S3 时添加不在动态框架中的分区
- machine-learning - 我可以从 lightgbm 或 xgboost 模型中采样或选择单个树吗?
- reactjs - 如何获取 ORDER 和 OrderItems 的值
- swift - AVAsset.LoadValuesAsynchronously 0 轨道在完成处理程序与 m3u8 URL
- java - 如何添加 O(N) 和 O(M)?
- django - geopy 返回“Civitas Vaticana”字符串而不是 django 中的实际城市名称
- javascript - 如何通过重定向更改选定的选项卡
- vue.js - 如何在 vuetify 卡中使画布响应
- c - 是否可以使用 tee 捕获标准输入?
- javascript - 如何在Angular 11中路由到PDF文件