如何通过ansible通信两台远程机器 [英] How communicate two remote machine through ansible
问题描述
我正在从系统 1 运行 ansible playbook,它在系统 2 上运行任务以进行备份,然后,我想将备份文件从系统 2 复制到系统 3.
I am running ansible playbook from system 1 which runs tasks on system 2 to take backup and after that, I want to copy backup file from system 2 to system 3.
我正在执行此任务以自动执行以下命令其中系统 2 上的/bck1/test 和系统 3 上的 opt/backup
I am doing this task for automating below command where /bck1/test on system 2 and opt/backup on system 3
rsync -r -v -e ssh /bck1/test.* root@host3:/opt/backup
推荐答案
您可以使用 shell
模块运行原始 rsync 命令.
You can run the raw rsync command with the shell
module.
tasks:
- shell: rsync -r -v -e ssh /bck1/test.* root@host3:/opt/backup
为此,您需要将私有 ssh 密钥部署到系统 2,或者最好启用 ssh 代理转发,例如在您的 .ssh/config
中:
For this to work, you will either need to have your private ssh key deployed to system 2, or, preferable enable ssh agent forwarding, for example in your .ssh/config
:
Host host2
ForwardAgent yes
另外,系统 2 上的 sshd 需要接受代理转发.以下是我用来执行此操作的一些任务:
Additionally sshd on system 2 would need to accept agent forwarding. Here are some tasks which I use to do this:
- name: Ensure sshd allows agent forwarding
lineinfile: dest=/etc/ssh/sshd_config
regexp=^#?AllowAgentForwarding
line="AllowAgentForwarding yes"
follow=yes
backup=yes
sudo: yes
register: changed_sshd_config
- name: "Debian: Restart sshd"
shell: invoke-rc.d ssh restart
sudo: yes
when:
- ansible_distribution in [ "Debian", "Ubuntu" ]
- changed_sshd_config | changed
- name: "CentOS 7: Restart sshd"
shell: systemctl restart sshd.service
sudo: yes
when:
- ansible_distribution == "CentOS"
- ansible_distribution_major_version == "7"
- changed_sshd_config | changed
在 Debian 和 CentOS7 上重启 sshd 有两个独立的任务.选择您需要的内容,或者您可能必须使其适应您的系统.
There are two separate tasks for restarting sshd on Debian and CentOS7. Pick what you need or maybe you have to adapt that to your system.
您可能需要在单独的剧本中进行配置.因为 Ansible 将保持与主机的开放 ssh 连接,并且在激活代理转发后,您很可能需要重新连接.
You might need to configure this in a separate playbook. Because Ansible will keep an open ssh connection to the host and after activating agent forwarding you most probably will need to re-connect.
PS:允许 root 用户通过 ssh 登录并不是最好的主意,但那是另一个话题.:)
PS: It's not the best idea to allow ssh login for user root, but that is another topic. :)
这篇关于如何通过ansible通信两台远程机器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!