Skip to main content
 首页 » 编程设计

python之使用 ansible 配置 docker 容器

2024年09月03日30zhenyulu

我正在尝试使用我现有的 docker playbook 来配置一个使用 ubuntu 18.04 的 docker 容器进行本地开发。

我在容器上运行 playbook 时遇到问题,因为它没有安装 python,所以根据我的理解,ansible 无法运行。

有没有办法在容器上安装 python 以便我的 playbook 可以运行?

注意我知道 ansible-container 存在,但我想使用我现有的使用 become_user 的剧本,但它并不像 build instructions 中所述那样工作

请您参考如下方法:

您需要先将您的 Docker 容器添加到 ansible list 中,然后才能将其定位到您的 playbook 中。这样的事情会起作用:

--- 
- hosts: localhost 
  gather_facts: false 
 
  tasks: 
    - name: create container 
      docker_container: 
        name: ansible-test 
        image: ubuntu:bionic 
        command: bash 
        detach: true 
        interactive: true 
        tty: true 
 
    - name: add docker container to inventory 
      add_host: 
        name: ansible-test 
        ansible_connection: docker 
 
- hosts: ansible-test 
  gather_facts: false 
  tasks: 
 
    - name: update apt cache 
      delegate_to: ansible-test 
      raw: apt -y update 
 
    - name: install python 
      delegate_to: ansible-test 
      raw: apt -y install python-minimal 
 
    - name: demonstrate that normal ansible modules work 
      file: 
        path: /etc/testdir 
        state: directory 

请注意,虽然这可行,但它并不是一个非常好的模型:您通常不想在运行时在容器中执行配置任务;您想在构建时配置您的图像。