FreeKB - Ansible file module (create directory mkdir)
Ansible - file module (create directory mkdir)

The file module with state: directory is used to create a directory on a managed node (e.g. target system). Or, the local_action module can be used to invoke this module on the control node (that's your Ansible server).

The ansible-doc file command can be used to show the Ansible documention on the file module.

In this example, the /tmp/example directory will be created if it does not exist.

- name: "mkdir /tmp/example"
  file:
    path: "/tmp/example"
    state: "directory"

 

Directory created

If the directory was successfully created, the play should indicate changed.

TASK [mkdir /tmp/example]
changed: [server1.example.com]

 

Directory not created

If the directory was not created, the play should indicate ok. This is the expected behavior if the directory already exists. If the directory already exists, the directory will not be created, overwritten, or changed.

TASK [mkdir /tmp/example]
ok: [server1.example.com]

 

Optional Parameters

The file module accepts the following parameters.

  • owner (e.g. owner: "root")
  • group (e.g. group: "wheel")
  • mode (e.g. mode: "2775")
  • seuser - SELinux user (e.g. seuser: "unconfined_u")
  • serole - SELinux role (e.g. serole: "object_r")
  • setype - SELinux type (e.g. setype: "httpd_sys_content_t")
  • selevel - SELinux level (e.g. selevel: "s0")

 

Here is an example of how these parameters would be used.

- name: "mkdir /tmp/example"
  file:
    path: "/tmp/example"
    state: "directory"
    owner: "foo"
    group: "foo"
    mode: "0644"
    seuser: "unconfined_u"
    serole: "object_r"
    setype: "httpd_sys_content_r"
    selevel: "s0"

 

 

Permission denied

If permission denied is returned when running the play, refer to our article on resolving permission denied.

 


You may also want to use x.stat.exists to determine if the directory exists, and x.stat.isdir to determine if the object is a directory.



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter c7c4d in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |