连接到受CentOS8 Ansible管理的服务器

从管理服务器进行SSH密钥交换

发送管理服务器的公钥


[ansible@mng053 ~]$ ssh-copy-id root@192.168.0.XXX
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/ansible/.ssh/id_rsa.pub"
The authenticity of host '192.168.0.XXX (192.168.0.XXX)' can't be established.
ECDSA key fingerprint is SHA256:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes     ⇒初回接続時に聞かれる。「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
root@192.168.0.XXX's password:     ⇒ログイン先のパスワード

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'root@192.168.0.XXX'"
and check to make sure that only the key(s) you wanted were added.

验证连接

完成作业后务必进行确认。
使用hostname命令确认已连接到预期的主机。


[ansible@mng053 ~]$ ssh root@192.168.0.XXX
Activate the web console with: systemctl enable --now cockpit.socket

Last login: Sat Mar 28 08:05:04 2020 from 192.168.0.XXX
[root@dbpg054 ~]# hostname
dbpg054.localdomain

在管理服务器上进行Ansible主机清单的注册

由于Ansible需要进行清单注册,因此我们将在此次操作中注册192.168.0.XXX。注册的方法请参照以下链接:
https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html#hosts-in-multiple-groups

注册的库存


[ansible@mng053 ~]$ cat /etc/ansible/hosts
all:
  children:
    centos8:
      hosts:
        192.168.0.XXX:
    postgre10:
      hosts:
        192.168.0.XXX:

我建立了一个为操作系统产品和数据库产品各自构建的团队。

沟通确认

先试试用主机名进行操作。
从管理服务器连接到被管理服务器。


[ansible@mng053 ~]$ ansible 192.168.0.XXX -m ping
192.168.0.XXX | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: ansible@192.168.0.XXX: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).",
    "unreachable": true
}

如果不指定用户名,则似乎尝试以管理服务器上的相同用户(ansible)连接到受管理服务器。
除非使用root登录……是不可以的。

似乎可以使用“-m”选项来进行用户指定。


[ansible@mng053 ~]$ ansible 192.168.0.XXX -u root-m ping
192.168.0.XXX | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}

事情进展顺利。

在「all」和「centos8」的群组中进行确认。


[ansible@mng053 ~]$ ansible all -u root -m ping
192.168.0.XXX | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}
[ansible@mng053 ~]$ ansible centos8 -u root -m ping
192.168.0.XXX | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}

连接成功!

bannerAds