手动对单独服务器进行配置

创建Ansible用户

1
useradd ansible -m -s /bin/bash -g root -c "ansible control user

检测用户所属组

1
2
[root@chqGrafana01ap ~]# groups ansible
ansible : root
1
2
3
[root@chqGrafana01ap ~]# cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
ansible:x:1002:0:ansible control user:/home/ansible:/bin/bash

配置控制节点免密登陆

手动配置

1
2
3
4
5
makir -p /home/ansible/.ssh
echo "<contorl-Public-key>" >> /home/ansible/.ssh/authorized_keys
chown -R ansible:root /home/ansible/
chmod 700 /home/ansible/.ssh
chmod 600 /home/ansible/.ssh/authorized_keys

为Ansible用户配置Sudoer

1
echo "ansible ALL=(ALL)NOPASSWD: ALL" >> /etc/sudoers.d/ansible-user

配置完成后即可使用控制节点对被控服务器进行操作


通过脚本一键部署

使用Ansible的场景大多为批量服务器同时操作,因为需要对多数的服务器都配置以上步骤,较为繁琐。可以通过以下脚本迅速对大量机器进行操作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/bin/bash
if id "ansible" >/dev/null 2>&1; then
usermod -aG root ansible
else
useradd ansible -m -s /bin/bash -g root -c "ansible control user"
fi

echo '$PASSWD' | passwd --stdin ansible

if [ -f "/home/ansible/.ssh/authorized_keys" ]; then
if grep -q "<contorl-Public-key>"; then
echo ""
else
echo "<contorl-Public-key>" >> /home/ansible/.ssh/authorized_keys
fi
else
mkdir -p /home/ansible/.ssh
echo "<contorl-Public-key>" >> /home/ansible/.ssh/authorized_keys
fi

chown -R ansible:root /home/ansible/
chmod 700 /home/ansible/.ssh
chmod 600 /home/ansible/.ssh/authorized_keys

if [ -f "/etc/sudoers.d/ansible-user" ]; then
if grep -q "ansible ALL=(ALL)NOPASSWD: ALL" "/etc/sudoers.d/ansible-user"; then
echo ""
else
sudo echo "ansible ALL=(ALL)NOPASSWD: ALL" >> /etc/sudoers.d/ansible-user
fi
else
sudo echo "ansible ALL=(ALL)NOPASSWD: ALL" >> /etc/sudoers.d/ansible-user
fi