How to create a directory using Ansible

后端 未结 22 1480
暗喜
暗喜 2020-12-22 16:44

How do you create a directory www at /srv on a Debian-based system using an Ansible playbook?

相关标签:
22条回答
  • 2020-12-22 17:02

    Just need to put condition to execute task for specific distribution

    - name: Creates directory
      file: path=/src/www state=directory
      when: ansible_distribution == 'Debian'
    
    0 讨论(0)
  • 2020-12-22 17:04

    Directory can be created using file module only, as directory is nothing but a file.

    # create a directory if it doesn't exist
    - file:
        path: /etc/some_directory
        state: directory
        mode: 0755
        owner: foo
        group: foo
    
    0 讨论(0)
  • 2020-12-22 17:04

    You can directly run the command and create directly using 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
    
    0 讨论(0)
  • 2020-12-22 17:06
    ---
    - hosts: all
      connection: local
      tasks:
        - name: Creates directory
          file: path=/src/www state=directory
    

    Above playbook will create www directory in /src path.

    Before running above playbook. Please make sure your ansible host connection should be set,

    "localhost ansible_connection=local"

    should be present in /etc/ansible/hosts

    for more information please let me know.

    0 讨论(0)
  • 2020-12-22 17:06

    Use file module to create a directory and get the details about file module using command "ansible-doc file"

    Here is an option "state" that explains:

    If directory, all immediate subdirectories will be created if they do not exist, since 1.7 they will be created with the supplied permissions.
    If file, the file will NOT be created if it does not exist, see the [copy] or [template] module if you want that behavior.
    If link, the symbolic link will be created or changed. Use hard for hardlinks.
    If absent, directories will be recursively deleted, and files or symlinks will be unlinked.

    Note that file will not fail if the path does not exist as the state did not change.

    If touch (new in 1.4), an empty file will be created if the path does not exist, while an existing file or directory will receive updated file access and modification times (similar to the way touch works from the command line).

    0 讨论(0)
  • 2020-12-22 17:07

    You want the file module. To create a directory, you need to specify the option state=directory :

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

    You can see other options at https://docs.ansible.com/ansible/latest/collections/ansible/builtin/file_module.html

    0 讨论(0)
提交回复
热议问题