I’m going to show you a live Playbook with some simple Ansible code. I’m Luca Berton and welcome to today’s episode of Ansible Pilot.

Ansible create a text file

Today we’re talking about Ansible module copy. The full name is ansible.builtin.copy which means is part of the collection of modules “builtin” with ansible and shipped with it. This module is pretty stable and out for years. The purpose is to copy files to remote locations but it’s also capable to create some simple text files. If you need a more complex configuration it’s better to rely on the template module.

Parameters

  • dest path - destination file
  • content string - text
  • mode/owner/group - permission
  • setype/seuser/selevel - SELinux

The parameter list is pretty wide but I’ll summarize the most useful for the use case. The only required parameter is “dest” which specifies the remote absolute path destination. The content parameter sets the contents of a file directly to the specified value. It works only when dest is a file/ Please note that if you use a variable in the content parameter will result in unpredictable output. For advanced formatting or if the content contains a variable, use the ansible.builtin.template module. Let me also highlight that we could also specify the permissions and SELinux properties.

Join 50+ hours of courses in our exclusive community

Playbook

Let’s jump into a real-life playbook on how to create an empty file with Ansible.

code

  • copy.yml
---
- name: copy module Playbook
  hosts: all
  vars:
    myfile: "{{ ~/example.txt }}"
  tasks:
  - name: create a text file
    ansible.builtin.copy:
      dest: "{{ myfile }}"
      content: |
        line 1
        line 2        

code with ❤️ in GitHub

Conclusion

Now you know better how to create a text file with Ansible. Subscribe to the YouTube channel, Medium, and Website, X (formerly Twitter) to not miss the next episode of the Ansible Pilot.

Academy

Learn the Ansible automation technology with some real-life examples in my Udemy 300+ Lessons Video Course.

BUY the Complete Udemy 300+ Lessons Video Course

My book Ansible By Examples: 200+ Automation Examples For Linux and Windows System Administrator and DevOps

BUY the Complete PDF BOOK to easily Copy and Paste the 250+ Ansible code

Want to keep this project going? Please donate

Patreon Buy me a Pizza