How to perform File System operations (copy, exists, move, ) in Ansible?

Card Puncher Data Processing


This page shows you how to perform File system operations in Ansible.


Get file name

{{ item|basename }}
  • Filename without extension (splits the extension only after the last dot)
{{ item | basename | splitext | first }}
  • Directory name
{{ path | dirname }}

More managing-file-names-and-path-names

Create a directory

# create a directory if it doesn't exist
- file:
    path: /etc/some_directory
    state: directory
    mode: 0755

Create a file

- name: Touch a file, using symbolic modes to set the permissions (equivalent to 0644)
    path: /etc/foo.conf
    state: touch
    mode: u=rw,g=r,o=r


Ownership recursively

- file:
    path: /etc/some_directory
    state: directory
    group: 'foo'
    owner: 'bar'
    recurse: yes


from local to host

With Copy
- name: Copy ansible inventory file to client (command on  multi-line - break + indent any continuation lines)
    src: hosts 
    dest: /etc/ansible/hosts
    owner: root 
    group: root 
    mode: 0644
    backup: yes

where the relative search path for src is

  • for a play, playdir/{files|vars|templates}/, playdir/.
  • for a role, rolename/{files|vars|templates}/, rolename/tasks/.

The synchronize-module is more efficient than copy for a large number of files. The synchronize module wraps rsync.

With template

See Ansible - Template module

from same host

- name: Move file
  become: yes
  become_user: "{{ prometheus_user_name }}"
    cmd: "/bin/cp {{ prometheus_install_dir }}/{{ prometheus_node_exporter_name }}/* {{ prometheus_home }}"

from Host to host

You use normally 'rsync' for this purpose (with the synchronize module or at the command line)


  • without the rsync daemon passing the ssh password via sshpass at the command line,
- name: 'Copy the keystore from the master'
  delegate_to: "{{ hostvars[ groups['gateway'][0] ].inventory_hostname }}"
  shell: |
    sshpass -p "{{ ansible_password }}" rsync \
      -v \
      {{ src_path_file }} \
      {{ ansible_user }}@{{ ansible_host }}:{{ dst_path_file }}
  register: keystore_copy
  changed_when: keystore_copy.rc != 0
  • or with the synchronize module If the rsync daemon is not running, you may got a permission denied
- hosts: all
   - name: Copy Remote-To-Remote (from serverA to serverB)
     synchronize: src=/copy/from_serverA dest=/copy/to_serverB
     delegate_to: serverA
     when: inventory_hostname = serverB


One directory

with with_fileglob -

  • Matches files in a single directory,
  • non-recursive
- name: display content of all .txt files in dir
  debug: msg={{lookup('fileglob', '/my/path/*.txt')}}

- name: "Connection templates that add the environment as prefix {{ env_name}}"
    become: yes
    become_user: '{{ bdm_install_user }}'
      src: '{{ item }}'
      dest: '{{ connection_dst }}/{{ item|basename }}_{{ env_name|upper }}'
      owner: '{{ bdm_install_user }}'
      group: '{{ bdm_install_group }}'
      mode: 0770
    with_fileglob: 'template/connections/*'

The tree (recursive)

- name: "Creating connection file properties from template for the environment {{ env_name }}"
    become: yes
    become_user: '{{ bdm_install_user }}'
      src: '{{ item.src }}'
      dest: '{{ bdm_connection_dst }}/{{ item.path }}_{{ env_name|upper }}'
      owner: '{{ bdm_install_user }}'
      group: '{{ bdm_install_group }}'
      mode: 0770
    with_filetree: 'template/connection/{{ env_name|lower }}'
    when: item.state == 'file'

Conditional task

based on file presence, if file exists

- name: Stat the {{ infa_domain_file }} 
    path: '{{infa_domain_file}}'
  register: infa_domain_file

- name: Install if the domain file does not exist
  become: yes
  become_user: '{{ bdm_install_user }}'
  import_tasks: user_install.yml
  when: not infa_domain_file.stat.exists

You can also just fail

- name: Check if Gogs is already installed.
    path: "{{ gogs_bin_file }}"
  register: gogs_bin

- name: Download
  when: gogs_bin.stat.islnk is not defined

Creation of file with content

You create a file with you own content (ie string) with the copy module

Example with a private key that was encrypted with encrypt string

- name: Private Key
    content: "{{ private_key }}"
    dest: "/path/to/my/key"
    owner: 'root'
    group: 'root'
    mode: "0600"

Presence of text in file

Block In File

    path: /etc/hosts
    block: |
      {{ item.ip }} {{ }}
    marker: "# {mark} ANSIBLE MANAGED BLOCK Hostname"
    - { name: "{{ hostname }}  {{ hostname.split('.', 1)[0] }}", ip: }



- name: 'Configure the Java memory requirement'
    dest: "{{nexus_application_directory}}/bin/nexus.vmoptions"
    state: present
    regexp: "{{ item.regexp }}"
    line: "{{ item.line }}"
    - regexp: '^-Xms(\\d+)m$'
      line: '-Xms{{nexus_java_memory}}m'
    - regexp: '^-Xmx(\\d+)m$'
      line: '-Xmx{{nexus_java_memory}}m'
    - regexp: '^-XX:MaxDirectMemorySize=(\\d+)m$'
      line: '-XX:MaxDirectMemorySize={{nexus_java_memory}}m'
    - nexus reload

Discover More
Card Puncher Data Processing
Ansible - Copy Module (Remote File System operation)

The copy module operates on the remote system to move the file into its final location, sets file permissions, and so on. See ...
Card Puncher Data Processing
Ansible - Flow (Conditional)

This page is conditional operators in Ansible. Variable initialization See Loop variable value can be made conditional. Example: variables by type of operating system with include_vars...
Card Puncher Data Processing
Ansible - Function

function in Ansible are tasks that includes other playbook and can pass variable. Include_tasks is done at runtime while import_tasks is done at start time If you have a conditional (such as...
Card Puncher Data Processing
Ansible - Loop

loop in Ansible are done with look up plugin that returns variables for each selectionned item that you can use in your template. loop in Ansible are never nested but you can combine list See...
Bash Liste Des Attaques Ovh
Sudo - How to allow a user to manage a service ?

How to allow a user to manage a service with sudo sudo is a program that defines rules over what a user may run as command. It allows to add sudoer file (configruation file) into the directory /etc/sudoers.d...

Share this page:
Follow us:
Task Runner