Ansible无密码执行时向其他用户目录复制解压文件问题
Hey there! Let's work through this Ansible playbook issue you're dealing with. You're trying to copy your local tasks.tar.gz to remote servers and extract it to /data/files/tasks/, but that target directory is owned by another user—this is a common permission hurdle, and we've got a few solid fixes for it.
Solution 1: Elevate privileges with
become (most common approach) If the target directory is owned by root or a privileged user, we can use Ansible's become feature to run tasks with elevated permissions. This lets us bypass the ownership restriction safely:
--- - name: Copy and extract tasks archive to remote target hosts: your_remote_servers_group become: yes # Defaults to switching to root via sudo tasks: - name: Copy local archive to remote temporary directory ansible.builtin.copy: src: ./tasks.tar.gz dest: /tmp/tasks.tar.gz mode: '0644' # Using /tmp avoids permission issues since it's world-writable by default - name: Extract archive to the target directory ansible.builtin.unarchive: src: /tmp/tasks.tar.gz dest: /data/files/tasks/ remote_src: yes owner: target_username # Replace with the actual owner of /data/files/tasks/ group: target_groupname # Replace with the directory's group # These owner/group params ensure extracted files match the directory's permissions - name: Clean up temporary archive ansible.builtin.file: path: /tmp/tasks.tar.gz state: absent
Quick notes for this approach:
- Make sure your
daviduser on machineA has sudo access on the remote servers. You can verify this by logging into a remote server asdavidand runningsudo -l. - The temporary
/tmpdirectory is a safe middle ground because almost all users can write to it, avoiding initial copy failures.
Solution 2: Run tasks directly as the directory's owner
If you don't want to use root, you can switch directly to the user who owns /data/files/tasks/ using become_user:
--- - name: Copy and extract archive as the target directory owner hosts: your_remote_servers_group become: yes become_user: target_username # Replace with the actual owner of the target directory tasks: - name: Copy local archive to the target user's home directory ansible.builtin.copy: src: ./tasks.tar.gz dest: ~/tasks.tar.gz mode: '0644' # The target user will have full access to their home directory - name: Extract archive to the target directory ansible.builtin.unarchive: src: ~/tasks.tar.gz dest: /data/files/tasks/ remote_src: yes - name: Remove the archive from the home directory ansible.builtin.file: path: ~/tasks.tar.gz state: absent
Extra tips to avoid headaches:
- Test your playbook in dry-run mode first with
ansible-playbook your_playbook.yml --checkto catch permission issues without making changes. - If you need to enforce specific file permissions for the extracted content, add the
modeparameter to theunarchivetask (e.g.,mode: '0755'for executable files).
内容的提问来源于stack exchange,提问作者user1950349
相关产品推荐
相关产品推荐

