HCIP-openEuler V1.0 Lab Guide
HCIP-openEuler V1.0 Lab Guide
HCIP-openEuler
Lab Guide
ISSUE: 1.0
2
Copyright © Huawei Technologies Co., Ltd. 2024. All rights reserved.
No part of this document may be reproduced or transmitted in any form or by any
means without prior written consent of Huawei Technologies Co., Ltd.
and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd.
All other trademarks and trade names mentioned in this document are the property of
their respective holders.
Notice
The purchased products, services and features are stipulated by the contract made
between Huawei and the customer. All or part of the products, services and features
described in this document may not be within the purchase scope or the usage scope.
Unless otherwise specified in the contract, all statements, information, and
recommendations in this document are provided "AS IS" without warranties,
guarantees or representations of any kind, either express or implied.
The information in this document is subject to change without notice. Every effort has
been made in the preparation of this document to ensure accuracy of the contents, but
all statements, information, and recommendations in this document do not constitute
a warranty of any kind, express or implied.
Overview
This document is an HCIP-openEuler certification training course and is intended for
trainees who are going to take the HCIP-openEuler exam or readers who want to learn
how to build enterprise services, master shell scripts, or perform automated O&M using
Zabbix or Salt on openEuler and other Linux distributions.
Description
This lab guide describes five labs about how to set up Apache, NGINX, DNS, and MySQL
servers based on openEuler and how to perform LAMP-related operations through a
comprehensive lab.
⚫ Lab 1: Apache lab. This lab involves service installation and basic management,
helping you further understand Apache.
⚫ Lab 2: NGINX lab. This lab involves NGINX installation, static resource access, and
reverse proxy.
⚫ Lab 2: DNS lab. This lab combines lab 2 to configure forward and reverse DNS
resolution for the NGINX server.
⚫ Lab 4: MySQL lab. This lab involves how to install and perform basic operations on
MySQL, including adding, deleting, querying, and modifying MySQL.
⚫ Lab 5: Comprehensive lab. This lab describes how to set up WordPress, a LAMP
typical application, to help you further understand enterprise services.
In this environment, the EIPs of Server01, Server02, Server03, and Server04 are
124.70.153.72, 123.60.63.199, 121.37.184.67, and 124.70.167.64, respectively. See the
following figure.
For the ECS security group, allow both inbound and outbound traffic, as shown in the
following figure.
Contents
1 Apache Configurations
Log in to the installed openEuler, run the dnf install -y httpd command, and wait until
the installation is complete.
Run the httpd -t command to check whether the configuration file is correct.
Save the modification and exit. Check whether the configuration file is correct.
Run the systemctl enable httpd --now command to start the httpd service and set it to
start upon system startup. Then run the systemctl status httpd command to check the
httpd service status.
Step 4 Alternatively, use the following methods for testing the httpd service status:
Method 1:
Run the ss -lnp | grep 80 command to check whether port 80 is in the listening state.
Method 2:
Run the curl command on the HTTP server to access port 80.
Method 3:
Enter the EIP of the HTTP server in the address box of the browser and check whether
the test page is displayed.
1.1.2 Quiz
Check whether the test page can be accessed using method 3. If not, why?
The access may fail. If both methods 1 and 2 succeeded but method 3 failed, there is a
high probability that port 80 is not enabled on the HTTP server. In this case, check the
firewall or security group.
Requirement: Clients are allowed to access the HTTP server only through port 81 at the
server IP address (192.168.1.11).
HCIP-openEuler Lab Guide Page 4
Comment out the listening IP address and port number in the main configuration file, as
shown in the following figure.
Create a configuration file port.conf in /etc/httpd/conf.d and add the following content
to the file:
Listen 192.168.1.11:81
Run the curl 192.168.1.11:81, curl 192.168.1.11:80, and curl 127.0.0.1:81 commands to
check whether the test page can be accessed.
⚫ Question: If the content in the main configuration file is not commented out, can the
effect in the requirement be achieved?
Answer: No. If you do not comment out the content, clients can access the service
through port 80.
⚫ Question: Can I directly modify the main configuration file to achieve the effect
specified in the requirement?
Answer: Yes, you can. However, if the main configuration file is modified, it is difficult to
maintain the file. You are advised to add the mentioned configuration file to the conf.d
directory.
Run the systemctl reload httpd command and access the server again, as shown in the
following figure.
Requirement: Create the /home/source directory and move index.html to the directory
to enable the server to return "hello, openEuler".
Comment out the configuration of the directory for storing static resources in the main
configuration file, as shown in the following figure.
Create a home/source directory and cut the index.html file to the directory, as shown in
the following figure.
Create a configuration file source.conf in conf.d and enter the following content:
DocumentRoot "/home/source"
Run the systemctl reload httpd command and access the server again, as shown in the
following figure.
HCIP-openEuler Lab Guide Page 6
Add the following content to the source.conf file to grant the access permission on the
directory:
<Directory "/home/source">
AllowOverride None
# Allow open access:
Require all granted
</Directory>
Run the systemctl reload httpd command and access the server again. The result meets
the requirement, as shown in the following figure.
Change index.html to Index.html and access the service again. The system returns to
the test page, as shown in the following figure.
HCIP-openEuler Lab Guide Page 7
Add the following content to the source.conf file to change the static page name to
Index.html:
DirectoryIndex Index.html
Reload the configurations and try to access the service again, as shown in the following
figure.
1.2.2 Quiz
Can an HTTP server return different static pages for different users?
Yes, it can. This is the virtual host function of the Apache httpd service, which will be
introduced and implemented later.
1.3.2 Procedure
Step 1 Check the status of the mod_status module.
Run the httpd –M command to check whether mod_status is loaded. The command
output is as follows:
status_module (shared)
<Location /server-status>
SetHandler server-status
Order deny,allow
Deny from all
Allow from all
</Location>
ExtendedStatus On
Reload the Apache configurations, and enter EIP:81/server-status in the address box of
the browser to check the Apache status.
Reload the Apache configurations, and use EIP:81/server-status to access the Apache
again. The following information is displayed.
This module will be used in subsequent labs. Uncomment the line in step 4 and reload
the Apache configurations to restore the module.
Method 3: View the related configuration file, as shown in the following figure.
HCIP-openEuler Lab Guide Page 10
Comment out the configuration related to the event mode in the configuration file and
uncomment the configuration related to the worker mode, as shown in the following
figure.
Restart the httpd service and use method 2 in step 1 to check whether the configuration
takes effect, as shown in the following figure.
1.4.2 Quiz
⚫ After the MPM working mode is changed, can the modification take effect after the
Apache is reloaded? Why?
No, it cannot. You need to restart the service for the modification to take effect. The
MPM determines the working mode of the httpd processes and threads. You need to
restart the service to enable the systemd to create the corresponding processes.
⚫ Can I enable multiple working modes at the same time?
HCIP-openEuler Lab Guide Page 11
No, you cannot. If multiple working modes are enabled, the system displays the
following error message.
On the mod_status page, the value of keep-alive is 0, as shown in the following figure.
KeepAlive On
KeepAliveTimeout 20
MaxKeepAliveRequests 500
Reload the Apache configurations and check the value of keep-alive on the mod_status
page, as shown in the following figure.
HCIP-openEuler Lab Guide Page 12
1.5.2 Quiz
Does a longer persistent connection indicate better effect?
No, it does not. If a connection is occupied for a long time, the number of concurrent
connections increases, increasing the pressure on the server.
Create a test directory in /home/source, and create files test1 and test2 in test. Enter
"hello,test1" in test1, and soft link test1 to test2.
<Directory "/test">
Options Indexes
AllowOverride None
# Allow open access:
Require all granted
</Directory>
HCIP-openEuler Lab Guide Page 13
Reload the httpd service, enter EIP:81/test in the address box of the browser. The
following information is displayed.
Reload the httpd service and access the path again. The following information is
displayed.
HCIP-openEuler Lab Guide Page 14
⚫ Question: If there is no configuration file about /test, can I access the corresponding
resources through 192.168.1.11:81/test?
Answer: Yes, you can.
⚫ Question: If the Index.html file is created in the test directory, can I access the
corresponding resources through 192.168.1.11:81/test?
Answer: No, you cannot. The system returns the home page content, or indexes the
current directory only when the specified home page cannot be found in the directory.
Reload the httpd service, enter EIP:81/test2 in the address box of the browser. The
following information is displayed.
HCIP-openEuler Lab Guide Page 15
Add the following content to the configuration of the real directory of test2 in the
source.conf file:
<RequireAll>
Require all granted
Require not ip 192.168.38.1
</RequireAll>
Reload the Apache configurations and access the directory using the browser of the test
machine. The following information is displayed.
If you access the same directory on the server, the following information is displayed.
HCIP-openEuler Lab Guide Page 16
View the cause of the access failure of the test machine in logs. The details are as
follows.
Comment out the configuration added in step 1 in the source.conf file and add
AllowOverride All, as shown in the following figure.
<RequireAll>
Require all granted
Require not ip 192.168.38.1
</RequireAll>
HCIP-openEuler Lab Guide Page 17
Refer to step 2.
Run the following command to create a .passwd file in the directory where the resource
is located:
AuthType Basic
AuthName "http test"
AuthUserFile "/home/source/test/.passwd"
Require user test
Reload the Apache configurations and use a browser to access EIP:81/test2/. The system
prompts you to enter the authentication information, as shown in the following figure.
HCIP-openEuler Lab Guide Page 18
Enter the user name test and password Huawei@123. The static resources can be
accessed successfully, as shown in the following figure.
1.6.4 Quiz
Can the configuration of controlling static resource access permissions through accounts
be written to source.conf instead of .htaccess?
Yes, it can be controlled by AllowOverride.
cd /home/source
mkdir test{1..3}
Create the corresponding files in the directories and enter the corresponding contents.
Create a vhost.conf configuration file in the /etc/httpd/conf.d directory and enter the
following content:
<VirtualHost *:81>
ServerName www.test1.com
DocumentRoot "/home/source/test1"
DirectoryIndex test1
</VirtualHost>
<VirtualHost *:81>
ServerName www.test2.com
DocumentRoot "/home/source/test2"
DirectoryIndex test2
</VirtualHost>
<VirtualHost *:81>
ServerName www.test3.com
DocumentRoot "/home/source/test3"
DirectoryIndex test3
</VirtualHost>
There is no DNS server in the environment. Therefore, you need to manually configure
domain name resolution by adding the following content to the /etc/hosts file:
192.168.1.11 www.test1.com
192.168.1.11 www.test2.com
192.168.1.11 www.test3.com
Reload the configurations and run the following commands to perform a test:
curl www.test1.com:81
curl www.test2.com:81
curl www.test3.com:81
⚫ Question: Is there any log in error_log when an error is reported during the access to
www.test2.com:81?
Answer: No, there is no such log. The /etc/httpd/logs/error_log file does not store error
logs of virtual hosts, but the access_log file stores access logs of virtual hosts. To view
related logs, add the following configuration to the virtual host:
errorLog "logs/test1_error_log"
mkdir ca
cd ca
openssl genrsa -out ca.key 2048
openssl req -newkey rsa:4096 -nodes -sha256 -keyout ca.key -x509 -days 3650 -out ca.crt
HCIP-openEuler Lab Guide Page 22
openssl req -newkey rsa:4096 -nodes -sha256 -keyout www.test1.com.key -out www.test1.com.csr
openssl x509 -req -days 36500 -in www.test1.com.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out
www.test1.com.crt
vim /etc/httpd/conf.d/ssl.conf
Add a static resolution entry to the client to resolve www.test1.com to the EIP of
Server01.
Enter https://www.test1.com in the address box of the browser. The following page is
displayed.
Click Advanced and select Proceed to www.test1.com (unsafe). The following page is
displayed.
⚫ Question: Is the preceding page displayed after performing the preceding operations?
Why?
HCIP-openEuler Lab Guide Page 24
Answer: The preceding page may not be displayed. If port 443 of www.test1.com is not
configured on the virtual host, an error page is displayed.
HCIP-openEuler Lab Guide Page 25
2 NGINX Configurations
2.1.2 Procedure
Step 1 Install NGINX using the Yum repository.
After the installation is complete, run the following command to check the NGINX
version:
nginx -v
After confirming that the NGINX is correctly installed, run the following commands to
start NGINX and check whether the NGINX processes are started:
HCIP-openEuler Lab Guide Page 26
Enter the IP address of the NGINX server in the address box of the browser. The following
page is displayed.
The default global configurations in the main configuration file are as follows:
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
user nobody;
worker_processes 4;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
HCIP-openEuler Lab Guide Page 27
Run the following commands to reload the NGINX configurations and check the
processes:
nginx -s reload
ps -ef | grep nginx
The user of the worker processes changes to nobody, and the user of the master process
changes to root. In addition, the number of worker processes changes to 4.
Requirement: Use the domain name www.test.com to access the specified home page of
the NGINX service and the specified image file and TXT file.
Run the following command to create a directory for storing static resources:
mkdir -p /data/Nginx
touch /data/Nginx/index.html
echo "hello,openEuler" > /data/Nginx/index.html
touch /data/Nginx/test.txt
echo "hello,Nginx" > /data/Nginx/test.txt
cp /usr/share/nginx/html/nginx-logo.png /data/Nginx/
After the configuration is complete, the files in the Nginx directory are as follows:
In the /etc/nginx/conf.d directory, create a configuration file static.conf for the new
static website and configure the following content:
HCIP-openEuler Lab Guide Page 28
server {
listen 81;
server_name www.test.com;
root /data/Nginx;
index index.html;
}
Run the nginx -t command to check whether the configuration is correct. If the
configuration is incorrect, rectify the fault before performing subsequent operations. If
the configuration is correct, the following information is displayed.
After confirming that the information is correct, run the nginx -s reload command to
reload the service.
Configure static domain name resolution on the host where the browser is located to
map www.test.com to the server. Then access www.test.com:81 using the browser. The
following page is displayed.
⚫ Question 1: If a test.nn file is created in the Nginx directory and certain content is
entered, will the system return the corresponding content when the file is accessed
through www.test.com:81/test.nn? Why?
HCIP-openEuler Lab Guide Page 29
No, it will not. The .nn file is not in mime.type. Therefore, NGINX cannot parse the file.
When you access the URL, the corresponding file is downloaded to the local host by
default.
⚫ Question 2: To implement the same function of the preceding website, is there any
other writing format for the configuration file?
Yes, there is. You can refer to the following content:
server {
listen 81;
server_name www.test.com;
location / {
root /data/Nginx;
index index.html;
}
}
Create the nginx1, nginx2, and nginx3 directories in the /data directory.
mkdir nginx{1..3}
Run the following commands to create index.html in the three directories and enter
"hello,nginx1", "hello,nginx2", and "hello,nginx3" in the files:
server {
listen 81;
server_name localhost;
location / {
root /data/nginx1;
index index.html;
}
}
server {
listen 82;
server_name localhost;
location / {
root /data/nginx2;
index index.html;
}
}
server {
listen 83;
server_name localhost;
location / {
root /data/nginx3;
index index.html;
}
}
After the configuration is complete, run the nginx -t command to check whether syntax
errors exist. If no syntax error exists, run the nginx -s reload command to reload the
configurations.
Run the curl command to configure virtual hosts with different ports, as shown in the
following figure.
server {
listen 81;
HCIP-openEuler Lab Guide Page 31
server_name localhost;
location / {
root /data/nginx1;
index index.html;
}
}
server {
listen 82;
server_name localhost;
location /nginx2 {
root /data;
index index.html;
}
}
server {
listen 83;
server_name localhost;
location / {
root /data/nginx3;
index index.html;
}
}
Run the curl localhost:81, curl localhost:82, and curl localhost:83 commands. The
following information is displayed.
After you run the curl localhost:82/nginx2 command, the following information is
displayed.
HCIP-openEuler Lab Guide Page 32
server {
listen 81;
server_name localhost;
location ~* \.html$ {
root /data/Nginx1;
# index index.html;
}
}
server {
listen 82;
server_name localhost;
location = /nginx2/index.html {
root /data;
# index index.html;
}
}
server {
listen 83;
server_name localhost;
location = / {
root /data/nginx3;
index index.html;
}
}
Answer: Virtual host 1 uses a case-insensitive regular expression to match all resources
whose name extension is html. The corresponding URL is localhost:81. See the following
figure.
Virtual host 2 uses exact match to strictly match the required resource. The
corresponding URL is localhost:82/nginx2/index.html. See the following figure.
Virtual host 3 also uses exact match but the URL must end with a slash (/). However, the
actual path of the server is /data/nginx3/index.html. For this reason, the corresponding
resource cannot be accessed, and the system returns the default home page. See the
following figure.
server {
listen 81;
server_name localhost;
location /Nginx1 {
root /data;
index index.html;
}
}
server {
listen 82;
server_name localhost;
location /nginx2 {
alias /data/nginx2/index.html;
# index index.html;
}
}
server {
listen 83;
server_name localhost;
location = / {
HCIP-openEuler Lab Guide Page 34
root /data/nginx3;
index index.html;
}
}
server {
listen 81;
server_name localhost;
location / {
proxy_pass http://127.0.0.1:83;
# root /data;
# index index.html;
}
}
server {
listen 82;
server_name localhost;
location /nginx2 {
alias /data/nginx2/index.html;
# index index.html;
}
}
HCIP-openEuler Lab Guide Page 35
server {
listen 83;
server_name localhost;
location / {
root /data/nginx3;
index index.html;
}
}
Run the curl localhost:81 command to access the corresponding resource and check the
returned information, as shown in the following figure.
server {
listen 81;
server_name localhost;
location /nginx1 {
proxy_pass http://127.0.0.1:82/nginx2;
# root /data;
# index index.html;
}
}
server {
listen 82;
server_name localhost;
location /nginx2 {
alias /data/nginx2/index.html;
# index index.html;
}
}
server {
listen 83;
server_name localhost;
location / {
root /data/nginx3;
index index.html;
}
}
Run the curl localhost:81/nginx1 command to access the corresponding resource and
check the returned information, as shown in the following figure.
HCIP-openEuler Lab Guide Page 36
Restore the vhost.conf file to the content in step 2 in section "Configuring Virtual Hosts."
The details are as follows:
server {
listen 81;
server_name localhost;
location / {
root /data/nginx1;
index index.html;
}
}
server {
listen 82;
server_name localhost;
location / {
root /data/nginx2;
index index.html;
}
}
server {
listen 83;
server_name localhost;
location / {
root /data/nginx3;
index index.html;
}
}
Restore Nginx1 to nginx1. After the restoration, the /data directory is as follows.
Reload the NGINX configurations and check whether the services corresponding to the
virtual hosts can be accessed, as shown in the following figure.
Create a load balancing configuration file lb.conf in the conf.d directory and enter the
following content:
upstream www.test.com {
server 192.168.1.12:81;
server 192.168.1.12:82;
server 192.168.1.12:83;
}
server {
location / {
proxy_pass http://www.test.com;
}
}
After the configuration is complete, reload the NGINX configurations and manually add
the static domain name resolution of www.test.com to /etc/hosts, as shown in the
following figure.
Run the curl www.test.com command on the server for multiple times and check the
returned information, as shown in the following figure.
It can be observed that each request is served by the three virtual hosts in turn.
Modify the lb.conf file to add weights for load balancing as follows:
upstream www.test.com {
server 192.168.1.12:81 weight=2;
server 192.168.1.12:82 weight=1;
server 192.168.1.12:83;
}
server {
location / {
proxy_pass http://www.test.com;
}
HCIP-openEuler Lab Guide Page 38
Run the curl www.test.com command on the server for multiple times and check the
returned information, as shown in the following figure.
The three virtual hosts provide services based on the configured weights.
upstream www.test.com {
server 192.168.1.12:81 backup;
server 192.168.1.12:82;
server 192.168.1.12:83;
}
server {
location / {
proxy_pass http://www.test.com;
}
}
Run the curl www.test.com command on the server for multiple times and check the
returned information, as shown in the following figure.
HCIP-openEuler Lab Guide Page 39
You can see that NGINX does not forward requests to virtual host 1.
Run the curl www.test.com command on the server for multiple times and check the
returned information, as shown in the following figure.
upstream www.test.com {
server 192.168.1.12:81 backup;
server 192.168.1.12:82;
server 192.168.1.12:83 down;
}
server {
location / {
proxy_pass http://www.test.com;
}
}
What is returned by the system when you run the curl www.test.com command to
request a resource? Why?
Answer: The system returns "hello,nginx2". Because virtual host 3 is down but virtual
host 2 is still available, NGINX does not forward the request to backup virtual host 1 and
the system thus returns the resource provided by virtual host 2. See the following figure.
HCIP-openEuler Lab Guide Page 40
HCIP-openEuler Lab Guide Page 41
3 DNS Configurations
3.1 Introduction
3.1.1 About This Lab
This lab is based on section "Configuring Load Balancing with NGINX." The DNS server is
used to replace the original static DNS to provide services for the client.
Wait until the installation is complete and run the following command to start DNS-
related services:
If no error message is displayed, check whether the port used by DNS is listened on, as
shown in the following figure.
Bind provides the administrator with a template file for configuring resource records. The
file is stored in the /var/named directory and named named.localhost. Run the cp
command to copy the file as test.com.zone. The details are as follows:
cd /var/named
cp named.localhost test.com.zone -p
$TTL 1D
@ IN SOA master.test.com. admin.test.com. (
0 ; serial
1D ; refresh
1H ; retry
1W ; expire
3H ) ; minimum
NS master
master A 192.168.1.13
www CNAME main
main A 192.168.1.12
After the preceding configurations are complete, run the named-checkconf command to
check whether the DNS configuration file is correct, and run the named-checkzone
test.com /var/named/test.com.zone command to check whether the test.com zone
configuration is correct, as shown in the following figure.
If all configurations pass the check, run the rndc reload command to reload the DNS
service configurations, as shown in the following figure.
On the VM of the NGINX server, run the following commands (change ens33 in the
commands as required) to point the DNS server address to the newly configured server:
To ensure the lab effect, manually set the DNS server address of the VPC where the ECS
resides to 192.168.1.13, as shown in the following figure.
HCIP-openEuler Lab Guide Page 44
After the configuration is complete, run the nslookup command to check whether the
DNS service can correctly resolve www.test.com to 192.168.1.12, as shown in the
following figure.
Run the curl command to access www.test.com, as shown in the following figure.
Bind provides the administrator with a template file for configuring resource records. The
file is stored in the /var/named directory and named named.loopback. Run the cp
command to copy the file as 192.168.1.zone. The details are as follows:
cd /var/named
cp named.loopback 192.168.1.zone -p
$TTL 1D
@ IN SOA master.test.com. admin.test.com. (
0 ; serial
1D ; refresh
1H ; retry
1W ; expire
3H ) ; minimum
NS master
master A 192.168.1.13
12 PTR www.test.com
Check whether the configurations are correct, as shown in the following figure.
If no error is found, run the rndc reload command to reload the DNS configuration file.
Log in to the NGINX server and run the nslookup command to check whether the
configurations take effect.
HCIP-openEuler Lab Guide Page 46
4 MySQL Configurations
Run the following command on openEuler to check the MySQL version supported by the
Yum repository of openEuler:
According to the query result, you can install MySQL 8.0.x or 5.7.x.
Run the yum command to install MySQL-server, as shown in the following figure.
After the installation is complete, run the systemctl start mysqld command to start the
service and check whether the corresponding port is listened on, as shown in the
following figure.
HCIP-openEuler Lab Guide Page 48
After the installation is complete, run the mysql command to log in to the MySQL
database, as shown in the following figure.
⚫ Question: What are the user name and password for logging in to the MySQL
database?
Answer:
The current user is root. After 8.0.x is installed, the default password of user root is
empty. Therefore, you can log in to the MySQL database without entering the password.
However, the permission is low. You must initialize the password before performing the
next step.
In MySQL 5.7, the password of user root is not empty and is automatically generated by
the system. You can view the password in the /var/log/mysql/mysqld.log file.
After the modification is complete, exit the MySQL database and log in to the MySQL
database as user root again.
HCIP-openEuler Lab Guide Page 49
Run the show databases; command to view the default databases, as shown in the
following figure.
Run the select user,host from mysql.user; command to view the information about the
current system user, as shown in the following figure.
Use the status statement to check the status of the MySQL database.
Use the processlist statement to view the active threads of the MySQL database.
Use the ping statement to check whether the MySQL server is normal.
Create user vegetables_usser and allow it to perform SELECT query on the database. In
addition, create user vegetables_admin and grant it all permissions on the database.
After the creation is complete, view information about the created database.
Use the USE statement to access the database, and then use the SELECT statement to
view information about the database.
When creating a table, set ID to the primary key and set Name and PIC to NOT NULL.
mysql> CREATE TABLE Vegetables ( ID SMALLINT UNSIGNED PRIMARY KEY , Name VARCHAR(10)
NOT NULL , Price DECIMAL(5, 2) , Qty DECIMAL(7, 2) , PIC VARCHAR(10) NOT NULL );
To make the statement structure clearer, you can also write it as follows:
After the table is created, use related statements to view information about the table,
such as SHOW and SELECT.
HCIP-openEuler Lab Guide Page 53
After the table is added, view data in the table, as shown in the following figure.
HCIP-openEuler Lab Guide Page 54
⚫ Question: Why are the values in Price and Qty automatically saved to two decimal
places?
Answer: When the table is created, the DECIMAL modifier is added to Price and Qty to
make the values accurate to two decimal places.
Query information about the vegetables managed by Jim from the table.
Query information about the vegetables managed by Jim or Tom from the table.
Query information about the vegetables whose prices are higher than 7.00 and quantity
is less than 180.
Query information about the vegetables managed by the salesmen whose names start
with T (fuzzy query).
Create users vegetable_user and vegetable_admin as planned and set their passwords
to Huawei@123.
⚫ Question: Are there any deficiencies in the users created by running the preceding
commands? How do you make up for such deficiencies?
Answer: The users created by running the preceding commands can log in to the
database only on the local host but cannot log in to the database over the Internet.
When creating a user, you can specify the hosts or network segments that are allowed to
log in to the MySQL database. For example, to allow the 192.168.1.0 network segment,
use the following statement:
Log out of user root, log in to the database as users vegetable_admin and
vegetable_user, and check whether the configurations take effect. Log in to the
database as user vegetable_user.
Step 7 Modify and delete the database, data tables, and users.
Log in to the MySQL database as user root and delete users vegetable_user and
vegetable_admin.
5 LAMP Practices
5.1 Introduction
This lab uses Server01 and Server04 to set up a WordPress server developed in PHP.
After the installation is complete, run the following command to check whether the
installation is correct:
php -v
Add the PHP configuration to the Apache main configuration file as follows.
HCIP-openEuler Lab Guide Page 61
To prevent interference, back up or delete all configurations in the previous labs. For
example, copy all sub-configuration files in conf.d to the new conf.bk directory and
retain only the php.conf file related to PHP.
cd /etc/httpd/conf.d
mkdir conf.bk && mv * conf.bk/
mv conf.bk/php.conf .
After the configuration is complete, the files in the conf.d directory are as follows.
Create index.php in the root directory of httpd to test whether Apache and PHP can
work properly. The content of index.php is as follows:
<?php
phpinfo();
?>
If the page is not displayed, check whether the php-fpm service is normal, as shown in
the following figure.
This lab uses user root for testing. Check whether user root has the required permissions,
as shown in the following figure.
If user root is not allowed to access all other hosts or the Apache host, complete the
configuration by referring to the MySQL section.
After checking the permissions of user root, run the following commands on the Apache
host to install and connect to the MySQL server:
Create a conn_mysql.php file in the root directory of httpd and enter the following
content:
<?php
$con = mysqli_connect("192.168.1.14","root","Huawei@123");
if ($con)
echo 'OK';
else
echo 'NOT OK';
$con->close();
?>
Run the following commands on the Apache host to download the WordPress installation
package:
cd /home
mkdir wordpress
wget https://wordpress.org/latest.tar.gz
mv latest.tar.gz wordpress/
cd wordpress/
tar -xzf latest.tar.gz
HCIP-openEuler Lab Guide Page 65
If the tar command is not available, install it using the Yum repository.
Create a dedicated user named wp for the database and grant the read and write
permissions on the database to the user.
After the configuration is complete, check whether you can access the database as user
wp on the Apache host.
cd /home/wordpress/wordpress/
cp -r * /var/www/html
ls /var/www/html
⚫ Note: During the copy, the system asks you whether to overwrite the original
index.php file. Enter y to overwrite the original index.php file. Alternatively, back up
the original index.php file and copy the file again.
After the copy is complete, enter http://Apache_server_EIP/wp-admin/install.php in the
address box of the browser to start installation, as shown in the following figure.
Click Let's go to start installation. On the next page, enter the MySQL database
information, as shown in the following figure.
HCIP-openEuler Lab Guide Page 67
Click Submit. A message is displayed, indicating that the WordPress configuration file
wp-config.php cannot be found and needs to be manually created, as shown in the
following figure.
After the configuration is complete, click Install WordPress. After the installation is
complete, the following page is displayed.
Click Log In and enter the user name and password to log in, as shown in the following
figure.
HCIP-openEuler Lab Guide Page 69
Click Log In to log in to the home page, as shown in the following figure.
---------End---------
Huawei openEuler Certification Training
HCIP-openEuler
Lab Guide
Issue: 1.0
2
Copyright © Huawei Technologies Co., Ltd. 2024. All rights reserved.
No part of this document may be reproduced or transmitted in any form or by any
means without prior written consent of Huawei Technologies Co., Ltd.
and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd.
All other trademarks and trade names mentioned in this document are the property of
their respective holders.
Notice
The purchased products, services and features are stipulated by the contract made
between Huawei and the customer. All or part of the products, services and features
described in this document may not be within the purchase scope or the usage scope.
Unless otherwise specified in the contract, all statements, information, and
recommendations in this document are provided "AS IS" without warranties,
guarantees or representations of any kind, either express or implied.
The information in this document is subject to change without notice. Every effort has
been made in the preparation of this document to ensure accuracy of the contents, but
all statements, information, and recommendations in this document do not constitute
a warranty of any kind, express or implied.
Overview
This document is intended for trainees preparing for the HCIP-openEuler certification
exam and those who are interested in building enterprise services and shell scripts or
performing automated O&M using Zabbix or Salt on openEuler and other Linux
distributions.
Description
This lab guide consists of five labs, starting from basic device configurations, and
describes how to install and configure cluster software on openEuler, including the Linux
Virtual Server (LVS), NGINX, HAProxy, and Keepalived.
⚫ Lab 1: LVS configuration
➢ This lab employs the LVS-NAT and LVS-DR modes to balance the loads of web
servers.
⚫ Lab 2: NGINX reverse proxy and load balancing configuration
➢ This lab mainly introduces load balancing algorithms.
⚫ Lab 3: HAProxy configuration
➢ This lab focuses on how to use the monitoring function of HAProxy, configure
HAProxy logs, and configure the access control feature of HAProxy.
⚫ Lab 4: Keepalived configuration
➢ This lab uses Keepalived to provide high availability (HA) for NGINX and
implement an NGINX cluster together with LVS.
⚫ Lab 5: Redis operations
➢ This lab involves addition, deletion, query, and modification operations and
applies Redis in WordPress.
Contents
1 LVS Configuration
1.1.2 Networking
This lab requires four ECSs that functions as the client, LVS, Nginx1, and Nginx2. The
virtual IP address (VIP) of the LVS is 192.168.1.10/24, and its director IP address (DIP) is
10.0.0.10/24. The real IP address (RIP) of Nginx1 is 10.0.0.2/24, and the RIP of Nginx2 is
10.0.0.3/24. The RIPs are accessed by the client, as shown in the following figure.
HCIP-openEuler Lab Guide Page 2
On Huawei Cloud, subnet 1 and subnet 2 are two subnets in the same virtual private
cloud.
1.1.3 Procedure
Step 1 Configure Nginx1 and Nginx2.
Set the gateway of Nginx1 and Nginx2 to the LVS DIP according to the preceding
figure. Command example:
Note: After the modification is done, the network will be interrupted. Log in to the ECS
using VNC and perform following operations.
Configure Nginx1 and Nginx2 based on the knowledge in course 1. It is required that the
system returns "hello,10.0.0.2" when port 80 of Nginx1 is accessed and "hello,10.0.0.3"
port 80 of Nginx2 is accessed. Example:
Configure two NICs for the LVS ECS, one for the VIP and the other for the DIP. The DIP is
an intranet IP address and does not need a gateway. The VIP is a public IP address and
needs to be configured with gateway information. In addition, to ensure normal IP
forwarding, disable the Source/Destination Check item, as shown in the following
figure.
After the configuration, test whether Nginx1 and Nginx2 can be accessed.
After the installation is complete, create a configuration file required for starting
ipvsadm.
[root@Cluster1 ~]# touch /etc/sysconfig/ipvsadm
Start the service and check whether the service is started normally.
If the service is started properly, run the following command to create a cluster using the
round robin algorithm:
On the ECS where the LVS resides, use the LVS VIP to repeatedly access the web service.
The following information is displayed:
Or, use different browsers on the local PC to repeatedly access the EIP of the ECS and
view the responses.
It shows that the LVS forwards the requests to Nginx1 and Nginx2 in round robin mode
and returns the corresponding contents to the client.
⚫ Question: Is it mandatory to set the gateway of Nginx1 and Nginx2 to the LVS DIP?
Answer: Yes.
⚫ Task: Change the LVS algorithm to weighted round robin.
Log in to the client ECS, use the LVS VIP to repeatedly access the web service. The
following information is displayed:
As shown in the preceding figure, the LVS algorithm has been changed to weighted
round robin.
1.2.2 Networking
This lab requires four ECSs, one as the LVS, two as the NGINX servers, and the other as
the client. The NGINX servers in the previous lab can be reused. The LVS requires only
one NIC. Remove the NIC corresponding to 10.0.0.10 and change the IP address of the
NIC where 192.168.1.10 is located to 10.0.0.10. The two NGINX servers and the LVS are in
the same subnet, and the client is in another subnet. Configure dummy interfaces on the
NGINX servers and the LVS to carry VIPs.
HCIP-openEuler Lab Guide Page 6
1.2.3 Procedure
Step 1 Configure Nginx1 and Nginx2.
nmcli connection add type dummy ifname dummy2 ipv4.method manual ipv4.addresses 10.0.0.100/32
Run the following commands to change the RIP gateway address to the router interface
address:
After the network configuration is complete, modify the ARP kernel parameters.
net.ipv4.conf.all.arp_announce = 2
net.ipv4.conf.dummy2.arp_ignore = 1
net.ipv4.conf.dummy2.arp_announce = 2
EOF
After the configuration is complete, run the sysctl -p command for the configuration to
take effect.
If the LVS in the previous lab is reused in this lab, remove the existing configurations.
Run the following command to delete the LVS configuration added in the preceding lab:
ipvsadm -D -t 192.168.1.10:80
After the deletion, run the following command to add VIP configurations:
nmcli connection add type dummy ifname dummy2 ipv4.method manual ipv4.addresses 10.0.0.100/32
Run the following commands to set the DIP gateway address to the router interface
address:
If the LVS is newly created, you only need to add the VIP configurations and change the
gateway address.
ipvsadm -A -t 10.0.0.100:80 -s rr
ipvsadm -a -t 10.0.0.100:80 -r 10.0.0.3
ipvsadm -a -t 10.0.0.100:80 -r 10.0.0.2
⚫ Question: What information in the preceding figure indicates that the current mode
is DR?
Answer: Route in the Forward column.
Log in to the client ECS, use the LVS VIP to repeatedly access the web service. The
following information is displayed:
It shows that the LVS forwards the requests to Nginx1 and Nginx2 in round robin mode
and returns the page to the client.
HCIP-openEuler Lab Guide Page 9
2.1 Introduction
This lab uses multiple NGINX algorithms to implement load balancing on backend servers
and demonstrates the effect to enhance understanding of each algorithm.
2.2 Networking
In this lab, four ECSs are used. The two NGINX servers and the client in the LVS
configuration lab can be reused. An NGINX proxy server needs be created. You can also
reuse the LVS in the LVS configuration lab after clearing its configurations. The following
figure shows the topology.
HCIP-openEuler Lab Guide Page 10
2.3 Procedure
Step 1 Check whether the resources are available.
On the client, ping the IP address in segment 10 of the proxy server and ensure that the
network connection between them is normal, as shown in the following figure.
Access the two NGINX servers on the proxy server to ensure that the NGINX servers are
available, as shown in the following figure.
Install NGINX on the proxy server based on the knowledge in course 1, and then start the
NGINX service, as shown in the following figure.
Create a proxy and load balancing configuration file in the NGINX configuration file sub-
directory of the proxy server and add the following configurations to the file:
upstream 10.0.0.10 {
server 10.0.0.2:80;
server 10.0.0.3:80;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://10.0.0.10;
}
}
After the configuration, run the nginx -s reload command to reload the NGINX service.
HCIP-openEuler Lab Guide Page 11
Access 10.0.0.1 from the client. If the configuration is correct, the following information is
displayed:
To amplify the algorithm effect, add virtual hosts for the two NGINX servers.
Configuration example:
server {
listen 0.0.0.0:80;
root /data/Nginx/;
server_name localhost;
index index80.html;
}
server {
listen 0.0.0.0:81;
root /data/Nginx/;
server_name localhost;
index index81.html;
}
server {
listen 0.0.0.0:82;
root /data/Nginx/;
server_name localhost;
index index82.html;
}
Configuration example:
upstream 10.0.0.10 {
server 10.0.0.2:80;
server 10.0.0.2:81;
server 10.0.0.2:82;
server 10.0.0.3:80;
server 10.0.0.3:81;
HCIP-openEuler Lab Guide Page 12
server 10.0.0.3:82;
}
Modify to the configuration file of the proxy server as follows to change the algorithm to
IP Hash:
upstream 10.0.0.10 {
ip_hash;
server 10.0.0.2:80;
server 10.0.0.2:81;
……
}
…….
Reload NGINX configurations and perform a test on the client. The result is as follows:
Create test files in the root directory on the two NGINX servers.
Run the following command on Nginx2:
Load NGINX configurations and access the test.txt file from the client. The result is as
follows:
HCIP-openEuler Lab Guide Page 13
Reload NGINX configurations and access the test.txt file from the client. The result is as
follows:
⚫ Question: After the algorithm is set to Random, will the test result be exactly the
same as the preceding figure?
Answer: Not exactly. As the algorithm name indicates, the requests are scheduled to
randomly selected servers.
Modify the configuration file of the proxy server. Set all virtual hosts of Nginx2 to
backup and assign a weight for the virtual hosts of Nginx1. Configuration example:
HCIP-openEuler Lab Guide Page 15
Reload NGINX configurations and perform a test on the client. The result is as follows:
Modify the configuration file on the proxy server and change the status of some virtual
hosts of Nginx2 to down. Configuration example:
Reload NGINX configurations and perform a test on the client. The result is as follows:
HCIP-openEuler Lab Guide Page 16
3 HAProxy Configuration
3.1 Introduction
This lab consists of multiple sub-labs to show various HAProxy functions.
3.2 Networking
This lab requires four ECSs, one as the HAProxy server, two as the NGINX servers, and the
other as the client. The NGINX servers in the previous lab can be reused, and their
configurations after the previous lab is complete can be retained. Each NGINX runs three
virtual hosts. HAProxy uses two NICs to connect to the intranet and public network
respectively. The following figure shows the topology.
HCIP-openEuler Lab Guide Page 17
3.3 Procedure
3.3.1 Implementing Basic Load Balancing with HAProxy
Step 1 Install HAProxy.
frontend main
bind *:80
default_backend http_back
backend http_back
balance roundrobin
server node1 10.0.0.2:80 check
server node2 10.0.0.2:81 check
server node3 10.0.0.2:82 check
server node4 10.0.0.3:80 check
server node5 10.0.0.3:81 check
server node6 10.0.0.3:82 check
After the configuration, run the systemctl restart haproxy command to restart the
HAProxy service. Then access HAProxy from the client. If the configuration is correct, the
result is as follows:
HCIP-openEuler Lab Guide Page 18
In the listen section in the HAProxy configuration file, configure GUI-based HAProxy
monitoring.
listen admin_stat
bind 0.0.0.0:8443
mode http
stats refresh 30s
stats uri /haproxy_stats
stats realm Haproxy\ Statistics
stats auth openEuler:Huawei@123
stats hide-version
admin_stat indicates the user-defined name, refresh 30s indicates the refresh frequency,
uri /haproxy_stats indicates the URI to the monitoring page, and
openEuler:Huawei@123 indicates the authentication information for logging in to this
page.
After the configuration is complete, restart the HAProxy service. Open a browser on the
PC, enter http://EIP:8443/haproxy_stats in the address box, and press Enter. In the
displayed dialog box, enter the user name and password to log in to the monitoring
page.
HCIP-openEuler Lab Guide Page 19
HAProxy logs can be defined in the global, default, or frontend section. This lab uses
global as an example. Add log configuration information to the HAProxy configuration
file as follows:
global
log 127.0.0.1 local3 info
chroot /var/lib/haproxy
pidfile /var/run/haproxy.pid
user haproxy
group haproxy
daemon
maxconn 4000
local3.* /var/log/haproxy.log
$ModLoad imudp
$UDPServerRun 514
After steps 1 and 2 are complete, restart the HAProxy and rsyslog services. After the
restart, the system automatically creates a log file, as shown in the following figure.
Enable the firewall on Nginx2 and check whether the corresponding logs are generated,
as shown in the following figure.
HCIP-openEuler Lab Guide Page 20
⚫ Task: Log in to the monitoring page and check whether the status of the monitored
hosts changes.
Expected result: The status of the monitored hosts changes to DOWN, as shown in the
following figure.
frontend main
bind *:80
acl test url_reg -i \.txt$
use_backend test if test
default_backend http_back
backend http_back
balance roundrobin
server node1 10.0.0.2:80 check
server node2 10.0.0.2:81 check
server node3 10.0.0.2:82 check
server node4 10.0.0.3:80 check
server node5 10.0.0.3:81 check
server node6 10.0.0.3:82 check
backend test
balance roundrobin
server test1 10.0.0.2:80/test.txt check
server test2 10.0.0.3:80/test.txt check
After the configuration, restart the HAProxy service and perform a test on the client. The
result is as follows:
HCIP-openEuler Lab Guide Page 21
4 Keepalived Configuration
4.1.2 Networking
This lab requires three ECSs. Nginx1 and Nginx2 in the previous lab can be reused to run
the NGINX service, and Keepalived is used to virtualize a host for client access. Nginx1
and Nginx2 detect each other's heartbeat through network segment 10 and provide
services through floating IP address 192.168.1.20. If one host or the NGINX process on it
is down, services are automatically switched to the other host. The following figure shows
the topology.
HCIP-openEuler Lab Guide Page 23
Nginx1 and Nginx2 use two network interfaces. Configure them as planned, which will
not be described in the following steps.
4.1.3 Procedure
Step 1 Install Keepalived.
On Nginx1, ping Nginx2. If the network connection is normal, the following information
is displayed:
In this lab, Nginx1 is configured as the master node and Nginx2 is configured as the
backup node. Modify the Keepalived configuration file
(/etc/keepalived/keepalived.conf) on Nginx1 as follows:
global_defs {
router_id Nginx1
}
HCIP-openEuler Lab Guide Page 24
vrrp_instance Nginx {
state MASTER
interface ens192
virtual_router_id 51
priority 225
advert_int 1
authentication {
auth_type PASS
auth_pass Huawei@1
}
virtual_ipaddress {
192.168.1.20/24
}
}
global_defs {
router_id Nginx2
}
vrrp_instance Nginx {
state BACKUP
interface ens192
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass Huawei@1
}
virtual_ipaddress {
192.168.1.20/24
}
}
After the configuration is complete, run the following command on Nginx1 and Nginx2
to restart the Keepalived service:
On the client, use the floating IP address to access the NGINX service. The result shows
that Nginx1 responds to all the requests and returns the corresponding contents.
Shut down Nginx1 and use the floating IP address to access NGINX again. The result is as
follows:
Currently, Keepalived can switch services only based on whether the master node breaks
down. If only the NGINX service is faulty, Keepalived cannot switch services. Therefore,
configure a health check in Keepalived to check whether NGINX is available.
Start Nginx1 that is shut down in step 4 and add health check configurations to the
Keepalived configuration files of Nginx1 and Nginx2. The details are as follows:
global_defs {
router_id Nginx1
}
vrrp_script nginx_check {
script "/etc/keepalived/check.sh"
interval 1
weight -5
fail 3
}
HCIP-openEuler Lab Guide Page 26
vrrp_instance Nginx {
……
track_script {
nginx_check
}
}
Create a check.sh script for checking NGINX service status in /etc/keepalived on the two
NGINX servers. The script contents are as follows. Note: To prevent errors, do not directly
copy and paste the following contents.
#!/bin.bash
systemctl status nginx | grep "active (running)" > /dev/null
if [ $? -ne 0 ]; then
systemctl restart nginx &> /dev/null
sleep 1
systemctl status nginx | grep "active (running)" > /dev/null
if [ $? -ne 0 ]; then
systemctl stop keepalived
else
exit
fi
fi
After the configuration is complete, run the systemctl restart keepalived command to
restart the service. Modify the NGINX configuration file on Nginx1 so that the NGINX
process cannot be started properly (for example, rename the nginx.conf file
nginx.conf.bk). Then manually stop the NGINX service.
Run the systemctl start nginx command and ensure that NGINX cannot be started, as
shown in the following figure.
Perform the test on the client. It shows that Nginx2 provides services.
HCIP-openEuler Lab Guide Page 27
4.2.2 Networking
This lab requires five ECSs. Nginx1 and Nginx2 in the previous lab can be reused, but you
need to reconfigure IP addresses as planned in the topology below and uninstall
Keepalived. IP address configuration procedure will not be described.
LVS1 and LVS2 form an HA cluster through Keepalived and provide load balancing for
backend servers Nginx1 and Nginx2.
4.2.3 Procedure
Step 1 Install Keepalived and ipvsadm on LVS1 and LVS2 ECSs.
global_defs {
router_id Cluster1
}
vrrp_instance Nginx {
state MASTER
interface ens192
mcast_src_ip 20.0.0.1
virtual_router_id 51
priority 255
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.1.20/24
}
}
virtual_server 192.168.1.20 80 {
delay_loop 6
lb_algo rr
lb_kind DR
persistence_timeout 50
protocol TCP
real_server 192.168.1.14 80 {
weight 1
TCP_CHECK {
connect_timeout 3
retry 3
delay_before_retry 3
}
}
real_server 192.168.1.15 80 {
weight 2
TCP_CHECK {
connect_timeout 3
retry 3
delay_before_retry 3
}
}
}
global_defs {
router_id Cluster2
}
vrrp_instance Nginx {
state BACKUP
interface ens192
mcast_src_ip 20.0.0.2
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.1.20/24
}
}
virtual_server 192.168.1.20 80 {
delay_loop 6
lb_algo rr
lb_kind DR
persistence_timeout 50
protocol TCP
real_server 192.168.1.14 80 {
weight 1
TCP_CHECK {
connect_timeout 3
retry 3
delay_before_retry 3
}
}
real_server 192.168.1.15 80 {
weight 2
TCP_CHECK {
connect_timeout 3
retry 3
delay_before_retry 3
}
}
}
After the two LVS servers are configured, restart them and perform an access test on the
client. The result is as follows:
HCIP-openEuler Lab Guide Page 30
Restart the Keepalived service and perform a test again. The test result is as follows:
HCIP-openEuler Lab Guide Page 31
5.1 Introduction
This lab shows how to install Redis in standalone mode and perform some simple Redis
operations, such as creating, querying, and modifying keys.
After the installation is complete, run the systemctl start redis command to start the
Redis service.
HCIP-openEuler Lab Guide Page 32
Run the redis-cli command to log in to Redis, as shown in the following figure.
keys *
Run the get command to view the value of a key. For example:
Run the expire command to set the expiration time of a key. For example:
expire test1 2
Run the move command to migrate a key value to another database. For example:
HCIP-openEuler Lab Guide Page 33
⚫ Question: Does the data still exist in Redis after the ECS is restarted in the current
state?
Answer: Yes. By default, Redis automatically generates a dump.rdb file, which is a
memory snapshot.
After the modification, restart the Redis service and check whether the password takes
effect.
Modify the Redis configuration file, set dbfilename to snapshot.rdb, and set dir to a
directory that stores this file, as shown in the following figure.
HCIP-openEuler Lab Guide Page 34
Run the save command to set the RDB policy. In the following figure, 10 indicates that a
snapshot is saved if one key changes within 10 seconds (line 386 in the configuration
file).
After the modification is complete, restart the Redis service, go to Redis, and manually
create two keys. The system creates a snapshot file in the specified directory, as shown in
the following figure.
HCIP-openEuler Lab Guide Page 35
5.3.2 Networking
This lab requires four ECSs. Redis in the preceding lab can be reused, and Nginx1 in other
labs can be reused as the WordPress server. A browser needs to be installed on the client.
The following figure shows the topology and address planning.
5.3.3 Procedure
Step 1 Preconfigure Redis.
Modify the configuration file (line 75) so that Redis can be accessed over the network.
HCIP-openEuler Lab Guide Page 36
After the configuration is complete, restart the server and check whether the
configuration takes effect.
On WordPress, run the yum install -y php command to install PHP and its dependencies.
After the installation is complete, add listen = 9000 under listen.allowed_clients =
127.0.0.1 in the /etc/php-fpm.d/www.conf file, as shown in the following figure.
Run the systemctl restart php-fpm command to restart PHP and check whether port
9000 is enabled.
server {
listen 0.0.0.0:80;
root /data/WordPress;
#server_name localhost;
index index.php;
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
Create a directory /data/WordPress, create a test file index.php in this directory, and
add the following contents to the file:
<?php
phpinfo();
?>
HCIP-openEuler Lab Guide Page 37
Restart the NGINX service and access the PHP page in the client browser to check
whether the page can be displayed.
This lab uses user root for testing. Check whether user root has the required permissions,
as shown in the following figure.
If user root is not allowed to access all other hosts or the WordPress host, complete the
configuration by referring to the MySQL section.
After checking the permissions of user root, run the following commands on the
WordPress host to install and connect to the MySQL server:
After the login is successful, run the following command on WordPress to install the PHP
driver for MySQL:
HCIP-openEuler Lab Guide Page 38
<?php
$con = mysqli_connect("192.168.1.8","root","Huawei@123");
if ($con)
echo 'OK';
else
echo 'NOT OK';
$con->close();
?>
Install and test WordPress by following the instructions in "Installing and Testing
WordPress" in course 1.
Add the following content to the end of the WordPress configuration file wp-config:
define("FS_METHOD", "direct");
define("FS_CHMOD_DIR", 0777);
define("FS_CHMOD_FILE", 0777);
Run the following command to modify the permission on the WordPress directory:
On the displayed page, enter Redis Object Cache in the search box and click Install Now
in the search result, as shown in the following figure.
After the installation is complete, add the Redis configuration information to the
WordPress configuration file wp-config.php. The details are as follows:
Click Activate and then check the plugin status in Installed Plugins.
HCIP-openEuler Lab Guide Page 40
Log in to the Redis host. In the WordPress configuration, the generated data is stored in
database 0. Therefore, you can run the keys * command to query the generated cache
data.
HCIP-openEuler Lab Guide Page 41
------------End------------
Huawei openEuler Certification Training
HCIP-openEuler
Storage Management
Lab Guide
ISSUE: 1.0
2
Copyright © Huawei Technologies Co., Ltd. 2024. All rights reserved.
No part of this document may be reproduced or transmitted in any form or by any
means without prior written consent of Huawei Technologies Co., Ltd.
and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd.
All other trademarks and trade names mentioned in this document are the property of
their respective holders.
Notice
The purchased products, services and features are stipulated by the contract made
between Huawei and the customer. All or part of the products, services and features
described in this document may not be within the purchase scope or the usage scope.
Unless otherwise specified in the contract, all statements, information, and
recommendations in this document are provided "AS IS" without warranties,
guarantees or representations of any kind, either express or implied.
The information in this document is subject to change without notice. Every effort has
been made in the preparation of this document to ensure accuracy of the contents, but
all statements, information, and recommendations in this document do not constitute
a warranty of any kind, express or implied.
Overview
This document is an HCIP-openEuler certification training course and is intended for
trainees who are going to take the HCIP-openEuler exam or readers who want to learn
how to build enterprise services and master storage management on openEuler and
other Linux distributions.
Description
This lab guide consists of two labs, covering Network File System (NFS) and storage area
network (SAN) on shared networks, as well as the configuration and implementation of
GlusterFS distributed storage.
⚫ Lab 1: shared storage configuration
➢ This lab focuses on setting up and utilizing NFS and SAN storage, providing a
foundation in basic shared storage usage.
⚫ Lab 2: GlusterFS distributed storage management
➢ This lab covers storage cluster setup, along with the creation and utilization of
various volume types.
Contents
1.1.2 Networking
This lab involves three ECSs: Client01, Client02, and ecs-nfs. The following figure shows
the networking.
HCIP-openEuler Storage Management Lab Guide Page 2
ECS
IP Address Specifications
Name
1.1.3 Procedure
Step 1 Create ECSs.
Log in to ecs-nfs and check whether nfs-utils and rpcbind have been installed.
The private OS image used in this lab contains the nfs-utils and rpcbind software
packages, and the services have been installed. You only need to start the services.
If the nfs or rpcbind process does not exist in the environment, manually install nfs-utils.
rpcbind will be automatically installed with nfs-utils.
Start the nfs service and enable it to automatically start upon system startup.
Create a shared directory /data and check whether the creation is successful. The shared
directory will be mounted and accessed by clients on other ECSs.
mkdir /data
ls /
Edit the /etc/exports configuration file to allow access from any clients.
/data *(rw,sync,no_root_squash)
showmount -e
HCIP-openEuler Storage Management Lab Guide Page 4
Log in to ECS Client01 and install the nfs-utils and rpcbind services by referring to Step 2.
In this lab, Client01 and ecs-nfs are on the same network and are mutually reachable.
Proceed to Step 5. If the ECSs cannot reach each other, establish connectivity between
them before performing subsequent operations.
mkdir /mnt/data
showmount -e 192.168.1.10
If the shared directory exists, mount it to the /mnt/data directory on the client.
Successful mounting produces no output. Run the df -h command to check the status of
storage on Client01.
On Client01, enter the mount point and create file01 in the shared directory.
On ecs-nfs, go to the /data directory and check whether the preceding operation is
successful.
Log in to Client02 and repeat steps 4 and 5 to mount the NFS shared directory.
HCIP-openEuler Storage Management Lab Guide Page 6
On ecs-nfs, modify the /etc/exports file to refine client access permissions and restart
the NFS service.
/data 192.168.1.21/32(rw,sync,no_root_squash)
/data 192.168.1.22/32(ro)
HCIP-openEuler Storage Management Lab Guide Page 7
You can see that Client02 has only the read-only permission on the file and cannot
modify it. Try creating files in the shared directory. You can see that Client02 does not
have the permission to create files, while Client01 does.
HCIP-openEuler Storage Management Lab Guide Page 8
After the restart, the shared directory is unmounted. Configure automatic mounting.
On Client01, add the following content to the /etc/fstab file, and save the file.
Restart Client01 again and check its storage information. You can see that the shared
directory is automatically mounted.
HCIP-openEuler Storage Management Lab Guide Page 9
1.2.2 Networking
This lab involves three ECSs: Client01 and Client02 (from the NFS storage management
lab) as clients, and a separate ECS as the simulated IP-SAN storage. The following figure
shows the networking.
1.2.3 Procedure
Step 1 Log in to the Huawei Cloud official website and create ECS ecs-san.
Start the target service and enable it to automatically start upon system startup.
tgtadm --lld iscsi --mode target --op new --tid 1 --targetname iqn.2023-04.com.openeuler:target1
View information about the created target. This example uses short options, while other
examples in this lab use long options. Use whichever format as you prefer.
In the information about the created target, you can see that a logical unit with logical
unit number (LUN) 0 is automatically created. LUN 0 is created for each target and acts
as the controller. backing store type is null, indicating that the logical unit has no
underlying logical device.
Add a logical unit for the target. A data drive has been added during ecs-san creation.
Check the location of the drive.
fdisk -l
HCIP-openEuler Storage Management Lab Guide Page 13
A 10 GB drive /dev/vdb is displayed. You can either add the entire drive as a logical unit
to target1, or partition the drive and add a partition as a logical unit.
tgtadm --lld iscsi --mode logicalunit --op new --tid 1 --lun 1 --backing-store /dev/vdb
You can see that LUN 1 has been added to target1. LUN 1 is a readable and writable
(rdwr) device of the disk type and has logical device /dev/bdb. However, Account
information and ACL information is still empty, indicating that the target is not shared.
tgtadm --lld iscsi --mode target --op bind --tid 1 --initiator-address 192.168.1.21
Create a session between the initiator and target by associating the target. This session
enables the initiator to view, access, and operate SCSI devices of the target.
On Client01, run the following command to associate all discovered targets:
I_T nexus information shows information about connections between initiators and
LUNs of the target. nexus is the number of association times.
Run the following command to disassociate the target:
iscsiadm -m session
On Client01, check the drive name, format the drive, and write a file to it.
fdisk -l
HCIP-openEuler Storage Management Lab Guide Page 21
mkfs.ext4 /dev/sda
blkid /dev/sda
⚫ Question: If you format a server drive through a client-side operation, will the
changes be reflected on the server as well?
Answer: Yes. The drive format information on ecs-san is as follows.
blkid /dev/vdb
The drive format is ext4, indicating that the drive on the SAN is formatted.
HCIP-openEuler Storage Management Lab Guide Page 22
mkdir /mnt/san
In /mnt/san, create file test.txt and write This is from Client01 into it.
tgtadm --lld iscsi --mode target --op bind --tid 1 --initiator-address 192.168.1.22
HCIP-openEuler Storage Management Lab Guide Page 23
lsblk
Create a directory.
mkdir /mnt/san
Check files in the mounted directory. The file created by Client01 exists.
On Client02, go to /mnt/san/, create file test1.txt, and write This is from Client02 to it.
On Client01, and check the content of /mnt/san. You can see that data is not
synchronized.
On Client02, unmount /mnt/san and mount it again. You can see that test1.txt is lost.
HCIP-openEuler Storage Management Lab Guide Page 26
The logical storage device is accessed by multiple hosts simultaneously. As a result, data
may conflict and cannot be synchronized in a timely manner, causing data loss.
⚫ Question: When multiple hosts access a logical storage device simultaneously, how
do you keep data synchronized and prevent data loss?
Answer: Configure a cluster or distributed file system for iSCSI to ensure data
synchronization and loss prevention.
Step 10 Unmount the drive and disconnect the clients from the target.
umount /mnt/san
df -h
On Client02, repeat the operations to unmount the drive and disconnect from target1.
HCIP-openEuler Storage Management Lab Guide Page 27
tgtadm --lld iscsi --mode target --op unbind --tid 1 --initiator-address 192.168.1.21
tgtadm --lld iscsi --mode target --op unbind --tid 1 --initiator-address 192.168.1.22
Configurations set by the tgtadm command are saved in the memory and will be lost
when the tgt service or system restarts. To make the configurations persistent, save them
to the configuration file.
The default target configuration file is /etc/tgt/targets.conf.
On ecs-san, add the following content to the end of /etc/tgt/targets.conf, save the file,
and exit.
On Client01, connect to and mount the target. Then, test the connection.
Step 13 Enable the client to automatically mount the SAN storage upon system startup.
HCIP-openEuler Storage Management Lab Guide Page 30
By default, the storage mounting configuration is lost after a client is restarted, and
manual remounting is required. Configuring automatic mounting at startup streamlines
operations and enhances user experience.
On Client01, check whether the mounted directory still exists after the restart.
Run the following command to enable automatic login upon system startup:
2.1 Introduction
In this lab, you will use ECSs as storage nodes to set up a GlusterFS cluster and create
different types of volumes for client access. Lab operations include:
⚫ GlusterFS server cluster setup
⚫ GlusterFS client setup
⚫ Creation and usage of different types of volumes
⚫ Cluster and volume management
2.2 Networking
This lab involves seven ECSs. You can reuse Client01 from the shared storage
management lab and create six additional ECSs as storage nodes to form a GlusterFS
distributed storage cluster. The following figure shows the topology.
HCIP-openEuler Storage Management Lab Guide Page 34
/dev/vdb1 2G
For the /exp/vdb1
/dev/vdb2 2G test volume
node4 192.168.1.34 /dev/vdb3 2G For the /exp/vdb3
/dev/vdb4 5G distributed
replicated volume
/dev/vdb5 2G
HCIP-openEuler Storage Management Lab Guide Page 35
/dev/vdb1 2G
/dev/vdb2 2G For the /exp/vdb1
test volume
/dev/vdb3 2G
node5 192.168.1.35 For the /exp/vdb6
/dev/vdb4 5G
distributed
/dev/vdb5 2G dispersed volume
/dev/vdb6 2G
/dev/vdb1 2G
/dev/vdb2 2G
/dev/vdb3 2G For the /exp/vdb6
node6 192.168.1.36 distributed
/dev/vdb4 5G dispersed volume
/dev/vdb5 2G
/dev/vdb6 2G
OS: openEuler
22.03 LTS
Password: Set a
password as
needed.
Client01 192.168.1.21 Reused
Flavor: 2 vCPUs |
4 GB
Drive: 40 GB
Each ECS is
bound to an EIP.
2.3 Procedure
Step 1 Log in to Huawei Cloud and create six ECSs based on the resource information.
mkfs.xfs /dev/vdb1
mkfs.xfs /dev/vdb2
mkfs.xfs /dev/vdb3
mkfs.xfs /dev/vdb5
mkfs.xfs /dev/vdb6
Step 4 Edit the /etc/hosts file to set host name mapping for each storage node.
HCIP-openEuler Storage Management Lab Guide Page 39
Run the following commands to install the GlusterFS server and start the service:
node1, node2, node3, node4, node5 and node6 have joined the trusted pool. You can
also query the trusted pool status and node list on other nodes.
HCIP-openEuler Storage Management Lab Guide Page 44
The status of test-volume is Created, and the bricks of the volume are displayed. Start
the volume and check the volume information again.
Log in to Client01 and run the following command to install the client service:
Edit /etc/hosts to set host name mapping for each storage node.
mkdir -p /mnt/gfs/test
In /mnt/gfs/test, create file test.txt and write This is from Client01 into it.
cd /mnt/gfs/test
echo "This is from Client01" > test.txt
The same file exists in the bricks on the two nodes, indicating that replicated volume
test-volume is successfully mounted and has two replicas.
A GlusterFS distributed volume stores created files in different bricks randomly. Create
and start distributed volume gv-dis.
mkdir -p /mnt/gfs/dis
mount -t glusterfs node1:gv-dis /mnt/gfs/dis
HCIP-openEuler Storage Management Lab Guide Page 49
gv-dis contains two 2 GB bricks. The size of the mounted gv-dis volume is 4 GB, which is
the sum of the capacities of the two bricks.
Write five files into /mnt/gfs/dis.
The five files are distributed in different bricks, and each file can exist in only one brick.
Use /exp/vdb2/brick on node1, node2, and node3 to create a volume gv-rep with three
replicas by referring to the networking information and Step 8.
HCIP-openEuler Storage Management Lab Guide Page 50
gv-rep contains three 2 GB bricks. The size of the mounted gv-rep volume is 2 GB, which
is a third of the total size.
Write five files into /mnt/gfs/rep.
Use four bricks to create volume gv-disrep based on the networking information.
The command for creating the distributed replicated volume is similar to that for the
replicated volume, differing only in the number of replicas and added bricks.
On Client01, mount gv-disrep to /mnt/gfs/disrep.
mkdir -p /mnt/gfs/disrep
mount -t glusterfs node1:gv-disrep /mnt/gfs/disrep
gv-disrep contains four 2 GB bricks. The size of the mounted gv-disrep volume is 4 GB,
which is a half of the total capacity. This means that the other half is used as the replica.
Write five files into /mnt/gfs/disrep.
The bricks on node1 and node2 are replicas of each other, as are the bricks on node3
and node4. This is because when a distributed replicated volume is created, two adjacent
bricks become replicas of each other.
Dispersed volumes stripe the encoded data of files, add some redundancy, and store
them across multiple bricks in the volume. Use /exp/vdb5/brick on node1, node2, and
node3 to create dispersed volume gv-disp by referring to the networking information.
Divide each file into three stripes, including two for storage and one for redundancy.
mkdir -p /mnt/gfs/disp
mount -t glusterfs node1:gv-disp /mnt/gfs/disp
gv-disp contains three 2 GB bricks. The size of the mounted gv-disp volume is 4 GB,
which means that 2 GB is used for redundancy.
Write five files into /mnt/gfs/disp.
Each TXT file is divided into two data blocks and then encoded into three encode blocks
distributed across different bricks.
Distributed dispersed and distributed replicated volumes both distribute data across
nodes, but differ in the order of operations. Distributed replicated volumes first distribute,
then replicate, while distributed dispersed volumes first disperse, then distribute. Use
HCIP-openEuler Storage Management Lab Guide Page 56
/exp/vb6/brick on node1, node2, node3, node4, node5, and node6 to create distributed
dispersed volume gv-dd. Divide each file into three stripes, including two for storage and
one for redundancy.
mkdir -p /mnt/gfs/dd
mount -t glusterfs node1:gv-dd /mnt/gfs/dd
HCIP-openEuler Storage Management Lab Guide Page 57
gv-disp contains six 2 GB bricks. The size of the mounted gv-dd volume is 8 GB, which
means that 4 GB is used for redundancy.
Write five files into /mnt/gfs/dd.
On node1, node2, node3, node4, node5, and node6, check the content of /exp/vdb6/brick.
HCIP-openEuler Storage Management Lab Guide Page 58
Files are distributed in two dispersed volumes. One volume consists of node1, node2, and
node3, the other of node4, node5, and node6. In each dispersed volume, a file is divided
into two blocks, encoded into three blocks using erasure coding, and then stored in
different bricks.
HCIP-openEuler Storage Management Lab Guide Page 59
The brick has been added. On Client01, check the volume capacity.
⚫ Question: Why are the files not stored in the newly added brick?
Answer: A brick added to a GlusterFS volume can be used only after the volume is
rebalanced.
Rebalance the volume.
Stop test-volume.
Delete test-volume.
No volume contains bricks in node1. On Client01, check the mounting status of different
volumes.
HCIP-openEuler
Lab Guide
ISSUE: 1.0
2
Copyright © Huawei Technologies Co., Ltd. 2024. All rights reserved.
No part of this document may be reproduced or transmitted in any form or by any
means without prior written consent of Huawei Technologies Co., Ltd.
and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd.
All other trademarks and trade names mentioned in this document are the property of
their respective holders.
Notice
The purchased products, services, and features are stipulated by the commercial
contract made between Huawei and the customer. All or partial products, services, and
features described in this document may not be within the purchased scope or the
usage scope. Unless otherwise specified in the contract, all statements, information,
and recommendations in this document are provided "AS IS" without warranties,
guarantees or representations of any kind, either express or implied.
The information in this document is subject to change without notice. Every effort has
been made in the preparation of this document to ensure accuracy of the contents, but
all statements, information, and recommendations in this document do not constitute
a warranty of any kind, express or implied.
Overview
This document is an HCIP-openEuler certification training course and is intended for
trainees who are going to take the HCIP-openEuler exam or readers who want to learn
how to build enterprise services, shell scripts, or perform automated O&M using Zabbix
or SaltStack on openEuler and other Linux distributions.
Description
This lab guide consists of two labs, one for Ansible and the other for SaltStack automated
O&M.
⚫ Lab 1 is related to Ansible. This lab introduces basic Ansible operations, practices
common function modules, and simply compiles and executes the playbook.
⚫ Lab 2 is related to SaltStack. This lab introduces the remote execution function and
configuration management function of SaltStack.
Contents
About This Document ............................................................................................................... 3
Overview ............................................................................................................................................................................................. 3
Description ......................................................................................................................................................................................... 3
Background Knowledge Required ............................................................................................................................................. 3
Lab Environment Overview .......................................................................................................................................................... 3
1 Basic Operations of Ansible ................................................................................................. 1
1.1 Installing and Configuring the Ansible Controller ........................................................................................................ 1
1.2 Basic Operations of the Ansible Command .................................................................................................................... 2
1.3 Practice of Common Ansible Modules.............................................................................................................................. 6
1.3.1 Practice of the command Module .................................................................................................................................. 6
1.3.2 Practice of the shell Module ............................................................................................................................................. 6
1.3.3 Practice of the script Module ........................................................................................................................................... 7
1.3.4 Practice of the copy Module ............................................................................................................................................. 7
1.3.5 Practice of the fetch Module ............................................................................................................................................ 8
1.3.6 Practice of the file Module ................................................................................................................................................ 9
1.3.7 Practice of the archive and unarchive Modules ......................................................................................................11
1.4 Playbook Comprehensive Practice ...................................................................................................................................12
1.4.1 Environment Preparation .................................................................................................................................................12
1.4.2 Lab Practice ...........................................................................................................................................................................12
2 Basic Operations of SaltStack............................................................................................15
2.1 Installing and Configuring SaltStack ...............................................................................................................................15
2.1.1 Installing salt-master and salt-minion ........................................................................................................................15
2.1.2 Configuring the Master and Minion Authentication .............................................................................................17
2.1.3 Adding a Client in SSH Mode .........................................................................................................................................17
2.2 SaltStack Remote Execution Function Practice ...........................................................................................................18
2.2.1 Specifying the Target.........................................................................................................................................................18
2.2.2 Practice of Remote Execution Function Modules – cmd ......................................................................................19
2.2.3 Practice of Remote Execution Function Modules – pkg .......................................................................................20
2.2.4 Practice of Remote Execution Function Modules – service .................................................................................21
2.2.5 Practice of Remote Execution Function Modules – network ..............................................................................22
2.2.6 Practice of Remote Execution Function Modules – file ........................................................................................23
2.3 SaltStack Configuration Management Function Practice ........................................................................................25
2.3.1 Configuration Management Script Practice ..............................................................................................................25
2.3.2 Composing the top.sls File...............................................................................................................................................27
HCIP-openEuler Lab Guide Page 1
Log in to the Ansible host and run the following command to install Ansible:
After the installation is complete, run the following command to check Ansible:
ansible --version
Modify the Ansible configuration file and uncomment the host_key_checking parameter,
as shown in the following figure:
Modify the Ansible host list, add IP addresses of hosts Zabbix, Nginx1, and Nginx2 to the
list, and group the hosts as shown in the following figure:
HCIP-openEuler Lab Guide Page 2
Run the following commands to configure SSH password-free login from the controller to
the controlled hosts:
ssh-keygen
ssh-copy-id 192.168.1.4
ssh-copy-id 192.168.1.14
ssh-copy-id 192.168.1.15
Step 1 Ansible uses the ping module to check whether the communication with the
controlled hosts is normal.
Run the following command to invoke the ping module and check whether the controller
can communicate with the controlled hosts:
The command output contains warning information. You can add interpreter_python =
auto_legacy_silent to [default] in the configuration file to clear the warning.
Use the -k option to enter the SSH password in interactive mode. The method is as
follows:
all indicates all hosts in the host list. Use the host tag to specify the host that runs the
command. The command is as follows:
⚫ Task: Check the communication status between the host in the Zabbix group and the
controller.
HCIP-openEuler Lab Guide Page 4
Run the following command to check the communication between the Zabbix or Nginx
host group and the controller.
Run the following command to check the communication between the shared hosts in
the Zabbix and Nginx host groups and the controller:
Use the -v parameter to check the Ansible command execution process, as shown in the
following figure:
⚫ Task: Run -vv and -vvv to check more detailed execution process.
HCIP-openEuler Lab Guide Page 6
#!/bin/bash
ip addr | grep link/ether | awk '{print $2}'
Run the following command on the controller to execute the script on all the controlled
hosts:
ansible all -m script -a "~/mac.sh" | grep stdout | awk '{print $2}' | grep \n
mkdir /root/data
touch /root/data/copy
After the file is fetched, the structure of the /tmp directory is as follows:
⚫ Question: What are the owner and group to which the test file belongs? Why?
Answer: In this lab, the owner and group to which the test file belongs are root:root.
This is because the owner and group are not specified when the file is created. By default,
the owner and group that are running the Ansible commands are used.
In this step, variables are used to change the Zabbix host name to Zabbix_server, and
change the host names of Nginx01 and Nginx02 to Nginx-01 and Nginx-02.
Modify the Ansible host file as follows:
[Nginx]
192.168.1.14 host=01
192.168.1.15 host=02
[Nginx:vars]
group=Nginx
[Zabbix]
192.168.1.4 host=Server
---
- hosts: Zabbix
remote_user: root
gather_facts: no
tasks:
- name: set hostname for 192.168.1.4
hostname:
name={{ host }}
- hosts: Nginx
remote_user: root
gather_facts: no
tasks:
- name: set hostname for 192.168.1.14 and 192.168.1.15
hostname:
name={{ group }}-{{ host }}
After the editing is complete, use ansible-playbook –C to run the script and check
whether there is an error. If an error is reported, rectify the fault. After no error is
reported, perform the following steps.
HCIP-openEuler Lab Guide Page 13
Add the following content to the Ansible playbook and set related tags:
……
tasks:
- name: set hostname for 192.168.1.14 and 192.168.1.15
hostname:
name={{ group }}-{{ host }}
- name: download Zabbix yum repolist
tags: agent1
shell: rpm -Uvh https://repo.zabbix.com/zabbix/6.2/rhel/8/x86_64/zabbix-release-6.2-
3.el8.noarch.rpm
- name: install zabbix-agent
tags: agent2
yum:
name=zabbix-agent2
state=present
- name: config zabbix-agent
tags: agent3
replace:
path: /etc/zabbix/zabbix_agent2.conf
regexp: '^Server=127.0.0.1$'
replace: 'Server=192.168.1.4'
notify: restart zabbix-agent2
- name: config zabbix-agent service
tags: agent3
service:
name: zabbix-agent2
state: started
enabled: yes
handlers:
- name: restart zabbix-agent2
service:
name: zabbix-agent2
state: restarted
Use the tag to perform the test step by step until all the items pass the test. Then,
proceed to the next step.
Run the compiled playbook to install zabbix-agent. The details are as follows:
HCIP-openEuler Lab Guide Page 14
HCIP-openEuler Lab Guide Page 15
Log in to all hosts (192.168.1.60 is called SaltStack) and run the following commands to
configure the Yum repository required by SaltStack:
After the installation is complete, run the following command to start salt-master and set
it to start upon system startup:
Run the following command to install salt-ssh. The Zabbix host is managed using SSH,
and the Nginx1 and Nginx2 hosts are managed using salt-minion.
Create the master.conf file in the /etc/salt/master.d directory on the host SaltStack and
enter the following content:
interface: 0.0.0.0
publish_port: 4505
ret_port: 4506
pki_dir: /etc/salt/pki/master
file_roots:
base:
- /srv/salt/
pillar_roots:
base:
- /srv/pillar
Restart the salt-master service and check the service status. If any error occurs, rectify the
fault before proceeding to the next step.
After the installation is complete, run the following command to start salt-minion and set
it to start upon system startup:
Create the minion.conf file in the /etc/salt/minion.d directory on the host Nginx1 and
enter the following content:
master: 192.168.1.60
id: Nginx1
HCIP-openEuler Lab Guide Page 17
Create the minion.conf file in the /etc/salt/minion.d directory on the host Nginx2 and
enter the following content:
master: 192.168.1.60
id: Nginx2
After the configuration is complete, restart the salt-minion service on the two hosts and
ensure that the service is running properly.
Run the salt-key -A command to receive all keys. The details are as follows:
After the keys are received, run the following command to check whether the
communication between the master and minion is normal:
Zabbix:
host: 192.168.1.4
user: root
port: 22
Modify the SSH configuration file /etc/ssh/ssh_config on the Zabbix host by changing
StrictHostKeyChecking from ask to no, as shown in the following figure.
After the modification, run the systemctl restart sshd command to restart the SSH
service.
Then, run the following commands to configure SSH mutual trust between the hosts,
SaltStack and Zabbix:
ssh-keygen
ssh-copy-id 192.168.1.4
After the configuration is complete, run the following command to check whether the
communication between the two hosts is normal:
Authentication is required for the first connection. Enter the password as prompted. If the
connection is normal, the following information is displayed:
Requirement 1: Check whether the communication between all minions and the master is
normal.
Command: salt '*' test.ping
Requirement 2: Check whether the communication between all minions whose IDs start
with Nginx but do not contain Nginx1 and the master is normal.
Command: salt 'Nginx[!1]' test.ping
Run the following command to list NGINX of the latest version that can be installed on
Nginx1 using the current Yum repository:
Run the following command to install NGINX for Nginx1 and Nginx2:
Run the following command to check whether NGINX has been installed:
Run the following command to set the NGINX service on Nginx1 and Nginx2 to
automatically start upon system startup:
Run the following command to check whether the automatic startup of NGINX is enabled
upon system startup:
Run the following command to test whether Nginx1 can access the NGINX service of
Nginx2:
Use the same method to test whether Nginx2 can access the NGINX service of Nginx1.
Run the following command to create the test.conf configuration file in the Nginx
configuration directory:
After the preceding operations are complete, check whether the configuration takes
effect.
⚫ Question: Is the page displayed as expected?
Answer: No. The host names of Nginx1 and Nginx2 are not displayed on the page. The
host name of the master is displayed. The reason is that the master converts variables
HCIP-openEuler Lab Guide Page 25
and then sends them to the minion. To achieve the expected effect, you are advised to
use the Jinja template to invoke the grains value.
Cancel the configuration of the file_roots parameter on the master node, as shown in
the following figure.
Create the nginx.sls file in /srv/salt and enter the following content:
---
nginx_install:
pkg.installed:
- name: nginx
create_test:
file.touch:
- name: /etc/nginx/conf.d/test.conf
config_test:
file.append:
- name: /etc/nginx/conf.d/test.conf
- text:
- "server {"
- " root /data/Nginx;"
- " index index.html;"
- "}"
create_root_dir:
file.directory:
HCIP-openEuler Lab Guide Page 26
- name: /data/Nginx
- makedirs: True
create_index:
file.touch:
- name: /data/Nginx/index.html
config_index:
file.append:
- name: /data/Nginx/index.html
- text: hello,{{ grains['host'] }}
- template: jinja
enable_nginx:
service.running:
- name: nginx
- enable: True
- reload: True
If the command is successfully executed, the system returns the number of Succeeded
records, as shown in the following figure.
⚫ Task: Compile a configuration script to install Apache on Nginx2 and place the home
page in /data/Apache. The home page content is "hello, host name".
Answer: The SLS script for reference is as follows:
---
apache_install:
pkg.installed:
- name: httpd
create_test:
file.touch:
- name: /etc/httpd/conf.d/test.conf
config_test:
file.append:
- name: /etc/httpd/conf.d/test.conf
- text:
- DocumentRoot "/data/apache"
- '<Directory "/data/apache">'
HCIP-openEuler Lab Guide Page 27
modify_default_config:
file.replace:
- name: /etc/httpd/conf/httpd.conf
- pattern: 'DocumentRoot "/var/www/html"'
- repl: '#DocumentRoot "/var/www/html"'
create_root_dir:
file.directory:
- name: /data/apache
- makedirs: True
create_index:
file.touch:
- name: /data/apache/index.html
config_index:
file.append:
- name: /data/apache/index.html
- text: hello,{{ grains['host'] }}
- template: jinja
enable_apache:
service.running:
- name: httpd
- enable: True
- reload: True
base:
'host:Nginx1':
- match: grain
- nginx
'host:Nginx2':
- match: grain
- apache
Save the file and run the following command to test the top.sls file:
If the test is successful, run the top.sls file to complete the requirement.
HCIP-openEuler
Lab Guide
ISSUE: 1.0
2
Copyright © Huawei Technologies Co., Ltd. 2024. All rights reserved.
No part of this document may be reproduced or transmitted in any form or by any
means without prior written consent of Huawei Technologies Co., Ltd.
and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd.
All other trademarks and trade names mentioned in this document are the property of
their respective holders.
Notice
The purchased products, services, and features are stipulated by the commercial
contract made between Huawei and the customer. All or partial products, services, and
features described in this document may not be within the purchased scope or the
usage scope. Unless otherwise specified in the contract, all statements, information,
and recommendations in this document are provided "AS IS" without warranties,
guarantees or representations of any kind, either express or implied.
The information in this document is subject to change without notice. Every effort has
been made in the preparation of this document to ensure accuracy of the contents, but
all statements, information, and recommendations in this document do not constitute
a warranty of any kind, express or implied.
Overview
This document is an HCIP-openEuler certification training course and is intended for
trainees who are going to take the HCIP-openEuler exam or readers who want to learn
how to build enterprise services, shell scripts, or perform automated O&M using Zabbix
or SaltStack on openEuler and other Linux distributions.
Description
This lab guide consists of six labs, including advanced process control statements,
functions, regular expressions, global regular expression search and print (grep)
commands, stream editor (sed), and AWK statements in shell scripts.
⚫ Lab 1: Advanced process control statements. Through user password verification,
readers can master the process control statements and condition testing.
⚫ Lab 2: Functions. By creating the addUser function, readers can master how to create
and use functions.
⚫ Lab 3: Regular expressions. By filtering and querying the NIC and process
information, readers can master the usage of regular expression common characters,
common metacharacters, and extended metacharacters.
⚫ Lab 4: grep commands. By filtering and querying the NIC and process information,
readers can master output control options, context control options, and pattern
selection options of grep commands.
⚫ Lab5: sed. By filtering and querying the NIC and process information, readers can
master sed line number addressing, regular expression addressing, adding, deleting,
modifying, and querying, search and replacement, file operations, and parameter
options.
⚫ Lab 6: AWK statements. By filtering and querying the NIC and process information,
readers can master the built-in variables, field separators, record separators,
formatted output, regular expressions, control statements, and the script mode of
AWK statements.
Contents
About This Document ............................................................................................................... 3
Overview ............................................................................................................................................................................................. 3
Description ......................................................................................................................................................................................... 3
Background Knowledge Required ............................................................................................................................................. 3
Lab Environment Overview .......................................................................................................................................................... 4
1 Advanced Process Control Statement Practice ................................................................ 1
1.1 Verifying Input ........................................................................................................................................................................... 1
1.2 Verifying Files ............................................................................................................................................................................ 4
1.3 Verifying the User Name and Password .......................................................................................................................... 5
2 Function Practice .................................................................................................................... 7
2.1 addUser Function ..................................................................................................................................................................... 7
3 Regular Expression Practice ................................................................................................. 8
3.1 Common Characters ................................................................................................................................................................ 8
3.2 Common Metacharacters ...................................................................................................................................................... 8
3.3 Extended Metacharacters ...................................................................................................................................................... 9
4 grep Command Practice......................................................................................................11
4.1 Output Control Options .......................................................................................................................................................11
4.2 Context Control Options ......................................................................................................................................................12
4.3 Pattern Selection Options ...................................................................................................................................................13
5 sed Practice ............................................................................................................................14
5.1 Line Number Addressing .....................................................................................................................................................14
5.2 Regular Expression Addressing ..........................................................................................................................................15
5.3 Adding, Deleting, Modifying, and Querying Texts .....................................................................................................15
5.4 Searching and Replacing Texts ..........................................................................................................................................17
5.5 File Operations ........................................................................................................................................................................19
5.6 Parameter Options.................................................................................................................................................................20
6 AWK Statements ..................................................................................................................22
6.1 Built-in Variables ....................................................................................................................................................................22
6.2 Field Separators ......................................................................................................................................................................23
6.3 Record Separators ..................................................................................................................................................................24
6.4 Formatted Output ..................................................................................................................................................................24
6.5 Regular Expressions ...............................................................................................................................................................25
6.6 Control Statements ................................................................................................................................................................25
6.7 Script Mode ..............................................................................................................................................................................26
HCIP-openEuler Lab Guide Page 1
Log in to the openEuler operating system (OS) and run the following command to create
a shell script:
#!/bin/bash
Add the user name and password variables to the user.sh file for verification.
#!/bin/bash
username_file="root"
password_file="123456"
#!/bin/bash
username_file="root"
password_file="123456"
echo "Please enter username:"
while :
do
read username
done
Add the if condition for checking whether the input is empty to the while loop.
HCIP-openEuler Lab Guide Page 2
#!/bin/bash
username_file="root"
password_file="123456"
echo "Please enter username:"
while :
do
read username
if test -z $username
then
echo "Please enter a non empty username:"
continue
fi
done
#!/bin/bash
username_file="root"
password_file="123456"
echo "Please enter username:"
while :
do
read username
if test -z $username
then
echo "Please enter a non empty username:"
continue
elif test $username = $username_file
then
echo "User $username wants to login!"
break
fi
done
#!/bin/bash
username_file="root"
password_file="123456"
echo "Please enter username:"
while :
do
read username
if test -z $username
then
echo "Please enter a non empty username:"
continue
elif test $username = $username_file
HCIP-openEuler Lab Guide Page 3
then
echo "User $username wants to login!"
break
else
echo "Incorrect! Please re-enter the username:"
continue
fi
done
After the user name is verified, enter the password and verify it.
#!/bin/bash
username_file="root"
password_file="123456"
echo "Please enter username:"
while :
do
read username
if test -z $username
then
echo "Please enter a non empty username:"
continue
elif test $username = $username_file
then
echo "User $username wants to login!"
break
else
echo "Incorrect! Please re-enter the username:"
continue
fi
done
Save the script and exit the vim insert mode. Enter an empty user name and password,
an incorrect user name and password, and a correct user name and password. The
following shows an example:
⚫ Question: Why is an alarm generated during script execution? How to modify the
script to clear the alarm?
Answer: In this script, test compares numbers. Therefore, the entered value must be an
integer, and "a" is a character. As a result, a system alarm is generated. To clear the
alarm, replace -eq in the shell script with an equal sign (=).
Add file verification to user.sh. The user.txt file stores the user name and password. If
the user.txt file does not exist, the system prompts you to enter the user name and
password and saves them to a user.txt file.
#!/bin/bash
while :
do
if test -e user.txt
then
echo "Entering the Login Program:"
break
else
echo "The user does not exist. Enter the user registration program."
echo "Please enter username for storage:"
read username
echo "Please enter password for storage:"
read password
fi
done
username_file="root"
password_file="123456"
HCIP-openEuler Lab Guide Page 5
…….
Step 2 Check the user name and password based on multiple conditions.
#!/bin/bash
while :
do
if test -e user.txt
then
echo "Entering the Login Program:"
break
else
echo "The user does not exist. Enter the user registration program."
echo "Please enter username for storage:"
read username
echo "Please enter password for storage:"
read password
if test -n $username -a -n $password
then
echo "$username $password" > user.txt
echo "Storage Successed!"
echo ""
break
else
echo "Please enter a non empty username or password:"
continue
fi
fi
done
………
Save the data in the user.txt file to the user name and password variables for
subsequent user name and password verification.
Save and exit the vim insert mode. Enter an empty user name and password, an incorrect
user name and password, and a correct user name and password. The following shows
an example:
2 Function Practice
Add a function to user.sh for adding the user name and password using commands.
#!/bin/bash
addUser(){
if test -n $1 -a -n $2
then
echo "$1 $2" >> user.txt
else
echo "Add failed.The parameter is incorrect."
fi
}
Run the source command to add the addUser function to the current shell environment.
Run set to view the function. Execute the addUser function.
View the processes whose names contain zero or more hyphens (-) before "gp".
View the lines that contain one or more occurrences of "192" in the NIC information.
View the lines that contain zero or more occurrences of "255" after "255." in the NIC
information.
View the lines that contain zero or more occurrences of "255" or "0" after "255." in the
NIC information.
Step 4 Specify the number of repetitions of preceding characters in the NIC information.
View the lines that contain two occurrences of "255." after "255.".
View the lines that contain two or more occurrences of "255." after "255.".
View the lines that contain a maximum of two occurrences of "255." after "255.".
View the lines that contain one to two occurrences of "255." after "255.".
View a maximum of one line that contains "inet" in the NIC information.
View the lines that contain "inet6" and their line numbers in the NIC information.
View the number of lines that contain "inet6" in the NIC information.
View the lines that do not start with a space in the NIC information.
[root@openEuler ~]#
View the content that only contains "192.168.0.255" in the NIC information.
192.168.0.255
[root@openEuler ~]#
View the lines and file names that contain "Ethernet" in the NIC configuration file.
View the file names that contain "Ethernet" in the NIC configuration file.
View the lines that contain "192" and the following one line in the NIC information.
View the lines that contain "192" and one line before the matched line in the NIC
information.
Step 3 The matched line and n lines before and after it.
View the lines that contain "192" and one line before and after the matched line in the
NIC information.
View the lines that match the whole word "inet" in the NIC information.
View the lines that match the whole line "TYPE=Ethernet" in the NIC configuration file.
View the lines that match "broadcast" and ignore case distinctions in the NIC
information.
5 sed Practice
View line 2 and the following three lines in the NIC information.
View the lines that contain six consecutive digits in the NIC information.
Insert one line before the first line in the NIC configuration information.
[root@openEuler ~]#
Insert one line after the first line in the NIC configuration information.
[root@openEuler ~]#
[root@openEuler ~]#
[root@openEuler ~]#
Replace the first "255" of each line in the NIC information with "11111111".
[root@openEuler ~]#
[root@openEuler ~]#
Replace the slash (/) with the at sign (@) for search.
[root@openEuler ~]#
The text matched by the search string "RX" replaces & in the replacement string.
[root@openEuler ~]#
Read the content from the NIC configurations, insert the read content after the first line
of the ifconfig1.txt file, and the ifconfig1.txt file is not edited.
[root@openEuler ~]#
Save the first line of the ifconfig1.txt file to the ifconfig2.txt file.
Print the first line of ifconfig2.txt and insert "Network card configuration information"
after the first line.
[root@openEuler ~]# sed -e '1p' -e '1a Network card configuration information' ifconfig2.txt
myifconfig2
myifconfig2
Network card configuration information
[root@openEuler ~]#
Create the ifconfig2.sed script and perform the editing operations described in Step 2.
1p
1a Network card configuration information
[root@openEuler ~]# sed -f ifconfig2.sed ifconfig2.txt
myifconfig2
myifconfig2
Network card configuration information
[root@openEuler ~]#
HCIP-openEuler Lab Guide Page 21
Cancel the default output when running commands and display only the changed lines.
6 AWK Statements
Print the number of columns of the IPv6 address in the NIC information.
Method 2:
Print the eight groups of IPv6 addresses that are separated by vertical bars (|). Method 1:
Method 2:
[root@openEuler ~]#
Step 2 printf
Print the second column of the first two lines that contain "192".
Add 20 asterisks (*) before the second column of the second line and 20 number signs
(#) after the second column.
HCIP-openEuler
Lab Guide
Issue: 1.0
2
Copyright © Huawei Technologies Co., Ltd. 2024. All rights reserved.
No part of this document may be reproduced or transmitted in any form or by any
means without prior written consent of Huawei Technologies Co., Ltd.
and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd.
All other trademarks and trade names mentioned in this document are the property of
their respective holders.
Notice
The purchased products, services and features are stipulated by the contract made
between Huawei and the customer. All or part of the products, services and features
described in this document may not be within the purchase scope or the usage scope.
Unless otherwise specified in the contract, all statements, information, and
recommendations in this document are provided "AS IS" without warranties,
guarantees or representations of any kind, either express or implied.
The information in this document is subject to change without notice. Every effort has
been made in the preparation of this document to ensure accuracy of the contents, but
all statements, information, and recommendations in this document do not constitute
a warranty of any kind, express or implied.
Overview
This document is intended for trainees preparing for the HCIP-openEuler certification
exam and those who are interested in security technologies of openEuler or other Linux
distributions, including security hardening policies, principles and usage of common
firewalls, and SELinux mandatory access control policies.
Description
This document consists of eight labs, covering security hardening policies from five
aspects: kernel parameters, authorization and authentication, account and password, file
permission, and system services. It also describes the principles and command usage of
common firewall tools.
⚫ Lab 1: Kernel parameter hardening
⚫ Lab 2: Authorization and authentication hardening
⚫ Lab 3: Account and password hardening
⚫ Lab 4: File permission hardening
⚫ Lab 5: SSH service hardening
⚫ Lab 6: iptables comprehensive practice
⚫ Lab 7: firewalld comprehensive practice
⚫ Lab 8: SELinux access control practice
Lab Environment
The lab requires two ECSs with one serving as the bastion host and the other serving as
the web application server to security the network. JumpServer is the only entry for
accessing intranet services.
OS Security Hardening Lab Guide Page 5
Environment Preparation
Checking Devices
Before the lab, each group of trainees should apply for ECSs on Huawei Cloud according
to the following table.
Contents
About This Document ............................................................................................................... 4
Overview ............................................................................................................................................................................................. 4
Description ......................................................................................................................................................................................... 4
Background Knowledge Required ............................................................................................................................................. 4
Lab Environment .............................................................................................................................................................................. 4
Environment Preparation .............................................................................................................................................................. 5
1 OS Security Hardening .......................................................................................................... 1
1.1 Introduction ................................................................................................................................................................................ 1
1.1.1 About This Lab ....................................................................................................................................................................... 1
1.1.2 Objectives ................................................................................................................................................................................ 1
1.1.3 Planning ................................................................................................................................................................................... 1
1.2 Kernel Parameter Hardening Practice .............................................................................................................................. 1
1.2.1 Hardening Policy Configuration ...................................................................................................................................... 1
1.3 Authorization and Authentication Hardening Practice .............................................................................................. 2
1.3.1 Configuring a Warning for Remote Network Access ............................................................................................... 2
1.3.2 Disabling System Restart Using Ctrl+Alt+Del ............................................................................................................. 2
1.3.3 Setting the Automatic Timeout for Terminals ........................................................................................................... 3
1.3.4 Setting the Default User's umask Value to 0077 ...................................................................................................... 3
1.3.5 Setting the Encryption Password of GRUB2 ................................................................................................................ 3
1.3.6 Resetting the Root Password ............................................................................................................................................ 4
1.4 Account and Password Hardening Practice .................................................................................................................... 5
1.4.1 Shielding System Accounts ................................................................................................................................................ 5
1.4.2 Restricting Accounts that Are Allowed to Use su Commands ............................................................................. 6
1.4.3 Hardening su Commands .................................................................................................................................................. 6
1.4.4 Setting a Password Validity Period ................................................................................................................................. 6
1.4.5 Setting Password Complexity ........................................................................................................................................... 6
1.4.6 Setting Password Encryption Algorithms ..................................................................................................................... 7
1.4.7 Locking an Account After Three Login Failures ......................................................................................................... 7
1.5 File Permission Hardening Practice ................................................................................................................................... 7
1.5.1 Setting File Permissions and Ownership ...................................................................................................................... 7
1.5.2 Deleting Unowned Files ..................................................................................................................................................... 8
1.5.3 Deleting Link Files Pointing to Deleted Files .............................................................................................................. 8
1.5.4 Adding the Sticky Bit Property for Globally Writable Directories ....................................................................... 9
1.5.5 Disabling Global Write on Unauthorized Files ........................................................................................................... 9
1.5.6 Restricting Permissions to Run at Commands ........................................................................................................... 9
1.5.7 Restricting Permissions to Run cron Commands .....................................................................................................10
OS Security Hardening Lab Guide Page 7
1 OS Security Hardening
1.1 Introduction
1.1.1 About This Lab
This lab describes hardening policies of the openEuler OS from five aspects to improve
system and networking security.
1.1.2 Objectives
⚫ Master hardening policies for system services.
⚫ Master hardening policies for kernel parameters.
⚫ Master hardening policies for accounts and passwords.
⚫ Master hardening policies for authorization and authentication.
⚫ Master hardening policies for file permissions.
1.1.3 Planning
In this lab, the JumpServer cloud host is used as the only entry to the intranet, and
security hardening is performed on the host.
net.ipv4.ip_forward=1
net.ipv4.conf.all.log_martians=1
Step 3 send_redirects: disables all interfaces from sending IPv4 ICMP redirection packets.
net.ipv4.conf.all.send_redirects=0
net.ipv4.conf.all.accept_source_route=0
net.ipv4.conf.all.accept_redirects=0
net.ipv4.icmp_echo_ignore_broadcasts=1
Step 7 rp_filter: disables triangular routing and responds to queries from the same API.
This prevents IP spoofing.
net.ipv4.conf.all.rp_filter=1
net.ipv4.tcp_syncookies=1
export TMOUT=300
Step 1 Add umask 0077 to the /etc/bashrc file and all files in /etc/profile.d/.
Step 2 Set the owner and group of the /etc/bashrc file and all files in /etc/profile.d/ to
root.
Reenter password:
PBKDF2 hash of your password is
grub.pbkdf2.sha512.10000.011476329D0DCD1DE1758B7F19BC275BB60CC6C3DF1082BFB812D249112
484E7E7C084E6687A957BB91B40F0A8860E78872AACB89F277EB7D68DC2BD86D34E13.B29208FBE27
1A702ECA14CCB518C165F86564EED56D277434A289948C2504C5AAB73DFCF8E87B160525953DFC51
A57B3A17CE4452E2DD6BB0FAC1A0F36120FB4
The superusers field is used to set the account name of the super GRUB2 administrator.
The first parameter following the password_pbkdf2 field is the GRUB2 account name,
and the second parameter is the encrypted password of the account.
Restart the openEuler system. When the GUN GRUB screen is displayed, press e to modify
the startup command of the system.
Enter the user name root and the encrypted GRUB2 password to go to the startup
command modification screen.
Find the line starting with "linux" and add rd.break to the end of the line.
Press CTRL+x to enable the single-user mode.
OS Security Hardening Lab Guide Page 5
Remount the root directory (/sysroot) in writable mode and switch to this environment.
Find out the accounts that are forbidden from logging in to the system and check the
account status.
adm:x:3:4:adm:/var/adm:/sbin/nologin
dhcpd:x:177:177:DHCP server:/:/sbin/nologin
[root@Jumpserver ~]# passwd -S dhcpd
dhcpd LK 2022-03-30 -1 -1 -1 -1 (Password locked.)
ALWAYS_SET_PATH=yes
PASS_MAX_DAYS 90
PASS_MIN_DAYS 0
PASS_MIN_LEN 5
PASS_WARN_AGE 7
Step 1 Modify the file permission. For example, set the permission on the /bin directory to
755.
Step 2 Change the file ownership. For example, set the owner and group of the /bin
directory to root:root.
find / -nouser
Step 2 Delete the found files. In the command, filename indicates the name of a file
whose user ID does not exist.
rm -f filename
find / -nogroup
Step 4 Delete the found files. In the command, filename indicates the name of a file
whose group ID does not exist.
rm -f filename
Step 1 Run the following command to search for link files pointing to deleted files:
dirname is the name of the directory to be searched. Pay special attention to key
directories /bin, /boot, /usr, /lib64, /lib, and /var.
Step 2 If such files are useless, run the following command to delete them. In the
command, filename is the name of a link file pointing to deleted files.
OS Security Hardening Lab Guide Page 9
rm -f filename
Step 2 Add the sticky bit property for globally writable directories. Replace dirname with
the actual directory name.
chmod +t dirname
for i in `find / -type d -perm -o+w | grep -v proc`;do ls -ld $i | awk '{print $1,$NF}';done
for i in `find / -type f -perm -o+w | grep -v proc`;do ls -l $i | awk '{print $1,$NF}';done
Step 2 View all listed files, exclude files and directories with sticky bits, and delete files or
remove their global write permission. In the command, filename indicates the
corresponding file name.
rm -f /etc/at.deny
touch /etc/at.allow
OS Security Hardening Lab Guide Page 10
Step 4 Control the permission on the /etc/at.allow file. Only the root user can perform
this operation.
rm -f /etc/cron.deny
touch /etc/cron.allow
Step 4 Control the permission on the /etc/cron.allow file. Only the root user can perform
this operation.
⚫ The configuration that has been commented out in the file is the default openEuler
policy.
⚫ After the configuration is modified, restart the SSH service for the modification to
take effect.
MaxAuthTries 3
If a user fails to enter the correct password for three consecutive times when logging in
to the OS, the user will be locked for 60 seconds.
PermitEmptyPasswords no
IgnoreRhosts yes
PrintLastLog yes
ClientAliveInterval 900
ClientAliveCountMax 0
ListenAddress 192.168.0.48
DenyUsers $username
By default, users not listed in the blocklist are considered trustlist users. Blocklist and
trustlist users cannot exist at the same time.
PermitRootLogin no
The root user is not allowed to remotely log in to the system, and a common user is not
allowed to switch to the root user.
OS Security Hardening Lab Guide Page 13
PubkeyAuthentication yes
PasswordAuthentication no
1.7 Quiz
⚫ Can a common user switch to the root user after the root user is forbidden from
remote login during SSHD service hardening?
Answer: Yes.
OS Security Hardening Lab Guide Page 15
2 OS Network Security
2.1 Introduction
2.1.1 About This Lab
This lab describes how to use iptables and firewalld, and harden network security based
on the lab networking.
2.1.2 Objectives
⚫ Master the syntax rules of iptables.
⚫ Master firewalld commands.
Step 2 Check the status of iptables.service and enable it to be automatically started upon
system startup.
iptables -F
Step 2 Allow IP addresses from all sources to access TCP port 22 (OpenSSH).
Step 3 Allow the local host to access TCP port 22 (OpenSSH) of all hosts on the intranet
(192.168.0.0/24).
Step 6 Allow the local host to access UDP port 53 (DNS) of the remote host.
NAT is classified into source network address translation (SNAT) and destination network
address translation (DNAT).
2.2.3.1 SNAT
Step 1 Disable Source/Destination Check.
On the JumpServer ECS details page, click the Elastic NICs tab, unfold it, and set
Source/Destination Check to OFF.
sysctl -w net.ipv4.ip_forward=1
Step 5 Save iptables configurations and enable them to be automatically started upon
system startup.
Select a VPC to which a route is to be added and click Route Tables. On the Route
Tables page, click Add Route.
Enter the route information as prompted. Set the default gateway of the Server to the
private IP address of JmpServer.
2.2.3.2 DNAT
DNAT enables external users to directly access services provided by servers without
external IP addresses.
For example, an external user can access a web application on a server without a public
IP address through the Internet (the listening port is TCP 80).
Change the source IP address to the internal IP address of JumpServer. In this case, the
server communicates with JumpServer.
Step 4 Access the JumpServer public IP address (http://123.60.49.188/) to verify the lab
result.
Step 1 Install firewalld and enable it to be automatically started upon system startup.
Docs: man:firewalld(1)
Main PID: 24540 (firewalld)
Tasks: 2 (limit: 512)
CGroup: /system.slice/firewalld.service
└─24540 /usr/bin/python3 -Es /usr/sbin/firewalld --nofork –nopid
Select a VPC to which a route is to be added and click Route Tables. On the Route
Tables page, click Add Route.
Enter the route information as prompted. Set the default gateway of the Server to the
private IP address of JumpServer.
OS Security Hardening Lab Guide Page 22
As shown in the following, the server can access the external network.
2.3.2.2 DNAT
Step 1 Add port forwarding rules.
Step 2 Access the JumpServer public IP address (http://123.60.49.188/) to verify the lab
result.
OS Security Hardening Lab Guide Page 23
By default, firewalld provides more than 80 service groups. Check whether the HTTP
service is included.
Step 3 Add the HTTP service to the firewall zone and view the lab result.
Forward an access request to port 22 of the local host when 192.168.0.209 is used to
access port 5555.
2.4 Quiz
⚫ Can firewalld and iptables be used at the same time?
Answer: No. If iptables is directly used when firewalld is running, some unexpected
problems may occur. For example, if a user directly uses iptables to delete rules or chains,
the firewall may need to be reloaded to create them again.
OS Security Hardening Lab Guide Page 26
3.1 Introduction
3.1.1 About This Lab
When SELinux is enabled, the Apache HTTP server (httpd) is restricted by default.
Restricted processes run in their own domains and are separated from other restricted
processes. If a restricted process is attacked, the attacker's access to resources and
possible damage are also restricted due to SELinux policy configurations.
This lab demonstrates the impact of SELinux policies on httpd processes running in their
own domains.
3.1.2 Objectives
⚫ Be familiar with mandatory access control (MAC) models.
⚫ Master the identification and use of SELinux context information.
If BIOS is returned, modify the /etc/grub2.cfg file. If UEFI is returned, modify the
/etc/grub2-efi.cfg file.
Find the line starting with "linux" in the file and delete selinux=0.
Step 4 Check the SELinux ports that allow for httpd listening.
OS Security Hardening Lab Guide Page 30
Permissive
mkdir /home/mywebsite
echo "hello,openEuler!" > /home/mywebsite/index.html
chmod 755 /home/mywebsite
Modify the home directory of static resources and add the access permission.
If the returned content meets the expectation, the modification on the home page is
successful.
Step 5 Change the SELinux mode to enforcing and verify the access.
SELinux denies the httpd service's access to static resources because the context type
does not match.
3.3 Quiz
⚫ What are the differences between using the chcon and semanage fcontext
commands to modify the SELinux context?
Answer: The SELinux context modified by chon is not recorded in the file system. You can
run restorecon to restore the SELinux context to the default context. By contrast, the
SELinux context modified by semanage fcontext is recorded in the file system, and the
default context is modified.
⚫ Can SELinux replace firewalld to protect hosts?
Answer: SELinux can be used to guarantee data confidentiality and integrity and protect
processes from untrusted input, but it cannot replace security software such as firewalld.
Huawei openEuler Certification Training
HCIP-openEuler
System Monitoring
Lab Guide
ISSUE: 1.0
2
Copyright © Huawei Technologies Co., Ltd. 2024. All rights reserved.
No part of this document may be reproduced or transmitted in any form or by any
means without prior written consent of Huawei Technologies Co., Ltd.
and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd.
All other trademarks and trade names mentioned in this document are the property of
their respective holders.
Notice
The purchased products, services and features are stipulated by the contract made
between Huawei and the customer. All or part of the products, services and features
described in this document may not be within the purchase scope or the usage scope.
Unless otherwise specified in the contract, all statements, information, and
recommendations in this document are provided "AS IS" without warranties,
guarantees or representations of any kind, either express or implied.
The information in this document is subject to change without notice. Every effort has
been made in the preparation of this document to ensure accuracy of the contents, but
all statements, information, and recommendations in this document do not constitute
a warranty of any kind, express or implied.
Overview
This document is an HCIP-openEuler certification training course and is intended for
trainees who are going to take the HCIP-openEuler exam or readers who want to learn
about system performance metrics, basic monitoring commands, and Zabbix on
openEuler and other Linux distributions.
Description
This lab guide consists of six labs, covering basic usage of system monitoring commands
and Zabbix monitoring setup.
⚫ Lab 1: CPU performance metric practice
⚫ Lab 2: memory performance metric practice
⚫ Lab 3: drive I/O performance metric practice
⚫ Lab 4: network I/O performance metric practice
⚫ Lab 5: top performance analysis practice
⚫ Lab 6: Zabbix monitoring practice
Contents
1.1 Introduction
1.1.1 About This Lab
This lab describes how to use the basic commands for monitoring the CPU, memory, and
I/O performance metrics on openEuler.
1.1.2 Objectives
⚫ Master the usage of basic system monitoring commands.
⚫ Understand the meanings of CPU, memory, and I/O performance metrics.
In the multi-threaded scenario, the system load increases as the number of CPU context
switches per second reaches 3.2 million, accompanied by an increase in both voluntary
and involuntary task switches.
Step 3 Modify the permissions on the partition file and activate the swap partition.
[root@openEuler ~]# stress --vm 2 --vm-bytes 300M --vm-keep --timeout 300s &
[1] 6091
stress: info: [1247] dispatching hogs: 0 cpu, 0 io, 2 vm, 0 hdd
swappiness controls memory reclamation: the higher the value, the more actively the
kernel will use the swap space.
priority indicates the priority of the swap space: the higher the value, the higher the
priority, and the more likely the kernel will use it.
[root@openEuler ~]# stress --vm 7 --vm-bytes 500M --vm-hang 5 --timeout 300s &
[1] 6091
stress: info: [1361] dispatching hogs: 0 cpu, 0 io, 7 vm, 0 hdd
[root@openEuler ~]# sysbench --threads=4 --time=300 threads run --timeout 300s &
[1] 6091
sysbench 1.0.20 (using system LuaJIT 2.1.0-beta3)
mkdir /data
Start another terminal. You can see that the IOPS of drive sda is 7,705 and the
throughput is 120 Mbit/s.
The throughput of the ens3 interface is about 500,000 kilobytes per second.
# top
The following information is displayed from top to bottom: system time and load, task
status, CPU usage, memory and virtual memory, and processes under the fields.
HCIP-openEuler System Monitoring Lab Guide Page 9
Press the arrow keys to scroll and view fields and processes in the task area.
In this lab, numbers are left-aligned, texts are right-aligned, the multicolor mode is used,
and keywords are in bold.
Press keys for interactive commands to display or hide information in the summary area
or adjust information display.
Key Function
Key Function
In this lab, the usage of each CPU is displayed, and the display mode of CPU and memory
statistics in the summary area is modified.
Press f to go to the field management page. You can check the meaning of each field,
select required fields, and sort them.
Adjusts the
Exits the field
Up/Down location of a q
management page.
field.
In this lab, processes are sorted by the PID field, the TIME+ field is hidden, the PPID and
ENVIRON fields are added for display, and the PPID field is moved to the first column.
(1) The content under the ENVIRON field is not fully displayed. You can press the right
arrow key to scroll the view for the complete content.
HCIP-openEuler System Monitoring Lab Guide Page 11
(2) By default, processes in the task area are sorted in descending order based on the
selected field. You can press R to reverse the sorting order.
Toggles highlighting of
V Toggles the tree view. y
running tasks.
In this lab, a maximum of five processes are displayed, the tree view is enabled to
visualize parent-child process relationships, and the sorting field and running processes
are highlighted.
1.7 Quiz
⚫ How do you adjust the frequency at which the system uses the swap space?
Answer: Adjust the swappiness and priority of the swap space.
⚫ What is the difference between buff and cache in memory performance metrics?
Answer: buff is used to reduce the number of I/O responses and handle excessive
resource accesses. cache is a compromise strategy used to handle speed mismatches and
accelerate accesses.
HCIP-openEuler System Monitoring Lab Guide Page 12
yum install -y php-cli php-fpm php-gd php-mbstring php-bcmath php-xml php-ldap php-mysqlnd
server {
listen 0.0.0.0:80;
root /data/zabbix;
index index.php;
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
wget https://cdn.zabbix.com/zabbix/sources/oldstable/6.2/zabbix-6.2.8.tar.gz
After the download, run the tar command to decompress the package.
mkdir /etc/zabbix
./configure --sysconfdir=/etc/zabbix --enable-server --enable-agent --with-mysql --with-ssh2 --with-
zlib --with-libpthread --with-libevent --with-libpcre --with-net-snmp --with-libcurl --with-libxml2 --
with-openipmi --openssl --with-ldap
The following figure shows the information returned after the configuration.
make install
The following figure shows the information returned after the compilation and
installation.
HCIP-openEuler System Monitoring Lab Guide Page 14
The MySQL database is used in this lab, which shares the same VM with previous labs.
You only need to create a database and user for Zabbix on the original database server.
After the preceding configuration is complete, copy the files to be imported from Zabbix
to MySQL.
scp -r [email protected]:/root/zabbix-6.0.14/database/mysql .
Change the value of DBPassword to the password specified during user creation (line
123).
Copy all files in the ui directory of the source package to the specified root directory of
the Nginx service.
mkdir -p /data/zabbix/
cp -r /root/zabbix-6.2.8/ui/* /data/zabbix/
Enter the Zabbix IP address in the address box of the browser to access Zabbix and
deploy the web interface. The following figure shows its home page.
HCIP-openEuler System Monitoring Lab Guide Page 16
Click Next twice. On the database configuration page, complete the configuration as
planned.
After the configuration, click Next step. On the displayed page, set the parameters as
shown in the following figure.
HCIP-openEuler System Monitoring Lab Guide Page 17
After the configuration, click Next step. On the displayed page, check whether the
configuration is correct. If the configuration is correct, click Next step.
After the configuration, the system displays a message indicating that the installation is
complete, as shown in the following figure.
HCIP-openEuler System Monitoring Lab Guide Page 18
Click Finish. On the Zabbix web interface, enter the default username (Admin) and
password (zabbix), and click Sign In.
Modify the agent configuration file and specify the IP address of Zabbix server.
In the Monitoring area on the Zabbix home page, click Hosts. The following page is
displayed:
Click Create host in the upper right corner. On the displayed page, enter the host name
as planned.
Click Select following Templates to select a template. Preset templates are available.
Because the MySQL host runs in Linux and the MySQL database is running, you can enter
Operating systems or Databases in the search box to filter templates. The following
figure shows database-related templates. Select MySQL by Zabbix agent2.
HCIP-openEuler System Monitoring Lab Guide Page 20
You can also select multiple templates, as shown in the following figure:
Click Add in the Interfaces area, select Agent, and enter the agent information, as
shown in the following figure:
After the preceding configuration is complete, click Add to add the host. Then, you can
view the MySQL monitoring statistics, as shown in the following figure:
You can click Latest data, Graphs, or Dashboard to view the monitoring statistics in
respective forms. The following figure shows the dashboard view.
On the Zabbix home page, click Dashboard in the Monitoring area to view the global
information, as shown in the following figure.
HCIP-openEuler System Monitoring Lab Guide Page 22
In the Monitoring area, click Problems to view information about abnormal hosts, as
shown in the following figure.
Click the Ack status corresponding to a faulty host. The window for handling the problem
is displayed, as shown in the following figures.
HCIP-openEuler System Monitoring Lab Guide Page 23
After the update, the status of the problem will be updated, as shown in the following
figure.
This following uses the monitoring of online users of the MySQL server as an example to
describe how to create a custom monitoring item.
Create a User_MySQL.conf configuration file in the MySQL agent installation directory,
for example, /etc/zabbix/zabbix_agent2.d, and enter the following content to the file:
UserParameter=User.MySQL,who | wc -l
Restart the zabbix-agent2 server and run the zabbix_agent2 command to check whether
the value corresponding to the specified key can be obtained, as shown in the following
figure.
HCIP-openEuler System Monitoring Lab Guide Page 24
If the value cannot be obtained, adjust the command based on the command output. If
the value can be obtained, log in to the Zabbix server through the web interface, click
Hosts in the Configuration area, and select Items corresponding to MySQL, as shown in
the following figure.
On the displayed page, click Create item in the upper right corner and then set
parameters as planned.
HCIP-openEuler System Monitoring Lab Guide Page 25
After the configuration is complete, click Test. On the test page, click Get value and test
to check whether the corresponding value can be obtained, as shown in the following
figure.
HCIP-openEuler System Monitoring Lab Guide Page 26
If the returned value is normal, close the page and click Add.
Note: Zabbix has preset items for monitoring online users. You can refer to their
configurations to perform this lab.
In the Configuration area, click Hosts and select Triggers corresponding to MySQL, as
shown in the following figure.
On the displayed page, click Create trigger in the upper right corner. Enter the trigger
name and severity as planned.
After the configuration is complete, click Insert. The expression is added, as shown in the
following figure.
2.2 Quiz
⚫ What are the differences between the active and passive modes of Zabbix?
Answer: The passive mode is the default mode of Zabbix. In this mode, the server polls
the agent status. In active mode, the agent proactively reports information to the server,
which reduces the load of the server and thus accelerates server response.
Huawei openEuler Certification Training
HCIP-openEuler
Lab Guide
Issue: 1.0
2
Copyright © Huawei Technologies Co., Ltd. 2024. All rights reserved.
No part of this document may be reproduced or transmitted in any form or by any
means without prior written consent of Huawei Technologies Co., Ltd.
and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd.
All other trademarks and trade names mentioned in this document are the property of
their respective holders.
Notice
The purchased products, services and features are stipulated by the contract made
between Huawei and the customer. All or part of the products, services and features
described in this document may not be within the purchase scope or the usage scope.
Unless otherwise specified in the contract, all statements, information, and
recommendations in this document are provided "AS IS" without warranties,
guarantees or representations of any kind, either express or implied.
The information in this document is subject to change without notice. Every effort has
been made in the preparation of this document to ensure accuracy of the contents, but
all statements, information, and recommendations in this document do not constitute
a warranty of any kind, express or implied.
Overview
This document is an HCIP-openEuler certification training course and is intended for
trainees who are going to take the HCIP-openEuler exam or readers who want to learn
how to build enterprise services, shell scripts, or perform automated O&M using Zabbix
or Salt on openEuler and other Linux distributions.
Description
This lab guide introduces a comprehensive practice, which uses Ansible to set up an
enterprise website. The website can access static pages and internal blog systems. Static
data of the website is stored in the shared storage provided by GlusterFS, and dynamic
data is stored in the MySQL database. The domain name of the website is www.test.com.
Therefore, you need to configure the DNS to resolve the domain name to the IP address
of the web server. To monitor the status of each host, you need to also install and
configure Zabbix.
Contents
[Apache]
10.0.0.41 host=01
10.0.0.42 host=02
[Nginx]
10.0.0.13 host=01
10.0.0.14 host=02
[Gluster]
10.0.0.21 host=01
Comprehensive Practice Page 3
10.0.0.22 host=02
10.0.0.23 host=03
[Mysql]
10.0.0.31 host=01
10.0.0.32 host=02
[keepalive]
192.168.1.[11:12]
10.0.0.[21:23]
[lvs]
192.168.1.[11:12]
[dns]
192.168.1.13 host=dns
[zabbix]
192.168.1.15 host=zabbix
After the configuration is complete, use the ping module to test whether the
communication between the Ansible controller and all services is normal by running the
following command:
Compile playbook and change the host names of all ECSs to the planned values. The
following playbook content is for reference only:
---
- hosts: Nginx
remote_user: root
gather_facts: no
tasks:
- name: set hostname for Nginx
hostname:
name=Nginx-{{ host }}
- hosts: Mysql
remote_user: root
gather_facts: no
tasks:
- name: set hostname for Mysql
hostname:
name=Mysql-{{ host }}
- hosts: Gluster
remote_user: root
gather_facts: no
tasks:
- name: set hostname for Gluster
hostname:
Comprehensive Practice Page 4
name=Gluster-{{ host }}
- hosts: dns:zabbix
remote_user: root
gather_facts: no
tasks:
- name: set hostname for dns and zabbix
hostname:
name={{ host }}
Comprehensive Practice Page 5
2 Comprehensive Practice –
Implementation
Compile playbook to install Apache and PHP components on Apache1 and Apache2. The
following information is for reference:
---
- hosts: Apache
remote_user: root
gather_facts: no
tasks:
- name: install httpd
yum:
name: httpd
state: present
- name: enable and start httpd
service:
name: httpd
state: started
enabled: yes
- name: install php
yum:
name: php
state: present
- name: install php-mysqlnd
yum:
name: php-mysqlnd
state: present
---
- hosts: Mysql
remote_user: root
gather_facts: no
Comprehensive Practice Page 6
tasks:
- name: install mysql
yum:
name: mysql-server
state: present
- name: enable and start mysql
service:
name: mysqld
state: started
enabled: yes
---
- hosts: Nginx:Gluster
remote_user: root
gather_facts: no
tasks:
- name: install keepalived
yum:
name: keepalived
state: present
⚫ Question: In the preceding tasks, why does not start Keepalived after it is installed?
Answer: After Keepalived is installed, the configuration files of Keepalived on all hosts are
the same. If Keepalived is started at this time, the startup fails. Therefore, you are advised
to start Keepalived after it is configured.
Compile playbook to install Nginx components on Nginx1, Nginx2, and Zabbix. The
following information is for reference:
---
- hosts: Nginx:zabbix
remote_user: root
gather_facts: no
tasks:
- name: install nginx
yum:
name: nginx
state: present
- name: enable and start nginx
service:
name: nginx
state: started
enabled: yes
- hosts: zabbix
Comprehensive Practice Page 7
remote_user: root
gather_facts: no
tasks:
- name: install php
yum:
name: php
state: present
- name: config port of php
lineinfile:
path: /etc/php-fpm.d/www.conf
insertafter: "listen.allowed_clients = 127.0.0.1"
line: "listen = 9000"
- name: enable and start php
service:
name: php-fpm
state: started
enabled: yes
---
- hosts: Gluster
remote_user: root
gather_facts: no
tasks:
- name: install glusterfs-server
yum:
name: glusterfs-server
state: present
- name: enable and star glusterfs-server
service:
name: glusterd
state: started
enabled: yes
---
- hosts: dns
remote_user: root
gather_facts: no
tasks:
- name: install dns
yum:
name: bind
Comprehensive Practice Page 8
state: present
- name: enable and start named
service:
name: named
state: started
enabled: yes
Use playbook to initialize the database and set the password of the root user to
Huawei@123. The following information is for reference:
---
- hosts: Mysql
remote_user: root
gather_facts: no
tasks:
- name: set password for root
command: mysql -e "alter user root@'localhost' identified by 'Huawei@123';"
Set 10.0.0.31 as the master node of the MySQL cluster using playbook. The following
information is for reference:
---
- hosts: 10.0.0.31
remote_user: root
gather_facts: no
tasks:
- name: create user for replication
command: mysql -uroot -p"Huawei@123" -e "create user slave identified with
mysql_native_password by 'Huawei@123';"
- name: grant replication for slave
command: mysql -uroot -p"Huawei@123" -e "GRANT REPLICATION SLAVE ON *.* to
'slave'@'%';"
- name: enable privileges
tags: master
command: mysql -uroot -p"Huawei@123" -e "FLUSH PRIVILEGES;"
- name: config master
lineinfile:
path: /etc/my.cnf
line: "{{ item }}"
Comprehensive Practice Page 9
state: present
with_items:
- 'server-id=1'
- 'log-bin=/var/lib/mysql/binlog'
notify: restart mysqld
handlers:
- name: restart mysqld
service:
name: mysqld
state: restarted
Run the following command to view the current binary log name and offset of the
primary service:
Set 10.0.0.32 as the slave node of the MySQL cluster using playbook. The following
information is for reference:
---
- hosts: 10.0.0.32
remote_user: root
gather_facts: no
tasks:
- name: config slave
lineinfile:
path: /etc/my.cnf
line: "{{ item }}"
state: present
with_items:
- 'server-id=2'
- 'log-bin=/var/lib/mysql/binlog'
notify: restart slave
- name: choose master
tags: master
command: mysql -uroot -p"Huawei@123" -e "CHANGE MASTER TO
MASTER_HOST='10.0.0.31',MASTER_PORT=3306,MASTER_USER='slave',MASTER_PASSWORD='Huawei
@123',MASTER_LOG_FILE='binlog.000002',MASTER_LOG_POS=157;"
- name: start slave
tags: start
command: mysql -uroot -p"Huawei@123" -e "start slave;"
handlers:
- name: restart slave
service:
name: mysqld
Comprehensive Practice Page 10
state: restarted
If the status is Yes, the MySQL active/standby cluster is successfully created. Otherwise,
the creation fails. For details about the failure cause, see Last_IO_Error in the command
output.
Run the following command to create the database required by WordPress and set the
name of the created database to WP as planned:
After the creation is complete, check whether the WP is synchronized on the standby
node.
Create two partitions vdb1 and vdb2, both with 5 GB capacity, on the GlusterFS node.
Format the partitions as xfs and mount them to /mnt/point1 and /mnt/point2
respectively. point1 and point2 are storage blocks. For details about the playbook
content, see the following:
---
- hosts: Gluster
remote_user: root
gather_facts: no
tasks:
- name: create mount brick1
file:
path: /mnt/point1
state: directory
- name: create mount brick2
file:
path: /mnt/point2
state: directory
- name: install parted
yum:
name: parted
state: present
- name: create part1
parted:
device: /dev/vdb
number: 1
part_end: 5GiB
state: present
- name: create part2
parted:
device: /dev/vdb
number: 2
part_start: 5GiB
part_end: 10GiB
state: present
- name: install xfsprogs
yum:
name: xfsprogs
state: present
- name: format vdb1
filesystem:
dev: /dev/vdb1
fstype: xfs
force: yes
- name: format vdb2
filesystem:
Comprehensive Practice Page 12
dev: /dev/vdb2
fstype: xfs
force: yes
- name: mount vbd1
mount:
src: /dev/vdb1
path: /mnt/point1
fstype: xfs
state: mounted
- name: mount vbd2
mount:
src: /dev/vdb2
path: /mnt/point2
fstype: xfs
state: mounted
- name: config hosts
lineinfile:
path: /etc/hosts
line: "{{ item }}"
state: present
with_items:
- '10.0.0.21 Gluster-01'
- '10.0.0.22 Gluster-02'
- '10.0.0.23 Gluster-03'
Use Keepalived to configure three GlusterFS nodes as an HA cluster. First, create the
jinja2 template corresponding to the Keepalived configuration file. For details, see the
following content:
global_defs {
router_id {{ ansible_fqdn }}
}
vrrp_instance Nginx {
state {{ role }}
interface ens3
virtual_router_id 52
priority {{ priority }}
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
10.0.0.20/24
}
}
Use playbook to upload the template to each node and start the Keepalived service. Refer
to the following to configure playbook:
Comprehensive Practice Page 13
---
- hosts: 10.0.0.21
remote_user: root
vars:
- role: MASTER
- priority: 255
tasks:
- name: upload configuration to glusterfs
template: src=/root/yaml/file/keepalived.conf.j2 dest=/etc/keepalived/keepalived.conf
- name: restart keepalived
service:
name: keepalived
state: started
enabled: yes
- hosts: 10.0.0.22
remote_user: root
vars:
- role: BACKUP
- priority: 200
tasks:
- name: upload configuration to glusterfs
template: src=/root/yaml/file/keepalived.conf.j2 dest=/etc/keepalived/keepalived.conf
- name: restart keepalived
service:
name: keepalived
state: started
enabled: yes
- hosts: 10.0.0.23
remote_user: root
vars:
- role: BACKUP
- priority: 100
tasks:
- name: upload configuration to glusterfs
template: src=/root/yaml/file/keepalived.conf.j2 dest=/etc/keepalived/keepalived.conf
- name: restart keepalived
service:
name: keepalived
state: started
enabled: yes
Compile playbook and add PHP-related configurations to the Apache configuration file.
For details, see the following content:
---
- hosts: Apache
remote_user: root
gather_facts: no
tasks:
- name: config php
lineinfile:
path: /etc/httpd/conf/httpd.conf
insertafter: AddType application/x-gzip .gz .tgz
line: " AddType application/x-httpd-php .php"
According to the plan, WordPress files are stored in the /data/wp/ directory on the
Apache server, and static data is stored in the /data/image directory. Therefore, you
need to compile playbook to create the corresponding directories and mount the logical
volumes of GlusterFS to the corresponding directories as follows:
---
- hosts: Apache
remote_user: root
gather_facts: no
tasks:
- name: create wp
file:
path: /data/wp
owner: apache
group: apache
recurse: yes
state: directory
- name: create image
file:
path: /data/image
owner: apache
group: apache
recurse: yes
state: directory
- name: install glusterfs client
yum:
name: glusterfs-client
state: present
Comprehensive Practice Page 15
Create a configuration file for configuring the Apache virtual host in Ansible as follows:
<VirtualHost *:81>
ServerName localhost
DocumentRoot "/data/wp/"
<Directory "/data/wp">
AllowOverride None
Require all granted
</Directory>
</VirtualHost>
<VirtualHost *:82>
DocumentRoot "/data/image"
<Directory "/data/image">
AllowOverride None
Require all granted
</Directory>
ServerName localhost
</VirtualHost>
Use playbook to send the configuration to the Apache host and enable the corresponding
port as follows:
---
- hosts: Apache
remote_user: root
gather_facts: no
tasks:
- name: upload configure
Comprehensive Practice Page 16
copy:
src: /root/yaml/file/vhost.conf
dest: /etc/httpd/conf.d/vhost.conf
- name: set 81 and 82
lineinfile:
path: /etc/httpd/conf/httpd.conf
insertafter: Listen 80
line: "{{ item }}"
with_items:
- "Listen 81"
- "Listen 82"
- name: restart httpd
service:
name: httpd
state: restarted
Log in to an Apache host, for example, host 10.0.0.41, to perform the following
operations.
Create a static page for displaying images as follows:
<!DOCTYPE html>
<html>
<head>
<title>Image display page</title>
<style>
img {
max-width: 100%;
height: auto;
}
.separator {
border-top: 2px solid #000;
margin: 20px 0;
}
</style>
</head>
<body>
<h1>Image display page</h1>
<ul>
<li><img src="image1.png" alt="image1.png"></li>
<li class="separator"></li>
<li><img src="image2.png" alt="image2.png"></li>
<li class="separator"></li>
<li><img src="image3.png" alt="image3.png"></li>
<li class="separator"></li>
<li><img src="image4.png" alt="image4.png"></li>
</ul>
</body>
</html>
Save the file to the /data/image/ directory and upload four images named image1.png,
image2.png, image3.png, and image4.png to this directory. After the upload is complete,
the files in the /data/image/ directory are shown as follows.
Comprehensive Practice Page 17
⚫ Question: Why is only one Apache host required to perform the preceding
operations?
Answer: The same GlusterFS logical volumes are mounted to two Apache hosts.
Therefore, the data is consistent. Once you perform the operations on one Apache host,
you can view the same data on the other Apache host.
After all the preceding configurations are complete, use the EIP and port of the Apache
host to check whether the corresponding page can be accessed. Ensure that the page is
correct before performing subsequent operations.
On the Ansible host, create a layer-7 proxy configuration file required by Nginx and use
the planned addresses to access WordPress and images as follows:
upstream wp {
server blog.test.com;
}
upstream image {
server 10.0.0.41:82;
server 10.0.0.42:82;
}
server {
listen 80;
server_name 10.0.0.12;
location /blog/ {
proxy_pass http://wp/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Port $server_port;
}
location /image/ {
proxy_pass http://image/;
}
}
Note: WordPress writes the access address to the database. For example, 10.0.0.41:81 is
used during WordPress installation.
Comprehensive Practice Page 18
Use playbook to upload the file to the Nginx host and reload the Nginx service as
follows:
---
- hosts: Nginx
remote_user: root
tasks:
- name: upload configure
template:
src: /root/yaml/file/proxy.conf
dest: /etc/nginx/conf.d/proxy.conf
- name: reload nginx
service:
name: nginx
state: reloaded
Log in to the Nginx host and to set the gateway to the DIP of the active LVS:
nmcli con down "System enp4s4" && nmcli con up "System enp4s4"
Step 2 Use LVS and Keepalived to configure a layer-4 Proxy for Nginx.
global_defs {
router_id {{ ansible_fqdn }}
}
vrrp_instance LVS {
state {{ role }}
interface ens3
virtual_router_id 53
priority {{ priority }}
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.1.10/24
}
}
virtual_server 192.168.1.10 80 {
delay_loop 6
lb_algo rr
lb_kind NAT
persistence_timeout 50
Comprehensive Practice Page 19
protocol TCP
real_server 10.0.0.13 80 {
weight 1
TCP_CHECK {
connect_timeout 3
retry 3
delay_before_retry 3
}
}
real_server 10.0.0.14 80 {
weight 2
TCP_CHECK {
connect_timeout 3
retry 3
delay_before_retry 3
}
}
}
Compile playbook, upload the Keepalived configuration file to the corresponding host,
and restart the Keepalived service as follows:
---
- hosts: 192.168.1.11
remote_user: root
vars:
- role: MASTER
- priority: 255
tasks:
- name: upload configuration to Nginx
template: src=/root/yaml/file/lvs-keep.conf.j2 dest=/etc/keepalived/keepalived.conf
- name: restart keepalived
service:
name: keepalived
state: restarted
enabled: yes
- hosts: 192.168.1.12
remote_user: root
vars:
- role: BACKUP
- priority: 200
tasks:
- name: upload configuration to Nginx
template: src=/root/yaml/file/lvs-keep.conf.j2 dest=/etc/keepalived/keepalived.conf
- name: restart keepalived
service:
name: keepalived
state: restarted
enabled: yes
Comprehensive Practice Page 20
In this practice, there is only one DNS server. Therefore, you can directly log in to the
DNS server for configurations. According to the planning, you need to resolve
www.test.com to 192.168.1.10, add a record A (blog.test.com), and resolve it to
10.0.0.41 and 10.0.0.42. For details about the DNS configuration file, see the following:
$TTL 1D
@ IN SOA master.test.com. admin.test.com. (
0 ; serial
1D ; refresh
1H ; retry
1W ; expire
3H ) ; minimum
NS master
master A 192.168.1.10
www CNAME main
main A 192.168.1.10
blog A 10.0.0.41
blog A 10.0.0.42
use WP;
update wp_options set option_value="http://blog.test.com:81" where option_name="home";
update wp_options set option_value="http://blog.test.com:81" where option_name="siteurl";
---
- hosts: all
remote_user: root
gather_facts: no
tasks:
- name: install zabbix-release
Comprehensive Practice Page 21
Add all hosts on the Zabbix web page. The following figure shows some host information.
------------End----------------