Ansible Pilot

Create a text file - Ansible module copy

Create a text file

Ansible module copy

How to create a simple text file?

I’m going to show you a live demo 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

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.

demo

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

---
- name: copy module demo
  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

Recap

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

Academy

Learn the Ansible automation technology with some real-life examples in my

Donate

Want to keep this project going? Please donate

Follow me

Subscribe not to miss any new releases

September 22, 2021