Skip to main content

Managing Files and Directories

1. Copying Files

Parameter Description Example
src Source file path on the controller /path/to/source/file.txt
dest Destination file path on the managed node /tmp/file.txt
mode Permissions for the destination file 0644
owner Owner of the destination file root
group Group of the destination file root

Example: Copying a file from controller to managed node

- name: Copy file from controller to managed node
  copy:
    src: /local/path/file.txt
    dest: /remote/path/file.txt
    mode: '0644'
    owner: root
    group: root

Example: Copying a file with different permissions

- name: Copy file with executable permissions
  copy:
    src: /local/script.sh
    dest: /usr/local/bin/script.sh
    mode: '0755'
Note: The copy module does not support recursive copying of directories. Use the archive or synchronize modules for directory operations.

2. Creating Directories

Parameter Description Example
path Path to the directory to create /opt/myapp/config
state State of the directory (must be directory) directory
mode Permissions for the directory (e.g., 0755) 0755
owner Owner of the directory (e.g., root) ansible
group Group of the directory (e.g., ansible) ansible

Example: Create a directory with specific permissions and ownership

- name: Create directory with permissions
  ansible.builtin.file:
    path: /opt/myapp/config
    state: directory
    mode: '0755'
    owner: ansible
    group: ansible
Parameter Description Example
src Path to the source file or directory /etc/nginx/sites-available/default
dest Path where the symlink should be created /etc/nginx/sites-enabled/default
state Must be link to create a symlink link
force Overwrite existing files or symlinks at dest true
- name: Create a symlink
  ansible.builtin.file:
    src: /etc/nginx/sites-available/default
    dest: /etc/nginx/sites-enabled/default
    state: link
Note: The file module with state: link creates a symbolic link. Ensure the source path exists before creating the symlink.

4. Setting Permissions

Property Description Values
mode Sets file or directory permissions using octal or symbolic notation. 0644, u=rw,g=r,o=r
owner Specifies the user that owns the file or directory. root, ansible
group Specifies the group that owns the file or directory. root, ansible

Example: Setting File Permissions

- name: Set file permissions
  ansible.builtin.copy:
    src: /etc/ansible/config.ini
    dest: /etc/ansible/config.ini
    mode: '0644'
    owner: ansible
    group: ansible

Example: Setting Directory Permissions

- name: Set directory permissions
  ansible.builtin.file:
    path: /var/log/ansible
    state: directory
    mode: '0755'
    owner: ansible
    group: ansible
Note: The mode parameter supports both octal (e.g., 0644) and symbolic (e.g., u=rw,g=r,o=r) notation.

5. Setting Ownership

Parameter Description Values
owner Sets the user owner of the file or directory string
group Sets the group owner of the file or directory string
recursive Applies ownership changes recursively to subdirectories and files true or false

Example: Setting Ownership of a File

- name: Set ownership of a file
  ansible.builtin.file:
    path: /etc/myfile.txt
    owner: www-data
    group: www-data

Example: Setting Ownership Recursively

- name: Set ownership recursively
  ansible.builtin.file:
    path: /var/www/html
    owner: www-data
    group: www-data
    recursive: true
Note: The owner and group parameters can be specified as either user/group names or numeric IDs (UID/GID).

6. Removing Files

Parameter Description Default
name Path to the file or directory to remove Required
state Whether the file or directory should exist (must be absent to remove) present
force If true, remove read-only files and directories false
recurse If true, remove directories recursively false

Example: Remove a file

- name: Remove a file
  ansible.builtin.file:
    path: /tmp/example.txt
    state: absent

Example: Remove a directory recursively

- name: Remove a directory and its contents
  ansible.builtin.file:
    path: /tmp/example_dir
    state: absent
    recurse: true
Note: The file module is used here to remove files or directories. For removing files based on patterns, consider using find module in combination with file.

7. Creating Empty Files

Option Values Description
dest path/to/file Path to the file to create
state touch Ensures the file exists; creates it if missing
mode 0644 Permissions for the new file (optional)
owner user User owner of the file (optional)
group group Group owner of the file (optional)

