好久没用ansible了,刚好公司最近在用,本着熟悉下试试,没想到就踩坑了,花了我一上午时间。
ansible运行报错:
fatal: [192.168.1.13]: FAILED! => {“msg”: “Missing sudo password”} #报错一看就是sudo问题
系统版本
mew@mew:/etc/ansible$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 22.04.2 LTS
Release: 22.04
Codename: jammy
ansible版本
mew@mew:/etc/ansible$ ansible --version
ansible 2.10.8
config file = /etc/ansible/ansible.cfg
configured module search path = ['/home/mew/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python3/dist-packages/ansible
executable location = /usr/bin/ansible
python version = 3.10.6 (main, May 29 2023, 11:10:38) [GCC 11.3.0]
ansible配置文件
mew@mew:/etc/ansible$ cat ansible.cfg
[defaults]
host_key_checking = False
ansible_python_interpreter = /usr/bin/python3
remote_user = mew
forks = 5
log_path = /var/log/ansible.log
timeout = 60
mew@mew:/etc/ansible$ cat hosts
[test]
192.168.1.13
192.168.1.10
#测试普通用户mew 远程sudo创建文件。
mew@mew:/etc/ansible$ cat file.yaml
- hosts: all
become: yes
become_method: sudo
tasks:
- name: copy file
file: path=/opt/test state=touch
#报错很明显sudo问题。
mew@mew:/etc/ansible$ ansible-playbook file.yaml
PLAY [all] *************************************************************************************************************************************
TASK [Gathering Facts] *************************************************************************************************************************
fatal: [192.168.1.13]: FAILED! => {"msg": "Missing sudo password"}
ok: [192.168.1.10]
但是远程主机确实配置了mew 免密码sudo
但是我sudo 切换root还是要密码。
mew@mew:~$ sudo su
[sudo] password for mew:
Sorry, try again.
[sudo] password for mew:
root@mew:/home/mew# cat /etc/sudoers | grep mew
mew ALL=(ALL) NOPASSWD:ALL
配置写错了?不可能啊,centos玩了10年了。百度看看去,没啥区别,大家都一样啊。于是想着把192.168.1.10安装ansible这台机器加进去试试行不行,额 果然10这台是可以的,13这台不行。为啥ansible本机可以呢,有啥区别呢。发现除了mew用户在sudoers文件插入的行位置不一样,其他都一样。
于是我尝试把mew 免密sudo放在sudoers文件末尾测试。
#放在文件末尾
mew ALL=(ALL) NOPASSWD:ALL
ansible ALL=(ALL) NOPASSWD:ALL
ansible命令行运行测试发现成功了。
$ ansible all -m file -a 'path=/opt/mewfile state=touch' --become --become-method=sudo --become-user=root
运行ansible-playbook竟然也成功了。
服务器租用托管,机房租用托管,主机租用托管,https://www.e1idc.com