使用Ansible,尝试通过密码验证连接到目标服务器并显示“Hello World”,同时创建一个Linux用户

首先

由于以前没有使用过Ansible并为了学习,我尝试运行了Ansible。
因为这是第一次尝试,我在目标服务器上使用了密码认证连接,并尝试显示了Hello World。

Ansible 是一种开源的编配工具,用于自动化和配置管理 IT 基础设施。它使用 SSH 或 WinRM 等协议连接到远程主机,并执行管理目标主机上的任务。不需要在目标主机上安装代理,并且对管理目标主机的影响非常轻。

参考资料是我在Udemy上学习的《Ansible入门》课程。
https://www.udemy.com/course/ansible-linux/learn/lecture/15003064#overview

构成

我使用VirtualBox搭建了两台虚拟机。操作系统是CentOS7。

在管理主机上安装epel和ansible。
目标主机不需要安装任何包或软件。

image.png

我尝试使用密码进行验证连接到目标服务器并显示“你好,世界”。

我连接到了管理主机的SSH。

打开WSL,并通过SSH连接到管理主机的IP地址为「192.168.0.100」。

$ ssh root@192.168.0.100
root@192.168.0.100's password:
Last login: Sat Jul  8 10:35:17 2023 from 192.168.0.24

安装epel存储库。

查看当前的仓库列表

 yum repolist all

我已经确认epel已经被注册到仓库中。

[root@localhost ansible]# yum repolist all | grep epel
Failed to set locale, defaulting to C
 * epel: ftp.yz.yamagata-u.ac.jp
epel/x86_64                               Extra Packages for Ente enabled: 13753
epel-debuginfo/x86_64                     Extra Packages for Ente disabled
epel-source/x86_64                        Extra Packages for Ente disabled
epel-testing/x86_64                       Extra Packages for Ente disabled
epel-testing-debuginfo/x86_64             Extra Packages for Ente disabled
epel-testing-source/x86_64                Extra Packages for Ente disabled

安装了Ansible。

确认没有安装ansible

# rpm -qa | grep ans
jansson-2.10-1.el7.x86_64

安装了Ansible。

# yum install ansible --enablerepo=epel

为了确认是否安装了Ansible,我确认了版本。

# ansible --version
ansible 2.9.27
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.

已经设置了Ansible的hosts文件配置。

当您安装Ansible后,Ansible的主机文件”/etc/ansible/hosts”将自动生成。
主机文件需要设置登录信息以连接到目标服务器。

这次我们在group1下面添加了用户名和密码来登录目标服务器“192.168.0.32”。

vi /etc/ansible/hosts
[group1]
192.168.0.32 ansible_user=root ansible_password=<ログインパスワード>

我确认设置已成功反映。

[root@localhost ansible]# cat /etc/ansible/hosts | grep -v "#" | grep -v ^$
[group1]
192.168.0.32 ansible_user=root ansible_password=<ログインパスワード>

我已经确认了与目标服务器的连通性。

image.png

我根据以下Qiita文章的设置进行了参考。
https://qiita.com/taka379sy/items/331a294d67e02e18d68d

在ssh_connection的直接下方,添加ss_args =。

# cat /etc/ansible/ansible.cfg | grep -v "#" | grep -v "^$"
[inventory]
[privilege_escalation]
[paramiko_connection]
[ssh_connection]
ssh_args = -o ControlMaster=auto -o ControlPersist=60s -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null
[persistent_connection]
[accelerate]
[selinux]
[colors]
[diff]
[root@localhost ansible]#
image.png

我创建了一个仅包含Hello World表示的示例test.yml文件。

我创建了一个能够显示Hello world的yml文件。

“hosts all的意思是对于指定在/etc/ansible/hosts中的所有主机执行echo命令。由于此次只设置了一个目标主机,所以只会执行该主机的命令。”

# cat test.yml
- name: Execute a command
  hosts: all
  tasks:
    - name: Run command
      command: echo "Hello, World!"

我确认了/etc/ansible目录下的文件结构。

/etc/ansible
[root@localhost ansible]# ls -tlr
total 32
drwxr-xr-x. 2 root root     6 Jan 16  2022 roles
-rw-r--r--. 1 root root 19985 Jan 16  2022 ansible.cfg ※ansibleの設定ファイル
-rw-r--r--. 1 root root   109 Jul  8 09:49 test.yml ※コマンドの処理を定義する
-rw-r--r--. 1 root root  1084 Jul  8 09:50 hosts  ※接続する対象サーバーを定義する

对test.yml文件进行了语法检查。

因为只有 OK 是 1,其他都是 0,所以语法检查没有问题。

#  ansible-playbook test.yml -k --check

执行示例

[root@localhost ansible]# ansible-playbook test.yml -k --check
SSH password:

PLAY [Execute a command] **************************************************************************************************************************************************************

TASK [Gathering Facts] ****************************************************************************************************************************************************************
ok: [192.168.0.32]

TASK [Run command] ********************************************************************************************************************************************************************
skipping: [192.168.0.32]

PLAY RECAP ****************************************************************************************************************************************************************************
192.168.0.32               : ok=1    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0

执行了 test.yml 文件

当有变更时,changed的值将会大于等于0。
假设执行相同的操作多次,如果没有变更,将显示changed=0。

# ansible-playbook test.yml
[root@localhost ansible]# ansible-playbook test.yml

PLAY [Execute a command] **************************************************************************************************************************************************************

TASK [Gathering Facts] ****************************************************************************************************************************************************************
ok: [192.168.0.32]

TASK [Run command] ********************************************************************************************************************************************************************
changed: [192.168.0.32]

PLAY RECAP ****************************************************************************************************************************************************************************
192.168.0.32               : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

