Skip to Content

2 ways to create file with Ansible

Create a file with Ansible file module

There are a few ways to create a file with Ansible. One way is to use the file module. The file module has a state option that can be set to touch to create a new file.

  Description
path The path of the file that needs to be managed.
state The state of the file. Possible values are file, directory, link, hard, touch, absent.
owner The owner of the file.
group The group of the file.
mode The mode of the file in octal format.
recurse If yes, applies the specified state to all files and subdirectories recursively.
backup If yes, creates a backup of the file before modifying it.

For example, the following playbook would create a new file called myfile.txt in the home directory of the remote host:

- name: Create a file
  file:
    path: /path/to/file
    state: touch

In this example, the name parameter is used to give the task a name for identification purposes. The file module is used to interact with files and directories on the target host. The path parameter specifies the location where the file should be created.

The state parameter is set to touch which means that if the file does not exist, it will be created as an empty file.
while an existing file or directory will receive updated file access and modification times (similar to the way touch works from the command line).

We can also create a file with permission and owner.

In this example, the mode parameter is set to “0644”, which specifies that the file should have permissions of 644.

This means that the owner of the file has read and write permissions, while other users only have read permissions.

Additionally, the owner parameter is set to myuser, which specifies the file owner. The group parameter is set to mygroup, which specifies the file group. These values can be set to any valid owner and group on the target host.

- name: Create a file with specific permission and owner
  ansible.builtin.file:
    path: /path/to/file
    state: touch
    mode: "0644"
    owner: myuser
    group: mygroup

If you need to create multiple files with Ansible, you can use a loop with the ansible.builtin.file module to iterate over a list of file paths.

To learn how to use list in Ansible, you can refer to this article: Ansible Lists 101: A Beginner’s Guide to Managing and Manipulating Data

Here is an example task:

- name: Create multiple files
  ansible.builtin.file:
    path: "{{ item.path }}"
    state: touch
    mode: "{{ item.mode }}"
    owner: "{{ item.owner }}"
    group: "{{ item.group }}"
  loop:
    - { path: /path/to/file1, mode: "0644", owner: myuser, group: mygroup }
    - { path: /path/to/file2, mode: "0755", owner: myuser, group: mygroup }
    - { path: /path/to/file3, mode: "0600", owner: myuser, group: mygroup }

In this example, the path parameter is set dynamically using the item.path variable, which is taken from the current iteration of the loop. Similarly, the mode, owner, and group parameters are set using item.mode, item.owner, and item.group variables respectively.

The loop parameter is used to define the list of files to be created. In this example, the list contains three dictionary, each representing a file to be created. The path, mode, owner, and group keys in each dictionary

When the task is executed, Ansible will iterate over the list of files and create each file with the specified path, mode, owner, and group. You can add or remove files from the list as needed to create multiple files with different attributes.

Create a file with template module in Ansible

Another way to create a file with Ansible is to use the template module. The template module can be used to create a new file from a template.

Templates are files that contain text that can be dynamically generated using variables and other expressions

The template module has a number of options that can be used to control the behavior of the module. Some of the most important options are:

  Description
src The path to the template file.
dest The path to the destination file.
backup A boolean value that specifies whether or not to create a backup of the destination file.
owner The owner of the file.
group The group of the file.
mode The octal mode that you want to set for the file.

For example, the following playbook will create a new file called myfile.txt in the home directory of the remote host, and the content of the file will be taken from the template file myfile.j2:

---
- hosts: all
  hosts: web
  vars:
    http_port: 80
    https_port: 443
  tasks:
    - template:
        src: myfile.j2
        dest: /home/user/myfile.txt

Here’s an example Jinja2 template file myfile.j2:

server {
    listen {{ http_port }};
    server_name example.com;
    
    location / {
        proxy_pass http://127.0.0.1:{{ app_port }};
    }
    
    location /static {
        alias /var/www/example.com/static;
    }
    
    access_log /var/log/nginx/example.com.access.log;
    error_log /var/log/nginx/example.com.error.log;
}

In this example template file, we’re generating an Nginx configuration file for a web server that serves an application on port {{ app_port }}. We’re using the http_port variable to specify the port on which Nginx should listen.

We’re also defining two locations: / which proxies requests to the application, and /static which serves static files from the /var/www/example.com/static directory.

Finally, we’re defining access and error logs for this server.

When the template module processes this file, it will replace the variables http_port and app_port with their corresponding values.

The generated configuration file will look like this:

server {
    listen 80;
    server_name example.com;
    
    location / {
        proxy_pass http://127.0.0.1:443;
    }
    
    location /static {
        alias /var/www/example.com/static;
    }
    
    access_log /var/log/nginx/example.com.access.log;
    error_log /var/log/nginx/example.com.error.log;
}

Here is another example.

# {{ comment }}
{{ private_key }}

{{ public_key }}

In this template file, the {{ comment }}, {{ private_key }}, and {{ public_key }} are variables that will be replaced with the values defined in the Ansible playbook. For example, the comment variable could be the username of the user the SSH key belongs to, the private_key variable could be the contents of the user’s private key file, and the public_key variable could be the contents of the user’s public key file.

Here’s an example Ansible playbook that uses the template module to generate SSH key files for users:

- name: Generate SSH key files
  hosts: all
  vars:
    users:
      - name: alice
        comment: Alice Smith
        private_key: "{{ lookup('file', '/path/to/alice_rsa') }}"
        public_key: "{{ lookup('file', '/path/to/alice_rsa.pub') }}"
      - name: bob
        comment: Bob Johnson
        private_key: "{{ lookup('file', '/path/to/bob_rsa') }}"
        public_key: "{{ lookup('file', '/path/to/bob_rsa.pub') }}"
  tasks:
    - name: Create SSH key files
      template:
        src: /path/to/template.j2
        dest: "/home/{{ item.name }}/.ssh/id_rsa"
        mode: '0600'
      loop: "{{ users }}"

In this example, the playbook defines a list of users with their corresponding private and public key files. The src parameter in the template module specifies the path to the template file, and the dest parameter specifies the path where the generated SSH key files will be saved. The loop parameter iterates over each user defined in the users variable.

When the playbook is executed, the template module generates an SSH key file for each user based on the Jinja2 template file, replacing the variables with the values defined in the users variable. The mode parameter sets the permissions of the generated SSH key files to 0600.

In conclusion, using the file and template modules in Ansible is a powerful way to create and manage files on remote hosts. The file module allows users to create, modify, and delete files, while the template module enables the creation of dynamic content using Jinja2 templates.

With these modules, users can automate the creation and management of files, freeing up time for other important tasks.