如何使用 Ansible 管理远程 lxc 容器?

如何使用 Ansible 管理远程 lxc 容器?

如何使用 Ansible 在远程服务器上的 lxc 容器上执行任务?

我们使用 Ansible 在多台服务器(物理机和虚拟机)上部署我们的代码。

到目前为止,每个实例都有一个公共 IP 地址和一个正在运行的 ssh 服务器,因此一切都运行正常。但最近,我们必须在远程服务器上部署两个 lxc 容器。

这两个容器是经过 natted 的,没有运行 ssh 服务器(我们希望保持这种状态)。我只能使用 ssh 连接到物理主机,然后通过 lxc 附加到它们。

我发现的唯一方法是从未针对最新的 Ansible 2.0 版本进行更新的自定义插件。 我也到达邮件列表但至今尚无结果。

有人曾经在这样的配置下成功使用过 Ansible 吗?

答案1

尝试ansible-lxc-sshPierre Chifflier 的连接插件,适用于 Ansible 2.x。我将插件放在 ansible.cfg 中定义的默认位置 /usr/share/ansible_plugins/connection_plugins/

在清单主机文件 /etc/ansible/hosts 中,我输入了以下内容

[containers]
container_01 ansible_host=lxc_server ansible_connection=lxc_ssh ansible_ssh_extra_args=container_01

请注意,您必须将容器名称作为 ssh 额外参数传递。务必将 lxc_server 替换为您的 lxc 主机的名称。

答案2

好吧,由于我找不到解决方案,我最终在每个 lxc 容器上运行一个 ssh 服务器。

这是我的.ssh/config示例:

Host main_server
    HostName server_address
    User root
    Port 2022
    ForwardAgent yes

Host lxc_container
    User root
    Port 22
    ProxyCommand ssh main_server nc lxc_container 22
    ForwardAgent yes

答案3

我发现了一种简单的方法,不需要插件或配置 ssh。感觉有点笨拙,但在我的测试中效果很好。只需更改变量即可ansible_python_interpreter在 lxc 容器内运行所有内容。将name_of_lxc_container下面的 更改为您的容器名称。

<<< tasks to run on the remote host >>>

- name: BEGIN lxc exec ...
  set_fact:
    ansible_python_interpreter: lxc exec name_of_lxc_container -- /usr/bin/python3

<<< tasks to run in the lxc container >>>

- name: END lxc exec ...
  set_fact:
    ansible_python_interpreter: /usr/bin/python3

<<< more tasks to run on the remote host >>>

更新:从控制器复制到远程时,此技巧不适用于copyunarchive模块。相反,在 BEGIN .. END 块之外,使用 Ansible ,copy然后。/tmplxc file push ...

相关内容