Example: Creating an empty file

- name: Create an empty file
  ansible.builtin.file:
    path: /tmp/example.txt
    state: touch
    mode: '0644'

8. Using Templates

Property Description Example
src Path to the template file on the Ansible control node src: templates/file.j2
dest Path where the rendered template will be placed on the remote host dest: /etc/myapp/config.conf
mode Permissions for the rendered file (e.g., 0644) mode: '0644'
owner Owner of the rendered file owner: appuser
group Group of the rendered file group: appgroup

Example: Basic Template Usage

- name: Render config file from template
  ansible.builtin.template:
    src: templates/app.conf.j2
    dest: /etc/myapp/config.conf
    mode: '0644'
    owner: appuser
    group: appgroup

Example: Template with Variables

- name: Render config with variables
  ansible.builtin.template:
    src: templates/database.conf.j2
    dest: /etc/myapp/db.conf
    mode: '0640'
  vars:
    db_host: "{{ hostvars[inventory_hostname]['db_host'] }}"
    db_port: "{{ hostvars[inventory_hostname]['db_port'] }}"
Note: Template files must end with .j2 to be recognized by Ansible.

Example: Template with Loop

- name: Create multiple config files
  ansible.builtin.template:
    src: templates/service.conf.j2
    dest: "/etc/services/{{ item.name }}.conf"
  loop:
    - { name: web, port: 80 }
    - { name: api, port: 8080 }

Example: Template with Conditionals

- name: Render config based on OS
  ansible.builtin.template:
    src: templates/{{ ansible_os_family }}.conf.j2
    dest: /etc/myapp/config.conf
  when: ansible_os_family == 'RedHat'

9. Synchronizing Files

Option Values Description
src string Source directory or file path to synchronize from
dest string Destination directory or file path to synchronize to
mode string Synchronization mode: push, pull, or sync
delete bool If true, delete files in dest that don't exist in src
checksum bool If true, compare file checksums before syncing
recursive bool If true, sync subdirectories recursively

Example: Synchronizing Files

- name: Synchronize files from local to remote
  ansible.builtin.synchronize:
    src: /local/path/
    dest: /remote/path/
    delete: yes
    recursive: yes
Note: The synchronize module uses rsync under the hood, so all rsync options are supported.

10. Finding Files

Option Values Notes
find find Module to search for files and directories
file_pattern pattern Pattern to match files (e.g., *.txt)
file_path path Directory to search in
file_recursive recursive Search subdirectories recursively

Example: Find all .log files in /var/log

- name: Find all .log files in /var/log
  find:
    file_pattern: "*.log"
    file_path: "/var/log"
    file_recursive: yes
  register: log_files

- name: Display found files
  debug:
    var: log_files.files

11. Replacing Content

Parameter Description Default
src Path to a local file to replace content with None
content Literal content to write to the file None
dest Path to the destination file None
backup Create a backup before replacing false

Example: Replace file content from local source

- name: Replace content from local file
  ansible.builtin.copy:
    src: /local/file.txt
    dest: /remote/file.txt
    backup: yes

Example: Replace content with literal string

- name: Replace content with literal string
  ansible.builtin.copy:
    content: |
      Line 1
      Line 2
      Line 3
    dest: /remote/file.txt

12. Modifying Lines

Option Values Description
path string Path to the file to modify
line string The line content to ensure exists in the file
insertbefore string Insert the line before this pattern (regex)
insertafter string Insert the line after this pattern (regex)
firstmatch boolean Only match the first occurrence of the line
backup boolean Create a backup before modifying the file

Example: Ensure a line exists in a config file

- name: Ensure log level is set
  lineinfile:
    path: /etc/myapp/config.ini
    line: "log_level = INFO"
    backup: true

Example: Insert a line before a specific pattern

- name: Insert a new setting before a section
  lineinfile:
    path: /etc/nginx/nginx.conf
    line: "    proxy_cache_valid 200 302 404 60m;"
    insertbefore: "    location / {"
Note: The lineinfile module is idempotent and will not duplicate lines if they already exist.

Was this article helpful?