确认了目标主机的日志。

我连接到了目标主机“192.168.0.32”的SSH。

root@192.168.0.32's password:
Last login: Sat Jul  8 11:33:36 2023 from 192.168.0.100
[root@localhost ~]#

我查看了系统日志“/var/log/messages”。
确认在运行 Playbook 的时间段内,日志中输出了“Hello world”。

[root@localhost log]# tail -n 2 /var/log/messages
Jul  8 11:33:36 localhost ansible-command: Invoked with creates=None executable=None _uses_shell=False strip_empty_ends=True _raw_params=echo "Hello, World!" removes=None argv=None warn=True chdir=None stdin_add_newline=True stdin=None
Jul  8 11:34:37 localhost systemd-logind: Removed session 12.
[root@localhost log]#

在目标服务器上创建一个使用密码认证的Linux用户。

我打开了WSL,并通过SSH连接到管理主机「192.168.0.100」。

$ ssh root@192.168.0.100
root@192.168.0.100's password:
Last login: Sat Jul  8 10:35:17 2023 from 192.168.0.24

创建一个用于生成Linux用户的YML文件。

在以下文件夹中创建用户创建的yml文件。

[root@server1 ansible]# pwd
/etc/ansible
[root@server1 ansible]# ls -tlr
total 40
drwxr-xr-x. 2 root root     6 Jan 16  2022 roles
-rw-r--r--. 1 root root   109 Jul  8 09:49 test.yml
-rw-r--r--. 1 root root  1083 Jul  8 10:29 hosts
-rw-r--r--. 1 root root 20127 Jul  9 18:26 ansible.cfg
-rw-r--r--. 1 root root   268 Jul  9 18:57 usercreat.yml ※作成した

我创建了一个用户创建的yml文件。

我已将其配置为在 /etc/ansible/hosts 文件中指定的所有主机上执行playbook。

# vi usercreat.yml
---
- hosts: all
  become: yes
  tasks:
    - name: Create a Linux user
      user:
        name: test01
        password: "{{ 'newpassword' | password_hash('sha512') }}"
        createhome: yes
        home: /home/test01
        group: test
        shell: /bin/bash

用户密码需要进行哈希处理。
我参考了以下网站:
※使用chatGPT获得了关于ansible用户创建代码的知识。
https://qiita.com/sicksixrock66/items/474068167de9c8454319

我执行了Ansible的语法检查。

[root@server1 ansible]# ansible-playbook usercreat.yml -k --check
SSH password:

PLAY [all] **********************************************************************************************************************************************************************************************************************************

TASK [Gathering Facts] **********************************************************************************************************************************************************************************************************************
ok: [192.168.0.32]

TASK [Create a Linux user] ******************************************************************************************************************************************************************************************************************
changed: [192.168.0.32]

PLAY RECAP **********************************************************************************************************************************************************************************************************************************
192.168.0.32               : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

我执行了playbook。

[root@server1 ansible]# ansible-playbook usercreat.yml

PLAY [all] **********************************************************************************************************************************************************************************************************************************

TASK [Gathering Facts] **********************************************************************************************************************************************************************************************************************
ok: [192.168.0.32]

TASK [Create a Linux user] ******************************************************************************************************************************************************************************************************************
changed: [192.168.0.32]

PLAY RECAP **********************************************************************************************************************************************************************************************************************************
192.168.0.32               : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

如果使用-v选项运行,将会显示详细信息。

如果您想详细显示Ansible Playbook的操作,请使用-v选项。

[root@localhost ansible]# ansible-playbook -v user.yml
Using /etc/ansible/ansible.cfg as config file

PLAY [all] *********************************************************************************************************************************

TASK [Gathering Facts] *********************************************************************************************************************
ok: [192.168.0.30]

TASK [Create a Linux user] *****************************************************************************************************************
changed: [192.168.0.30] => {"changed": true, "comment": "", "create_home": true, "group": 1000, "home": "/home/test01", "name": "test01", "password": "NOT_LOGGING_PASSWORD", "shell": "/bin/bash", "state": "present", "system": false, "uid": 1001}

PLAY RECAP *********************************************************************************************************************************
192.168.0.30               : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

打开WSL,并连接到目标主机「192.168.0.32」进行SSH连接。

我已经确认了test01用户已经被创建。

[root@localhost home]# ls -tlr /home
total 0
drwx------. 3 test   test 117 Jan  9 12:44 test
drwx------  2 test01 test  62 Jul  9 19:02 test01 ※test01ユーザーが作成された
[root@localhost home]#
[root@localhost home]# id test01
uid=1001(test01) gid=1000(test) groups=1000(test)
[root@localhost home]#
image.png

提供额外的信息

Ansible需要在开头加上空格,以对齐主机(host)和任务(task)的位置。
根据任务的定义,在名称(name)前加入一个空格,否则在语法检查时会出现错误。
因此,在定义主机和任务时,请注意行首空格的数量。

image.png
image.png

总结

我发现使用Ansible可以提高工作效率,当需要在多台服务器上执行相同的命令时。

然而,必须确保管理主机和目标主机可以进行SSH连接。
在从管理主机连接到目标主机时遇到了SSH错误。
这次按照参考的Qiita文章的设置成功解决了问题,但在实际工作中,由于安全性考虑,修改配置文件时需要谨慎。

在使用Ansible时,需要在管理主机上安装Ansible。因此,如果在生产环境或其他无法安装Ansible的环境中,可能无法使用Ansible。

这次处理时,我发现在对test.yml进行语法检查方面很容易遇到问题,而且很难解决。您需要熟悉yml文件的创建。

由于我刚刚开始使用Ansible,因此我希望能够继续接触并增加我的知识。

bannerAds