Ansible - File System operation

> Infrastructure as code > Ansible

1 - About

File system operations in Ansible

Advertising

3 - Management

3.1 - Get file name

  • When looping through files, you can get the basename with the template filter basename
{{ item|basename }}

3.2 - Create a directory

http://docs.ansible.com/file_module.html

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

3.3 - Copy

The copy module has a recursive parameter. See Ansible - Copy Module (Remote File System operation)

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

3.4 - Synchronize

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

3.5 - Loop

3.5.1 - One directory

- 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 }}'
    template:
      src: '{{ item }}'
      dest: '{{ connection_dst }}/{{ item|basename }}_{{ env_name|upper }}'
      owner: '{{ bdm_install_user }}'
      group: '{{ bdm_install_group }}'
      mode: 0770
    with_fileglob: 'template/connections/*'
Advertising

3.5.2 - The tree (recursive)

- name: "Creating connection file properties from template for the environment {{ env_name }}"
    become: yes
    become_user: '{{ bdm_install_user }}'
    template:
      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'

3.6 - Conditional task based on file presence

- name: Stat the {{ infa_domain_file }} 
  stat:
    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
infra/ansible/fs.txt · Last modified: 2019/09/10 16:58 by gerardnico