使用 Ansible playbook 启用和禁用 root 登录

Sco*_*n21 8 ansible ubuntu-18.04

我是 Ansible 的新手,我正在尝试编写我的第一个 Ansible 剧本,以通过 ssh 两个远程 ubuntu 服务器启用 root 登录。

默认情况下,禁用以 root 身份 ssh 到两个远程 ubuntu 服务器的功能。为了通过 ssh 启用 root 登录,我通常这样做

#ssh to server01 as an admin user
ssh admin@server01

#set PermitRootLogin yes 
sudo vim /etc/ssh/sshd_config

# Restart the SSH server
service sshd restart
Run Code Online (Sandbox Code Playgroud)

现在我想通过 Ansible 剧本来做到这一点。

这是我的剧本

---
 - hosts: all
   gather_facts: no

   tasks:
   - name: Enable Root Login
     lineinfile:
           dest: /etc/ssh/sshd_config
           regexp: '^PermitRootLogin'
           line: "PermitRootLogin yes"
           state: present
           backup: yes
     notify:
       - restart ssh

   handlers:
   - name: restart ssh
     service:
       name: sshd
       state: restarted
Run Code Online (Sandbox Code Playgroud)

我以在这两个远程服务器中创建的管理员用户身份运行剧本

ansible-playbook enable-root-login.yml -u admin --ask-pass
Run Code Online (Sandbox Code Playgroud)

不幸的是,由于权限被拒绝,剧本失败。

fatal: [server01]: FAILED! => {"ansible_facts": {"discovered_interpreter_python": "/usr/bin/python"}, "changed": false, "msg": "Could not make backup of /etc/ssh/sshd_config to /etc/ssh/sshd_config.2569989.2021-07-16@06:33:33~: [Errno 13] Permission denied: '/etc/ssh/sshd_config.2569989.2021-07-16@06:33:33~'"}
Run Code Online (Sandbox Code Playgroud)

谁能告诉我我的剧本有什么问题吗?谢谢

小智 8

当您编辑使用的 sshd_config 文件时sudo,您需要指定该任务必须与其他用户一起执行。您必须设置关键字become: yes,默认情况下是become_userwill beroot和 the become_methodwill be sudo,您也可以指定become_password.

---
 - hosts: all
   gather_facts: no

   tasks:
   - name: Enable Root Login
     lineinfile:
           dest: /etc/ssh/sshd_config
           regexp: '^PermitRootLogin'
           line: "PermitRootLogin yes"
           state: present
           backup: yes
     become: yes
     notify:
       - restart ssh

   handlers:
   - name: restart ssh
     systemctl:
       name: sshd
       state: restarted
Run Code Online (Sandbox Code Playgroud)

文档: https ://docs.ansible.com/ansible/latest/user_guide/become.html#using-become