Ansible file creation with potentially unsafe permissions

Set permissions for the file’s purpose and verify ownership and effective permissions.

Description

When a task creates a file or directory without mode, its permissions depend on the module and the environment’s umask. An existing destination may retain its current permissions.

Potential impact

Overly broad read access can expose sensitive files. Write access can let another user change a service’s configuration.

Remediation

Specify the required mode for creation tasks such as create: true, state: touch, state: directory and get_url. Quote octal values such as "0600". Directories also need execute permission for traversal. Verify the owner, group and permissions after deployment.

Examples

Adjust the example URL and paths to your environment.

Before

yaml
- name: create config file without explicit permissions
  ansible.builtin.lineinfile:
    path: /etc/sample.conf
    create: true
    line: sample=true

- name: download file without explicit permissions
  ansible.builtin.get_url:
    url: https://example.com/file.txt
    dest: /tmp/file.txt

After

yaml
- name: create config file with explicit permissions
  ansible.builtin.lineinfile:
    path: /etc/sample.conf
    create: true
    line: sample=true
    mode: "0600"

- name: download file with explicit permissions
  ansible.builtin.get_url:
    url: https://example.com/file.txt
    dest: /tmp/file.txt
    mode: "0600"

Both tasks set mode: "0600" on a regular file, allowing only the owner to read and write it. If a separate service account needs to read the file, grant it the required read access.

References