在ansible中自动创建非现有dir的简单方法是什么?

use*_*660 100 ansible

在我的Ansible剧本中,我需要多次在那里创建文件

 - name: Copy file
   template:
     src: code.conf.j2
     dest: "{{project_root}}/conf/code.conf"
Run Code Online (Sandbox Code Playgroud)

现在很多次confdir不存在.然后我必须先创建更多任务来创建该目录.

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

Ale*_*dim 125

现在,这是唯一的方法

- 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"
Run Code Online (Sandbox Code Playgroud)

  • 应该注意你可能想在`file`调用中添加`recurse = yes`以获得`mkdir -p`类型的行为 (7认同)
  • 我认为确保这里是正确的词.保证:"积极地告诉某人某些事情以消除任何疑虑",确保:"确保(某事)将会发生或成为现实". (2认同)

小智 15

为确保使用完整路径成功,请使用recurse = yes

- name: ensure custom facts directory exists
    file: >
      path=/etc/ansible/facts.d
      recurse=yes
      state=directory
Run Code Online (Sandbox Code Playgroud)

  • `recurse=yes` 有一个不好的副作用,如果你提供模式,文件也会获得模式(例如 0755)。它也不是必需的:```如果是目录,则所有中间子目录(如果它们不存在)都将被创建。从 Ansible 1.7 开始,它们将使用提供的权限创建。``` (3认同)
  • 根据文档(和我的测试),总是创建子目录,而`recurse = yes`只递归地应用权限。但是,文档指出,这是从v1.7开始自动发生的,因此“递归”可能已经过时了。 (2认同)

Ste*_*ing 10

如果您正在运行Ansible> = 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
        recurse: yes

    # 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 }}"
Run Code Online (Sandbox Code Playgroud)

  • 虽然这个解决方案仍然冗长,但我认为它最接近作者的意图。如果有像 Salt 这样的简单“makedirs”参数,我会*喜欢*它:https://docs.saltstack.com/en/latest/ref/states/all/salt.states.file.html#salt.states .file.managed (2认同)

leu*_*cos 7

据我所知,这是唯一的方法可以做的是通过使用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
Run Code Online (Sandbox Code Playgroud)


小智 5

根据最新文档,在将状态设置为目录时,您无需使用参数递归来创建父目录,文件模块将负责处理。

- name: create directory with parent directories
  file:
    path: /data/test/foo
    state: directory
Run Code Online (Sandbox Code Playgroud)

这足以创建父目录数据并使用foo 测试

请参阅参数说明-“ 状态http://docs.ansible.com/ansible/latest/modules/file_module.html