用 Ansible 在Linux系统上搭建一个基于用户控制的https网站

该实验通过Ansible Playbook自动化配置HTTPS网站,包括安装Apache服务、生成证书、创建用户信息文件,并使用YAML语法编写配置文件,实现协议为https且用户可控的网站。最终通过Ansible执行Playbook完成所有节点的配置,并测试验证了网站的正常运行。
摘要由CSDN通过智能技术生成


--------------含源码--------------

前言

Playbook 是 Ansible “任务书”,它采用了 YAML 语法,学习 Ansible 以及前置配置请移步:Ansible的原理与配置


本文介绍一个简单的小实验,要求如下:

  1. 网站要求:协议https、可以用户控制
  2. 用 Playbook 编写任务

实验

环境配置

创建 Ansible 工作目录

[root@master:~]$ su - class
Last login: Mon Feb 21 18:05:52 CST 2022 on pts/0
[class@master:~]$ mkdir https_server
[class@master:~]$ cd https_server/
[class@master:~/https_server]$

创建清单:vim inventory

[class@master:~/https_server]$ vim inventory
[class@master:~/https_server]$ cat inventory
master

[web]
node12
node13

在这里插入图片描述
编写配置文件:vim ansible.cfg

[class@master:~/https_server]$ vim ansible.cfg
[class@master:~/https_server]$ cat ansible.cfg
[defaults]
inventory=./inventory
remote_user=student
ask_pass=false

[privilege_escalation]
become=true
become_method=sudo
become_user=root
become_ask_pass=false

在这里插入图片描述
既然是搭建Web网站就需要配置文件,我们可以创建在本地,一会使用copy模块拷贝给受控节点的/etc/httpd/conf.d/

[class@master:~/https_server]$ mkdir conf.d
[class@master:~/https_server]$ vim conf.d/https.conf
[class@master:~/https_server]$ cat conf.d/https.conf
<Directory /var/www>
        AuthType basic
        AuthName "please login:"
        AuthUserFile /usr/local/secret
        Require user xiaoming
</Directory>
<VirtualHost *:443>
SSLEngine on
SSLCertificateFile /etc/pki/tls/certs/https.crt
SSLCertificateKeyFile /etc/pki/tls/certs/https.key

        DocumentRoot /var/www
        ServerName 0.0.0.0
</VirtualHost>

在这里插入图片描述

https的配置文件写好了,接下来完善文件中指定的内容.
创建证书,一会拷贝到受控节点的/etc/pki/tls/certs/

[class@master:~/https_server]$ mkdir ssl_certs
[class@master:~/https_server]$ cd ssl_certs/

# 生成密钥
[class@master:~/https_server/ssl_certs]$ openssl genrsa -out https.key
Generating RSA private key, 2048 bit long modulus (2 primes)
.............................................................+++++
................................+++++
e is 65537 (0x010001)

