跳至内容

Docker无根模式

使用非特权用户运行Docker

Molecule Docker驱动程序以root用户身份执行Ansible playbook。如果您的工作流程需要添加以非特权用户身份运行的支持,请按如下方式修改molecule.ymlDockerfile.j2

注意:Dockerfile模板和镜像构建过程仅在pre_build_image = False的情况下执行,这并非生成molecule.yml文件的默认设置。

要修改Docker镜像以支持以普通用户身份运行

将以下代码块附加到Dockerfile.j2的末尾。它创建一个具有无密码sudo权限的ansible用户。请注意,变量SUDO_GROUP取决于目标发行版,因为Debian使用sudo而不是wheel组。

# Create `ansible` user with sudo permissions and membership in `DEPLOY_GROUP`
# This template gets rendered using `loop: "{{ molecule_yml.platforms }}"`, so
# each `item` is an element of platforms list from the molecule.yml file for this scenario.
ENV ANSIBLE_USER=ansible DEPLOY_GROUP=deployer
ENV SUDO_GROUP={{'sudo' if 'debian' in item.image else 'wheel' }}
RUN set -xe \
  && groupadd -r ${ANSIBLE_USER} \
  && groupadd -r ${DEPLOY_GROUP} \
  && useradd -m -g ${ANSIBLE_USER} ${ANSIBLE_USER} \
  && usermod -aG ${SUDO_GROUP} ${ANSIBLE_USER} \
  && usermod -aG ${DEPLOY_GROUP} ${ANSIBLE_USER} \
  && sed -i "/^%${SUDO_GROUP}/s/ALL\$/NOPASSWD:ALL/g" /etc/sudoers

按如下方式修改molecule.yml中的provisioner.inventory

platforms:
  - name: instance
    image: quay.io/centos/centos:stream8
    # …
provisioner:
  name: ansible
  # …
  inventory:
    host_vars:
      # setting for the platform instance named 'instance'
      instance:
        ansible_user: ansible

确保使用您的**平台实例名称**。在本例中为instance

不同平台实例名称的示例

platforms:
  - name: centos8
    image: quay.io/centos/centos:stream8
    # …
provisioner:
  name: ansible
  # …
  inventory:
    host_vars:
      # setting for the platform instance named 'centos8'
      centos8:
        ansible_user: ansible

要测试它,请将以下任务添加到tasks/main.yml中。它会失败,因为非特权用户无权在/opt/中创建文件夹。这需要使用sudo执行。

要使用sudo执行此任务,请取消注释become: yes。现在任务将成功。

- name: Create apps dir
  file:
    path: /opt/examples
    owner: ansible
    group: deployer
    mode: 0775
    state: directory
  # become: yes

如果镜像已创建,请记得运行molecule destroy