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


当前回答

你可以使用陈述句

- name: webfolder - Creates web folder
  file: path=/srv/www state=directory owner=www-data group=www-data mode=0775`

其他回答

我看到很多Playbooks的例子,我想提到Adhoc命令的例子。

$ansible -i inventory -m file -a "path=/tmp/ directory state=directory(我们可以用touch代替directory来创建文件)

您需要文件模块。要创建目录,您需要指定选项状态:directory:

- name: Creates directory
  file:
    path: /src/www
    state: directory

你可以在https://docs.ansible.com/ansible/latest/collections/ansible/builtin/file_module.html上看到其他选项

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

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

您甚至可以扩展文件模块,甚至可以通过它设置所有者、组和权限。(参考:Ansible文件文档)

- name: Creates directory
  file:
    path: /src/www
    state: directory
    owner: www-data
    group: www-data
    mode: 0775

甚至,你可以递归地创建目录:

- name: Creates directory
  file:
    path: /src/www
    state: directory
    owner: www-data
    group: www-data
    mode: 0775
    recurse: yes

这样,如果这两个目录不存在,它将创建它们。

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

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

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

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