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


当前回答

创建目录

ansible host_name -m file -a "dest=/home/ansible/vndir state=directory"

其他回答

只需要为特定的分配设置执行任务的条件

- name: Creates directory
  file: path=/src/www state=directory
  when: ansible_distribution == 'Debian'

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

- name: creates multiple directories in one task
  file:
    path: "{{ item }}"
    state: directory
  loop:
    - /srv/www
    - /dir/foo
    - /dir/bar
---
- hosts: all
  connection: local
  tasks:
    - name: Creates directory
      file: path=/src/www state=directory

上面的playbook将在/src路径下创建www目录。

在运行上面的剧本之前。请确保您的ansible主机连接应该设置,

“本地主机ansible_connection=本地”

应该出现在/etc/ansible/hosts中

如需更多信息,请与我联系。

您甚至可以扩展文件模块,甚至可以通过它设置所有者、组和权限。(参考: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

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

要检查目录是否存在,然后运行一些任务(例如创建目录),请使用以下命令

- name: Check if output directory exists
    stat:
    path: /path/to/output
    register: output_folder

- name: Create output directory if not exists
    file:
    path: /path/to/output
    state: directory
    owner: user
    group: user
    mode: 0775
    when: output_folder.stat.exists == false