Blog

Flexible Ansible Playbook: Efficiently Copy, Overwrite, or Append Data

6/17/2025 1 min read
Flexible Ansible Playbook: Efficiently Copy, Overwrite, or Append Data

Flexible Ansible Playbook for File Operations

This Ansible playbook is a flexible tool for copying, overwriting, or appending files and directories.
It allows you to automate file operations across multiple hosts by simply adjusting the variables defined within the playbook.

With this script, you can efficiently and consistently move or update data between different locations.


How It Works

The Tasks in the Playbook

The playbook contains three main tasks that are executed depending on the value of the variable action:

  • copy – copy files or directories
  • overwrite – overwrite target files
  • append – append content to existing files

This playbook offers a straightforward and flexible way to perform various file operations in an automated process.
It is especially useful when data needs to be regularly synchronized or updated across different systems.


Ansible Playbook

---
- name: Flexible Playbook for Copying Data
  hosts: all
  vars:
    source_path: "/pfad/zur/quelle"   # Source directory or file
    dest_path: "/pfad/zum/ziel"       # Destination directory or file
    action: "copy"                    # Possible values: copy, overwrite, append

  tasks:
    - name: Copy data
      copy:
        src: "{{ source_path }}"
        dest: "{{ dest_path }}"
      when: action == "copy"

    - name: Overwrite data
      copy:
        src: "{{ source_path }}"
        dest: "{{ dest_path }}"
        force: yes
      when: action == "overwrite"

    - name: Append data
      command: bash -c 'cat {{ source_path }} >> {{ dest_path }}'
      when: action == "append"