Ansible使用lineinfile模块出现Permission denied权限错误如何解决
问题根因
你配置become_method: su是错误的,su提权方式默认需要输入root用户密码,而你日常的操作逻辑是用当前服务账号的sudo权限切换到root,不需要输入root密码,所以需要将提权方式指定为sudo才能匹配现有权限规则。
修正后的playbook
--- - name: Modify server.properties hosts: kafka_broker become: yes # 明确指定提权方式为sudo,匹配手动操作的逻辑 become_method: sudo become_user: root vars: ansible_ssh_extra_args: "-o StrictHostKeyChecking=no" ansible_host_key_checking: false tasks: # 可选保留该测试任务确认执行用户 - name: 验证执行用户 command: whoami register: whoami_out - debug: var=whoami_out.stdout - name: "Add the line if it does not exist" tags: addifnotexists lineinfile: path: /etc/kafka/server.properties line: "ssl.enabled.protocols = TLSv1.2" insertafter: EOF state: present backup: yes register: addifnotexists - debug: var=addifnotexists
需要排查的点
- 确认所有目标节点的
sudoers配置中,已经给svcacct账号配置了免密sudo权限,标准配置项为svcacct ALL=(ALL) NOPASSWD:ALL,如果限制了可执行命令范围,需要放开ansible模块执行所需的命令权限 - 检查
/etc/ansible/ansible.cfg全局配置文件中是否存在强制覆盖become相关配置的项,比如become_method被全局设置为非sudo的值 - 确认执行playbook时没有添加
--become-method参数覆盖剧本内配置的提权方式
特殊场景兼容方案
如果部分节点的sudo配置要求输入当前用户的密码,可以在执行playbook时加上-K参数,交互式输入svcacct的sudo密码即可,不需要root密码。
内容的提问来源于stack exchange,提问作者adbdkb
相关产品推荐
相关产品推荐

