← Lessons/Tasks & Modules
← Tasks & Modules

Create a file with the copy module

Learn

copy: a file with exact contents

A module is a small, focused tool that manages one kind of thing: a file, a package, a service, a user. You don't tell it how; you give it the desired state.

ansible.builtin.copy ensures a file exists with exact contents: dest: is where, content: is what. It checks the file first: if it's missing or different, it writes it; if it already matches, it leaves it alone.

Every task reports one of two outcomes you'll watch constantly:

  • changed: reality didn't match the desired state, so Ansible acted;
  • ok: reality already matched, so Ansible did nothing. The task still passed; it just had no work to do.

A file that doesn't exist yet is, by definition, a changed.

Add a task using ansible.builtin.copy to create app.conf with the exact contents port=8080. Because the file doesn't exist yet, the task will report changed.

    - name: Write the app config
      ansible.builtin.copy:
        dest: app.conf
        content: "port=8080\n"
$ ansible-playbook playbook.yml
Loading...

Output

Run your solution to see its output here.