1.4. 准备受管节点
Ansible 不在受管主机上使用代理。唯一的要求是 Python (默认情况下在 RHEL 上安装),以及对受管主机的 SSH 访问。
但是,以 root
用户身份直接进行 SSH 访问可能会造成安全隐患。因此,当您准备受管节点时,您可以在此节点上创建一个本地用户并配置 sudo
策略。然后,控制节点上的 Ansible 可以使用此帐户登录受管节点,并以不同的用户(如 root
)执行 playbook。
先决条件
- 您已准备好了控制节点。
流程
创建用户:
[root@managed-node-01]# useradd ansible
控制节点稍后使用这个用户建立与这个主机的 SSH 连接。
为
ansible
用户设置密码:[root@managed-node-01]# passwd ansible Changing password for user ansible. New password: password Retype new password: password passwd: all authentication tokens updated successfully.
当 Ansible 使用
sudo
以root
用户身份执行任务时,您必须输入此密码。在受管主机上安装
ansible
用户的 SSH 公钥:以
ansible
用户身份登录控制节点,并将 SSH 公钥复制到受管节点:[ansible@control-node]$ ssh-copy-id managed-node-01.example.com /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/ansible/.ssh/id_rsa.pub" The authenticity of host 'managed-node-01.example.com (192.0.2.100)' can't be established. ECDSA key fingerprint is SHA256:9bZ33GJNODK3zbNhybokN/6Mq7hu3vpBXDrCxe7NAvo. Are you sure you want to continue connecting (yes/no/[fingerprint])? yes /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys ansible@managed-node-01.example.com's password: password Number of key(s) added: 1 Now try logging into the machine, with: "ssh 'managed-node-01.example.com'" and check to make sure that only the key(s) you wanted were added.
在控制节点上远程执行命令以验证 SSH 连接:
[ansible@control-node]$ ssh managed-node-01.example.com whoami ansible
为
ansible
用户创建sudo
配置:使用
visudo
命令创建和编辑/etc/sudoers.d/ansible
文件:[root@managed-node-01]# visudo /etc/sudoers.d/ansible
在正常编辑器中使用
visudo
的好处是,该实用程序提供基本的健全检查和检查是否有解析错误,然后再安装该文件。在
/etc/sudoers.d/ansible
文件中配置满足您要求的sudoers
策略,例如:要为
ansible
用户授予权限,以便在输入ansible
用户密码后在此主机上以任何用户和组身份来运行所有命令,请使用:ansible ALL=(ALL) ALL
要向
ansible
用户授予权限,以便在不输入ansible
用户密码的情况下在该主机上以任何用户和组身份来运行所有命令,请使用:ansible ALL=(ALL) NOPASSWD: ALL
或者,配置匹配您安全要求的更精细的策略。有关
sudoers
策略的详情,请查看sudoers (5)
手册页。
其他资源
- 准备控制节点
-
sudoers (5)
手册页