自动创建不存在的目录的简单方法是什么

在我的安赛波剧本很多次,我需要创建文件那里

 - name: Copy file
template:
src: code.conf.j2
dest: "{{project_root}}/conf/code.conf"

现在很多时候 conf目录不在那里。然后我必须创建更多的任务来创建目录第一。

是否有任何简单的方法来自动创建目录,如果不存在一些选项

152474 次浏览

AFAIK,唯一的办法,这个 可以是通过使用 state=directory选项。 虽然 template模块支持大多数 copy选项,这反过来又支持大多数 file选项,但是您不能使用类似于 state=directory的东西。此外,这将是相当混乱的(这是否意味着 \{\{project_root}}/conf/code.conf是一个目录?还是意味着应该先创建 \{\{project_root}}/conf/

所以我不认为这是可能的,现在没有添加以前的 file任务。

- file:
path: "\{\{project_root}}/conf"
state: directory
recurse: yes

现在,这是唯一的办法

- name: Ensures \{\{project_root}}/conf dir exists
file: path=\{\{project_root}}/conf state=directory
- name: Copy file
template:
src: code.conf.j2
dest: "\{\{project_root}}/conf/code.conf"

为了确保使用完整路径获得成功,请使用 urse = yes

- name: ensure custom facts directory exists
file: >
path=/etc/ansible/facts.d
recurse=yes
state=directory

您可以使用以下命令创建文件夹,具体取决于您的可变版本。

最新版本2 <

- name: Create Folder
file:
path: "\{\{project_root}}/conf"
recurse: yes
state: directory

旧版本:

- name: Create Folder
file:
path="\{\{project_root}}/conf"
recurse: yes
state=directory

参考 -http://docs.ansible.com/ansible/latest/file_module.html

根据最新的文档当状态被设置为目录时,您不需要使用参数 递归来创建父目录,文件模块将负责它。

- name: create directory with parent directories
file:
path: /data/test/foo
state: directory

这已经足够用 创建父目录 资料测试

请参阅参数说明 -国家 Http://docs.ansible.com/ansible/latest/modules/file_module.html

如果您运行的是 Anble > = 2.0,那么还可以使用 Dirname 过滤器来提取路径的目录部分。这样,您可以只使用一个变量来保存整个路径,以确保两个任务永远不会失去同步。

例如,如果你的剧本中定义了 dest_path这样的变量,你可以重复使用同样的变量:

- name: My playbook
vars:
dest_path: /home/ubuntu/some_dir/some_file.txt
tasks:


- name: Make sure destination dir exists
file:
path: "\{\{ dest_path | dirname }}"
state: directory


# now this task is always save to run no matter how dest_path get's changed arround
- name: Add file or template to remote instance
template:
src: foo.txt.j2
dest: "\{\{ dest_path }}"

Copy 模块创建目录(如果没有的话)

- name: put fallback_dns.conf in place
copy:
src: fallback_dns.conf
dest: /etc/systemd/resolved.conf.d/
mode: '0644'
owner: root
group: root
become: true
tags: testing

这个问题说“复制”,但是它随后特别要求创建“模板”文件。

对于使用 template:,我认为需要前面的步骤 ,这里已经有许多人回答了这个问题。

但是对于 copy:来说(只复制内容,没有模板) ,那么 可以只需要一个步骤,而不是两个步骤,只需要复制完整的目录,而不是一个单独的文件:

- name: SBT repo configuration
copy:
src: files/.sbt/ # Copying the file `./files/.sbt/repositories`
dest: $HOME/.sbt/ # Works irrespective of whether the directory exists or not

$HOME/.sbt/中已经存在的其他文件不受影响。