ansible file managament - ghdrako/doc_snipets GitHub Wiki

Creating Directories

- name: Ensure web server directories are present
file:
  path: "{{ item }}"
  state: directory
  mode: '0755'
with_items:
  - /var/www/html
  - /var/log/web_server

Copying Files

- name: Copy static assets to web server directory
copy:
 src: files/assets/
 dest: /var/www/html/assets/

Managing Configuration Files with Templates

server {
  listen {{ web_server_port }};
  root {{ web_server_root }};
  # ...
}
roles/web_server/tasks/main.yml
- name: Configure web server
  template:
    src: web_server.conf.j2
    dest: /etc/web_server/conf.d/web_server.conf

Modifying Existing Files with lineinfile

- name: Ensure the correct timezone in PHP
configuration
lineinfile:
  path: /etc/php.ini
  regexp: '^date.timezone ='
  line: 'date.timezone = UTC'

Managing File Permissions

- name: Set permissions for web server directories
file:
  path: "{{ item }}"
  mode: '0750'
  owner: www-data
  group: www-data
with_items:
  - /var/www/html
  - /var/log/web_server

Removing Files

- name: Remove unused directory
file:
  path: /var/www/old_directory
  state: absent