74次阅读
没有评论

*
docker: fatal: [test]: FAILED! => {“msg”: “failed to transfer file to /home/user/.ansible/tmp/ansible-local-123331or28t2a/tmp6st_fxv1 ~user/.ansible/tmp/ansible-tmp-1579990845.0734024-189911264147319/AnsiballZ_setup.py:\n\n\n”}


为什么会出现这种情况?为什么Ansible无法将文件复制到目标主机?

## 解决方案

### 使用 `docker` 连接模式
首先,根据你提供的信息,问题可能与 Ansible 与 Docker 容器的连接方式有关。确保你的目标主机可以与 Ansible 控制节点正常通信,以及是否存在权限问题。

以下是一个简单的示例,演示如何在 Docker 容器中成功运行 Ansible playbook。

1. 首先,确保你的目标 Docker 容器正在运行,例如使用 `php:7.0-apache` 镜像:

```bash
docker run -d --rm --name target_container php:7.0-apache
  1. 创建 Ansible playbook 文件,例如 playbook.yml
---
- hosts: target_container
  gather_facts: false
  tasks:
    - name: Ensure python is installed (temporary solution)
      raw: apt-get update && apt-get install -y python3
    - name: Copy files to the target
      copy:
        src: files/{{ item }}
        dest: /my/folder/
      with_items:
        - file.txt
  1. 执行 Ansible playbook:
ansible-playbook -i target_container, playbook.yml

这里使用 -i target_container, 指定目标主机为 target_container,逗号表示不使用 inventory 文件,直接指定主机名。

使用 become 设置权限

如果在复制文件时出现权限问题,可以尝试使用 become 来切换到 root 权限。以下是修改后的 Ansible playbook 示例:

---
- hosts: target_container
  become: true
  become_method: sudo
  tasks:
    - name: Ensure python is installed (temporary solution)
      raw: apt-get update && apt-get install -y python3
    - name: Copy files to the target
      copy:
        src: files/{{ item }}
        dest: /my/folder/
      with_items:
        - file.txt

这样,Ansible 将以 sudo 权限运行任务,确保在复制文件时具有足够的权限。

注意事项

  1. 在 Ansible 控制节点和目标容器之间,确保网络连接正常且没有防火墙或其他访问限制。
  2. 如果使用 become 切换到 root 权限,确保目标容器的 sudo 配置允许无密码使用 sudo。

请注意,以上解决方案可能需要根据你的实际情况进行适当调整。

注意:在实际操作中,请确保备份重要数据,并根据需要适当测试解决方案,以避免数据丢失或系统故障。

总结

通过逐步设置 Ansible playbook,确保目标容器正确运行,并使用适当的权限设置,你应该能够成功将文件复制到目标主机。在执行过程中,如果遇到任何错误,请根据错误信息进行适当的调整和排查。

正文完