# 签名
[class@master:~/https_server/ssl_certs]$ openssl req -key https.key -x509 -out https.crt      
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:86
State or Province Name (full name) []:shaanxi
Locality Name (eg, city) [Default City]:Xi'an
Organization Name (eg, company) [Default Company Ltd]:chi
Organizational Unit Name (eg, section) []:cc
Common Name (eg, your name or your server's hostname) []:www.chi.com
Email Address []:root@chi.com
[class@master:~/https_server/ssl_certs]$ ls
https.crt  https.key

生成用户信息的文件,由于htpasswd命令是Apache服务产生的,故我们本机需要先下载 httpd 服务,才可以使用此命令

[class@master:~/https_server]$ sudo yum install httpd -y
Last metadata expiration check: 1:22:31 ago on Mon 21 Feb 2022 10:14:18 PM CST.
Dependencies resolved.
=======================================================================================================
 Package                Arch        Version                                       Repository      Size
=======================================================================================================
Installing:
 httpd                  x86_64      2.4.37-43.module+el8.5.0+727+743c5577.1       appstream      1.4 M
Installing dependencies:
 apr                    x86_64      1.6.3-12.el8                                  appstream      128 k
 apr-util               x86_64      1.6.1-6.el8.1                                 appstream      104 k
 httpd-filesystem       noarch      2.4.37-43.module+el8.5.0+727+743c5577.1       appstream       39 k
 httpd-tools            x86_64      2.4.37-43.module+el8.5.0+727+743c5577.1       appstream      106 k
 mod_http2              x86_64      1.15.7-3.module+el8.5.0+695+1fa8055e          appstream      153 k
 rocky-logos-httpd      noarch      85.0-3.el8                                    baseos          22 k
Installing weak dependencies:
 apr-util-bdb           x86_64      1.6.1-6.el8.1                                 appstream       23 k
 apr-util-openssl       x86_64      1.6.1-6.el8.1                                 appstream       26 k
Enabling module streams:
 httpd                              2.4

Transaction Summary
=======================================================================================================
Install  9 Packages

Total download size: 2.0 M
Installed size: 5.4 M
Downloading Packages:
(1/9): apr-util-bdb-1.6.1-6.el8.1.x86_64.rpm                           121 kB/s |  23 kB     00:00
(2/9): apr-util-openssl-1.6.1-6.el8.1.x86_64.rpm                       402 kB/s |  26 kB     00:00
(3/9): apr-util-1.6.1-6.el8.1.x86_64.rpm                               378 kB/s | 104 kB     00:00
(4/9): apr-1.6.3-12.el8.x86_64.rpm                                     436 kB/s | 128 kB     00:00
(5/9): httpd-filesystem-2.4.37-43.module+el8.5.0+727+743c5577.1.noarch 790 kB/s |  39 kB     00:00
(6/9): httpd-tools-2.4.37-43.module+el8.5.0+727+743c5577.1.x86_64.rpm  1.0 MB/s | 106 kB     00:00
(7/9): mod_http2-1.15.7-3.module+el8.5.0+695+1fa8055e.x86_64.rpm       1.5 MB/s | 153 kB     00:00
(8/9): rocky-logos-httpd-85.0-3.el8.noarch.rpm                         431 kB/s |  22 kB     00:00
(9/9): httpd-2.4.37-43.module+el8.5.0+727+743c5577.1.x86_64.rpm        1.8 MB/s | 1.4 MB     00:00
-------------------------------------------------------------------------------------------------------
Total                                                                  454 kB/s | 2.0 MB     00:04
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                                               1/1
  Installing       : apr-1.6.3-12.el8.x86_64                                                       1/9
  Running scriptlet: apr-1.6.3-12.el8.x86_64                                                       1/9
  Installing       : apr-util-bdb-1.6.1-6.el8.1.x86_64                                             2/9
  Installing       : apr-util-openssl-1.6.1-6.el8.1.x86_64                                         3/9
  Installing       : apr-util-1.6.1-6.el8.1.x86_64                                                 4/9
  Running scriptlet: apr-util-1.6.1-6.el8.1.x86_64                                                 4/9
  Installing       : httpd-tools-2.4.37-43.module+el8.5.0+727+743c5577.1.x86_64                    5/9
  Installing       : rocky-logos-httpd-85.0-3.el8.noarch                                           6/9
  Running scriptlet: httpd-filesystem-2.4.37-43.module+el8.5.0+727+743c5577.1.noarch               7/9
  Installing       : httpd-filesystem-2.4.37-43.module+el8.5.0+727+743c5577.1.noarch               7/9
  Installing       : mod_http2-1.15.7-3.module+el8.5.0+695+1fa8055e.x86_64                         8/9
  Installing       : httpd-2.4.37-43.module+el8.5.0+727+743c5577.1.x86_64                          9/9
  Running scriptlet: httpd-2.4.37-43.module+el8.5.0+727+743c5577.1.x86_64                          9/9
  Verifying        : apr-1.6.3-12.el8.x86_64                                                       1/9
  Verifying        : apr-util-1.6.1-6.el8.1.x86_64                                                 2/9
  Verifying        : apr-util-bdb-1.6.1-6.el8.1.x86_64                                             3/9
  Verifying        : apr-util-openssl-1.6.1-6.el8.1.x86_64                                         4/9
  Verifying        : httpd-2.4.37-43.module+el8.5.0+727+743c5577.1.x86_64                          5/9
  Verifying        : httpd-filesystem-2.4.37-43.module+el8.5.0+727+743c5577.1.noarch               6/9
  Verifying        : httpd-tools-2.4.37-43.module+el8.5.0+727+743c5577.1.x86_64                    7/9
  Verifying        : mod_http2-1.15.7-3.module+el8.5.0+695+1fa8055e.x86_64                         8/9
  Verifying        : rocky-logos-httpd-85.0-3.el8.noarch                                           9/9

Installed:
  apr-1.6.3-12.el8.x86_64
  apr-util-1.6.1-6.el8.1.x86_64
  apr-util-bdb-1.6.1-6.el8.1.x86_64
  apr-util-openssl-1.6.1-6.el8.1.x86_64
  httpd-2.4.37-43.module+el8.5.0+727+743c5577.1.x86_64
  httpd-filesystem-2.4.37-43.module+el8.5.0+727+743c5577.1.noarch
  httpd-tools-2.4.37-43.module+el8.5.0+727+743c5577.1.x86_64
  mod_http2-1.15.7-3.module+el8.5.0+695+1fa8055e.x86_64
  rocky-logos-httpd-85.0-3.el8.noarch

Complete!

# 以上为装包信息
[class@master:~/https_server]$ mkdir users
[class@master:~/https_server]$ htpasswd -c users/secret xiaoming
New password:					# 输入用户密码:123
Re-type new password:			# 再次输入用户密码:123
Adding password for user xiaoming
[class@master:~/https_server]$ cat users/secret
xiaoming:$apr1$9q8mBQCp$mXoUJy6PHpRCjXpxrqw520

编写Playbook:vim https.yml

---
- name: Build an https website
  hosts: web
  vars:
    conf_src: /home/class/https_server/conf.d/
    conf_dest: /etc/httpd/conf.d/
    certs_src: /home/class/https_server/ssl_certs/
    certs_dest: /etc/pki/tls/certs/
    secret_src: /home/class/https_server/users/
    secret_dest: /usr/local/
    web_root: /var/www
  tasks:
    - name: Install packages
      yum:
        name:
          - httpd
          - mod_ssl
        state: present
    - name: Config web server; Make certs; Make users passwd
      copy:
        src: "{{ item.src }}"
        dest: "{{ item.dest }}"
      loop:
        - src: "{{ conf_src }}"
          dest: "{{ conf_dest }}"
        - src: "{{ certs_src }}"
          dest: "{{ certs_dest }}"
        - src: "{{ secret_src }}"
          dest: "{{ secret_dest }}"
    - name: Create index.html
      copy:
        content: "{{ ansible_facts.fqdn }}({{ ansible_facts.default_ipv4.address }})\n"
        dest: "{{ web_root }}/index.html"
    - name: Restart firewalld and httpd
      service:
        name: "{{ item }}"
        state: restarted
      loop:
        - firewalld
        - httpd
    - name: Allow https
      firewalld:
        service: https
        state: enabled

# Test web servers
- name: Test web servers
  hosts: localhost
  become: no
  tasks:
    - name: Connect web server
      uri:
        url: "https://{{ item }}"
        validate_certs: no
        force_basic_auth: yes
        user: xiaoming
        password: '123'
        return_content: yes
        status_code: 200
      loop:
        - node12
        - node13
      register: auth_test
    - debug:
        var: auth_test

在这里插入图片描述

运行 Ansible 文件:ansible-playbook https.yml
在这里插入图片描述

[class@master:~/https_server]$ ansible-playbook https.yml

PLAY [Build an https website] ****************************************************************

TASK [Gathering Facts] ***********************************************************************
ok: [node12]
ok: [node13]

TASK [Install packages] **********************************************************************
changed: [node13]
changed: [node12]

TASK [Config web server; Make certs; Make users passwd] **************************************
changed: [node12] => (item={'src': '/home/class/https_server/conf.d/', 'dest': '/etc/httpd/con                                                     f.d/'})
changed: [node13] => (item={'src': '/home/class/https_server/conf.d/', 'dest': '/etc/httpd/con                                                     f.d/'})
changed: [node12] => (item={'src': '/home/class/https_server/ssl_certs/', 'dest': '/etc/pki/tl                                                     s/certs/'})
changed: [node12] => (item={'src': '/home/class/https_server/users/', 'dest': '/usr/local/'})
changed: [node13] => (item={'src': '/home/class/https_server/ssl_certs/', 'dest': '/etc/pki/tl                                                     s/certs/'})
changed: [node13] => (item={'src': '/home/class/https_server/users/', 'dest': '/usr/local/'})

TASK [Create index.html] *********************************************************************
changed: [node12]
changed: [node13]

TASK [Restart firewalld and httpd] ***********************************************************
changed: [node12] => (item=firewalld)
changed: [node13] => (item=firewalld)
changed: [node12] => (item=httpd)
changed: [node13] => (item=httpd)

TASK [Allow https] ***************************************************************************
changed: [node12]
changed: [node13]

PLAY [Test web servers] **********************************************************************

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

TASK [Connect web server] ********************************************************************
ok: [localhost] => (item=node12)
ok: [localhost] => (item=node13)

TASK [debug] *********************************************************************************
ok: [localhost] => {
    "auth_test": {
        "changed": false,
        "msg": "All items completed",
        "results": [
            {
                "accept_ranges": "bytes",
                "ansible_loop_var": "item",
                "changed": false,
                "connection": "close",
                "content": "node12(192.168.32.12)\n",
                "content_length": "22",
                "content_type": "text/html; charset=UTF-8",
                "cookies": {},
                "cookies_string": "",
                "date": "Sat, 19 Feb 2022 13:32:52 GMT",
                "elapsed": 0,
                "etag": "\"16-5d85f08fc0b46\"",
                "failed": false,
                "invocation": {
                    "module_args": {
                        "attributes": null,
                        "backup": null,
                        "body": null,
                        "body_format": "raw",
                        "client_cert": null,
                        "client_key": null,
                        "content": null,
                        "creates": null,
                        "delimiter": null,
                        "dest": null,
                        "directory_mode": null,
                        "follow": false,
                        "follow_redirects": "safe",
                        "force": false,
                        "force_basic_auth": true,
                        "group": null,
                        "headers": {},
                        "http_agent": "ansible-httpget",
                        "method": "GET",
                        "mode": null,
                        "owner": null,
                        "password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
                        "regexp": null,
                        "remote_src": null,
                        "removes": null,
                        "return_content": true,
                        "selevel": null,
                        "serole": null,
                        "setype": null,
                        "seuser": null,
                        "src": null,
                        "status_code": [
                            "200"
                        ],
                        "timeout": 30,
                        "unix_socket": null,
                        "unsafe_writes": false,
                        "url": "https://node12",
                        "url_password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
                        "url_username": "xiaoming",
                        "use_proxy": true,
                        "user": "xiaoming",
                        "validate_certs": false
                    }
                },
                "item": "node12",
                "last_modified": "Sat, 19 Feb 2022 13:32:47 GMT",
                "msg": "OK (22 bytes)",
                "redirected": false,
                "server": "Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips",
                "status": 200,
                "url": "https://node12"
            },
            {
                "accept_ranges": "bytes",
                "ansible_loop_var": "item",
                "changed": false,
                "connection": "close",
                "content": "node13(192.168.32.13)\n",
                "content_length": "22",
                "content_type": "text/html; charset=UTF-8",
                "cookies": {},
                "cookies_string": "",
                "date": "Thu, 24 Feb 2022 10:12:53 GMT",
                "elapsed": 0,
                "etag": "\"16-5d8c0d2f4ea9c\"",
                "failed": false,
                "invocation": {
                    "module_args": {
                        "attributes": null,
                        "backup": null,
                        "body": null,
                        "body_format": "raw",
                        "client_cert": null,
                        "client_key": null,
                        "content": null,
                        "creates": null,
                        "delimiter": null,
                        "dest": null,
                        "directory_mode": null,
                        "follow": false,
                        "follow_redirects": "safe",
                        "force": false,
                        "force_basic_auth": true,
                        "group": null,
                        "headers": {},
                        "http_agent": "ansible-httpget",
                        "method": "GET",
                        "mode": null,
                        "owner": null,
                        "password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
                        "regexp": null,
                        "remote_src": null,
                        "removes": null,
                        "return_content": true,
                        "selevel": null,
                        "serole": null,
                        "setype": null,
                        "seuser": null,
                        "src": null,
                        "status_code": [
                            "200"
                        ],
                        "timeout": 30,
                        "unix_socket": null,
                        "unsafe_writes": false,
                        "url": "https://node13",
                        "url_password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
                        "url_username": "xiaoming",
                        "use_proxy": true,
                        "user": "xiaoming",
                        "validate_certs": false
                    }
                },
                "item": "node13",
                "last_modified": "Thu, 24 Feb 2022 10:12:48 GMT",
                "msg": "OK (22 bytes)",
                "redirected": false,
                "server": "Apache/2.4.37 (centos) OpenSSL/1.1.1k",
                "status": 200,
                "url": "https://node13"
            }
        ]
    }
}

PLAY RECAP ***********************************************************************************
localhost                  : ok=3    changed=0    unreachable=0    failed=0    skipped=0    re                                                     scued=0    ignored=0
node12                     : ok=6    changed=5    unreachable=0    failed=0    skipped=0    re                                                     scued=0    ignored=0
node13                     : ok=6    changed=5    unreachable=0    failed=0    skipped=0    re                                                     scued=0    ignored=0

返回信息中也有页面内容
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

1ta-chi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值