WSL上使用Ansible的注意事项

平时使用Windows的WSL(Windows Subsystem for Linux),在WSL上安装Ansible进行Ansible代码的测试。

WSL是Ubuntu系统,可以访问Windows的C盘(Ubuntu上的挂载点为/mnt/c),但是需要注意访问权限。

使用的环境如下。

  • Windows Windows 11 Enterprise 21H2
  • WSL为Ubuntu22.04.1 LTS
  • Ansible 2.13.7

在WSL上安装Ansible,按照Ansible安装手册执行apt命令即可。

apt-get update
apt-get install software-properties-common
apt-add-repository --yes --update ppa:ansible/ansible
apt-get install ansible

一般不会报错。为了在本地运行Ansible安装VMPlayer等虚拟化软件之后,在下载Linux系统进行安装,这些步骤可以跳过,WSL相当方便。

并且使用Visual Studio Code编辑器直接编辑C盘的Ansible相关文件(/mnt/c),编辑后无需上传,可直接运行。

但是这个时候需要注意/mnt/c目录(Windows的C盘)的权限问题。

比如,ansible.cfg文件的路径为C:\ansible_tutorial\ansible.cfg时,在WSL上执行以下命令。

# cd /mnt/c/ansible_tutorial
# ansible --version
[WARNING]: Ansible is being run in a world writable directory (/mnt/c/ansible_tutorial), ignoring it as an ansible.cfg
source. For more information see https://docs.ansible.com/ansible/devel/reference_appendices/config.html#cfg-in-world-
writable-dir
ansible [core 2.13.7]
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3/dist-packages/ansible
  ansible collection location = /root/.ansible/collections:/usr/share/ansible/collections
  executable location = /usr/bin/ansible
  python version = 3.10.6 (main, Aug 10 2022, 11:40:04) [GCC 11.3.0]
  jinja version = 3.0.3
  libyaml = True

ansible –version 执行结果里的config file = /etc/ansible/ansible.cfg,可发现并没有读取当前目录下的ansible.cfg文件。

  • https://docs.ansible.com/ansible/devel/reference_appendices/config.html#avoiding-security-risks-with-ansible-cfg-in-the-current-directory

因为无法修改/mnt/c目录的访问权限,单纯地执行chmod命令无法解决改问题。这时设定环境变量ANSIBLE_CONFIG可规避上述问题。

cd /mnt/c/ansible_tutorial
export ANSIBLE_CONFIG=$(pwd)

或者使用下面的方法重新挂载C盘,就可以修改访问权限。这是从Windows 10 Build 17063(正式版本1803)后开始支持的功能。

umount /mnt/c
mount -t drvfs C: /mnt/c -o metadata

重新挂载之后,可使用chmod命令修改权限。

chmod 755 /mnt/c/ansible_tutorial