Ansible file creation with potentially unsafe permissions

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

Description

Ansible tasks that create files or directories without an explicit mode can produce overly broad or unpredictable permissions. Effective permissions can depend on the environment’s umask and the module’s behavior.

Sensitive files such as configuration files or private keys may become readable or writable by other users or processes. Existing permissions can also be retained, so check the actual state.

Potential impact

  • Broad read permissions can expose sensitive file contents.
  • Permissions can vary across environments, reducing deployment consistency.
  • Other users may modify configuration files and cause outages or security problems.

Remediation

  • Set mode for the purpose of each creation task. Quote octal permissions, as in "0600".
  • Give sensitive files only the owner permissions they need, and check the owner and group. Directories need execute permission for traversal, so do not blindly reuse file permissions.
  • Review creation operations such as create: true, state: touch, state: directory and get_url, and verify permissions after deployment.

Examples

These examples compare regular-file permissions. Adapt the download URL and paths to the environment, and check ownership and service read-access requirements.

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

Files are created without explicit permissions, so the environment or existing state can affect the result.

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"

mode: "0600" grants read and write permission only to the owner. If another account needs to read the file, design the service’s required access separately.

References