Applying File Permissions: Use Cases and Examples
Ansible's file permission management capabilities can be applied in a variety of scenarios to ensure the security and integrity of your infrastructure. In this section, we'll explore some common use cases and provide examples to help you understand how to apply file permissions using Ansible.
Ensuring Consistent File Permissions
Maintaining consistent file permissions across multiple hosts is crucial for security and maintainability. Ansible can be used to enforce the desired file permissions on all managed hosts. Here's an example playbook:
- hosts: all
tasks:
- name: Ensure consistent file permissions
file:
path: /etc/config/app.conf
owner: appuser
group: appgroup
mode: "0644"
In this example, the file
module is used to ensure that the app.conf
file located at /etc/config/
has the correct owner, group, and permissions (read-only for the group and others) on all managed hosts.
Deploying Applications
When deploying applications, it's often necessary to set the correct file permissions for the application files and directories. Ansible can automate this process, ensuring that the application is properly configured. Here's an example:
- hosts: all
tasks:
- name: Deploy application files
unarchive:
src: /path/to/app.tar.gz
dest: /opt/app
remote_src: yes
file:
path: /opt/app
owner: appuser
group: appgroup
mode: "0755"
recurse: yes
In this example, the application files are extracted from a tar.gz archive and deployed to the /opt/app
directory. The file
module is then used to set the appropriate permissions for the application directory and its contents.
Securing Sensitive Files
Sensitive files, such as configuration files or private keys, often require specific permissions to ensure that only authorized users can access them. Ansible can be used to set the appropriate permissions for these files. Here's an example:
- hosts: all
tasks:
- name: Set permissions for private key
file:
path: /etc/ssh/id_rsa
owner: sshd
group: sshd
mode: "0600"
In this example, the private SSH key file located at /etc/ssh/id_rsa
is set to have permissions 0600
, which means that only the owner (the sshd
user) can read and write the file.
Handling Temporary Files
Temporary files or directories may need to be created with specific permissions during the execution of a task. Ansible's file
module can be used to create and manage these temporary resources. Here's an example:
- hosts: all
tasks:
- name: Create temporary directory
file:
path: /tmp/myapp
state: directory
owner: appuser
group: appgroup
mode: "0755"
In this example, a temporary directory /tmp/myapp
is created with the specified owner, group, and permissions.
By understanding these use cases and examples, you can effectively apply Ansible's file permission management capabilities to ensure the security and reliability of your infrastructure.