你如何创建一个目录www在/srv上基于debian的系统使用Ansible剧本?


当前回答

目录只能使用文件模块创建,因为目录只是一个文件。

# create a directory if it doesn't exist
- file:
    path: /etc/some_directory
    state: directory
    mode: 0755
    owner: foo
    group: foo

其他回答

可以直接执行该命令,使用ansible直接创建

ansible -v targethostname -m shell -a "mkdir /srv/www" -u targetuser

OR

ansible -v targethostname -m file -a "path=/srv/www state=directory" -u targetuser

—name:创建目录 ansible.builtin.file: 路径:/etc/some_directory 状态:目录 模式:“0755”

另外,在很多情况下,您需要创建多个目录,因此使用循环而不是为每个目录创建单独的任务是一个好主意。

- name: creates multiple directories in one task
  file:
    path: "{{ item }}"
    state: directory
  loop:
    - /srv/www
    - /dir/foo
    - /dir/bar

在本例中,您可以使用"file"模块,其中有许多参数可以传递给新创建的目录,如所有者、组、位置、模式等.....

关于文件模块的详细说明请参考本文档…

https://docs.ansible.com/ansible/latest/modules/file_module.html#file-module

记住这个模块不仅仅是用来创建目录的!!

在Ansible中创建目录的最简单方法。

name:如果your_directory不存在,创建该目录。 文件: 路径:/etc/your_directory

OR

您希望给该目录赋予sudo特权。

name:如果your_directory不存在,创建该目录。 文件: 路径:/etc/your_directory 模式:“777”