我有一项工作任务,例如:
- hosts: webservers
sudo: yes
gather_facts: yes
tasks:
- name: Create temp directory
file: state=directory path="{{ debian.tmp_dir }}"
- name: Correct Apt Dependency
command: apt-get -f install -y
但是当我添加sudo_user: "{{ ansible_ssh_user }}"
时,它要求我通过向命令添加sudo前缀来修改命令才能正常工作,例如
- hosts: webservers
sudo: yes
sudo_user: "{{ ansible_ssh_user }}"
gather_facts: yes
tasks:
- name: Create temp directory
file: state=directory path="{{ debian.tmp_dir }}"
- name: Correct Apt Dependency
command: sudo apt-get -f install -y
鉴于sudoers列表中的ansible_ssh_user,为什么我们需要在sudo_user
不是root
时才添加sudo?
我想要解决的实际问题是创建tmp目录,如果ubuntu:ubuntu
为ansible_ssh_user
,则应为ubuntu
,而不添加user=ubuntu, group=ubuntu
答案 0 :(得分:0)
您应该以常规用户身份运行play
并明确指定需要root权限的命令,每个任务使用sudo: yes
。在这种情况下,目录将作为普通用户创建(任务2):
剧本:
---
- hosts: all
vars:
debian_tmp_dir: /tmp/my_temp_dir
tasks:
- name: Create temp directory
file: state=directory path={{ debian_tmp_dir }}
- name: Create root file
sudo: yes
command: touch /tmp/root_temp_file
- name: Check debian_tmp_dir file permissions
stat: path={{ debian_tmp_dir }}
register: user_folder_permissions
- name: Check file created with sudo permissions
stat: path=/tmp/root_temp_file
register: root_file_permissions
- debug: var=user_folder_permissions.stat.pw_name
- debug: var=root_file_permissions.stat.pw_name
输出:
==> default: Running provisioner: ansible...
PLAY [all] ********************************************************************
GATHERING FACTS ***************************************************************
ok: [default]
TASK: [Create temp directory] *************************************************
ok: [default]
TASK: [Create root file] ******************************************************
changed: [default]
TASK: [Check {{ debian_tmp_dir }} file permissions] ***************************
ok: [default]
TASK: [Check file created with sudo permissions] ******************************
ok: [default]
TASK: [debug var=user_folder_permissions.stat.pw_name] ************************
ok: [default] => {
"var": {
"user_folder_permissions.stat.pw_name": "vagrant"
}
}
TASK: [debug var=root_file_permissions.stat.pw_name] **************************
ok: [default] => {
"var": {
"root_file_permissions.stat.pw_name": "root"
}
}
PLAY RECAP ********************************************************************
default : ok=7 changed=1 unreachable=0 failed=0