开发
【摘要】 云服务器管理在云服务器的/root/huawei 目录下编写 create_server.py 文件,并导入提供的huaweicloudapi.py 文件获取连接。编写 Python 代码,调用 ecs 类,创建华为云的云服务器,具体要求为(1) 云服务器名称:chinaskills_server;(2) 云服务器可用区域:cn-north-4a;(3) 云服务器镜像:CentOS 7.5 ...
云服务器管理
在云服务器的/root/huawei 目录下编写 create_server.py 文件,并导入提供的huaweicloudapi.py 文件获取连接。编写 Python 代码,调用 ecs 类,创建华为云的云服务器,具体要求为
(1) 云服务器名称:chinaskills_server;
(2) 云服务器可用区域:cn-north-4a;
(3) 云服务器镜像:CentOS 7.5 64bit;
(4) 云服务系统盘:磁盘规格 SSD、大小 100G;
(5) 云服务数据盘:SSD、大小 50G;
(6) 云服务器规格:c6.large.2;
(7) 云服务器网络: chinaskills_subnet;
(8) 云服务器安全组:chinaskills_security_group;
(9) 云服务器组:chinaskills_server_group;
(10) 云服务器秘钥对:chinaskills_keypair;
(11) 云服务器弹性公网 IP:类型为全动态 BGP、带宽为 5 Mbit/s;
(12) 云服务器标签:chinaskills=true;
(13) 如果云服务器已经存在,代码中需要先删除;
(14) 以上需求可用直接使用其 ID,例如:镜像 ID、网络 ID 等等;
(15) 使用其源码的 get 方法输出此云服务器的详细信息。(云服务器状态要求为 ACTIVE 且数据盘挂载成功)
# coding: utf-8
import os
from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkecs.v2.region.ecs_region import EcsRegion
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkecs.v2 import (
NovaDeleteServersRequest,
NovaListServersDetailRequest,
NovaCreateServersRequestBody,
NovaServer,
NovaServerFlavorRef,
NovaServerVolume,
NovaServerSecurityGroup,
NovaServerNetwork,
NovaAvailabilityZone,
NovaServerCreateBody,
NovaServerCreate,
NovaServerDataVolume,
NovaServerPersonality,
NovaServerSecurityGroups,
NovaServerAddress,
NovaServerSchedulerHints,
NovaServerCreatePublicip,
NovaServerCreatePublicipOption,
NovaServerTags,
NovaShowServerRequest
)
if __name__ == "__main__":
# 从环境变量获取AK和SK
ak = "POK72LFEPD9SMELVI1SZ"
sk = "oL3k0BMSZoQXZdzVJt0kODTt1MKZ6gBQmIHVzBhL"
if not ak or not sk:
print("错误:请设置环境变量 CLOUD_SDK_AK 和 CLOUD_SDK_SK!")
exit(1)
credentials = BasicCredentials(ak, sk)
client = EcsClient.new_builder() \
.with_credentials(credentials) \
.with_region(EcsRegion.value_of("cn-north-4")) \
.build()
try:
server_name = "chinaskills_server" # 替换为你的云服务器名称
# 检查云服务器是否存在
list_servers_request = NovaListServersDetailRequest()
list_servers_response = client.nova_list_servers_detail(list_servers_request)
existing_server_id = None
for server in list_servers_response.servers:
if server.name == server_name:
existing_server_id = server.id
break
if existing_server_id:
# 删除已存在的云服务器
delete_servers_request = NovaDeleteServersRequest(server_ids=[existing_server_id])
client.nova_delete_servers(delete_servers_request)
print(f"已删除名为 {server_name} 的云服务器")
# 创建新的云服务器
image_id = "your_image_id_here" # 替换为 CentOS 7.5 64bit 的镜像 ID
flavor_ref = "c6.large.2" # 替换为 c6.large.2 规格
vpc_subnet_id = "your_subnet_id_here" # 替换为 chinaskills_subnet 的 ID
security_group_id = "your_security_group_id_here" # 替换为 chinaskills_security_group 的 ID
server_group_id = "your_server_group_id_here" # 替换为 chinaskills_server_group 的 ID
key_name = "chinaskills_keypair" # 密钥对名称
system_volume_size = 100 # 系统盘大小
data_volume_size = 50 # 数据盘大小
bandwidth_size = 5 # 弹性公网 IP 带宽大小
server_body = NovaServer(
name=server_name,
imageRef=image_id,
flavorRef=flavor_ref,
availability_zone="cn-north-4a",
adminPass="", # 设置管理员密码(可选)
key_name=key_name,
security_groups=[
NovaServerSecurityGroup(uuid=security_group_id)
],
networks=[
NovaServerNetwork(uuid=vpc_subnet_id)
],
scheduler_hints=NovaServerSchedulerHints(group=server_group_id),
personality=[
NovaServerPersonality(path="/root/.ssh/authorized_keys", contents="your_public_key_here"), # 添加公钥
],
volumes=[
NovaServerVolume(volumeId=""),
NovaServerDataVolume(volumeType="SSD", size=data_volume_size, bootIndex=-1), # 数据盘
],
data_volumes=[
NovaServerDataVolume(volumeType="SSD", size=system_volume_size, bootIndex=0), # 系统盘
],
tags=[
NovaServerTags(key="chinaskills", value="true")
],
publicip=NovaServerCreatePublicip(
create=NovaServerCreatePublicipOption(
type="5_bgp",
bandwidth={
"size": bandwidth_size
}
)
),
count=1
)
create_server_request_body = NovaCreateServersRequestBody(
server=server_body
)
create_server_request = NovaCreateServersRequest()
create_server_request.body = create_server_request_body
create_server_response = client.nova_create_servers(create_server_request)
created_server_id = create_server_response.job_id
print("创建云服务器成功:")
print(create_server_response)
# 等待云服务器状态变为 ACTIVE
from time import sleep
print("等待云服务器状态变为 ACTIVE...")
while True:
show_server_request = NovaShowServerRequest(server_id=created_server_id)
show_server_response = client.nova_show_server(show_server_request)
server_status = show_server_response.server.status
if server_status == "ACTIVE":
print("云服务器状态变为 ACTIVE")
break
else:
print(f"当前状态:{server_status},继续等待...")
sleep(10) # 每隔10秒检查一次
# 获取云服务器信息
show_server_request = NovaShowServerRequest(server_id=created_server_id)
show_server_response = client.nova_show_server(show_server_request)
print("云服务器详细信息:")
print(show_server_response)
# 输出云服务器的详细信息
server_info = show_server_response.server
print(f"云服务器名称:{server_info.name}")
print(f"云服务器状态:{server_info.status}")
print(f"系统盘大小:{server_info.data_volumes[0].size} GB")
print(f"数据盘大小:{server_info.data_volumes[1].size} GB")
print(f"弹性公网 IP:{server_info.addresses['subnet'][0]['addr']}")
except exceptions.ClientRequestException as e:
print("请求失败:")
print(f"状态码:{e.status_code}")
print(f"请求ID:{e.request_id}")
print(f"错误代码:{e.error_code}")
print(f"错误信息:{e.error_msg}")
弹性伸缩配置
在云服务器的/root/huawei 目录下编写 create_as_config.py 文件,并导入提供的 huaweicloudapi.py 文件获取连接。编写 Python 代码,调用 auto_scaling 类,创建华为云的弹性伸缩配置,具体要求为
(1) 伸缩配置名称:chinaskills_as_config;
(2) 镜像配置:CentOS 7.5 64bit;
(3) 磁盘配置:系统盘规格 SSD、大小 100G;数据盘规格 SSD、大小 50G;
(4) 规格配置:c6.large.2;
(5) 安全组配置:chinaskills_security_group;
(6) 秘钥对配置:chinaskills_keypair;
(7) 弹性公网配置:类型为全动态 BGP、带宽为 5 Mbit/s;
(8) 如果弹性伸缩配置已经存在,代码中需要先删除;
(9)使用其源码的 get 方法输出此弹性伸缩配置的详细信息。
# coding: utf-8
import os
from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkas.v1.region.as_region import AsRegion
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkas.v1 import (
CreateScalingGroupRequest,
CreateScalingGroupOption,
ListScalingGroupsRequest,
DeleteScalingGroupRequest,
ShowScalingGroupRequest,
VpcAndSubnet
)
if __name__ == "__main__":
# 从环境变量获取AK和SK
ak = "POK72LFEPD9SMELVI1SZ"
sk = "oL3k0BMSZoQXZdzVJt0kODTt1MKZ6gBQmIHVzBhL"
if not ak or not sk:
print("错误:请设置环境变量 CLOUD_SDK_AK 和 CLOUD_SDK_SK!")
exit(1)
credentials = BasicCredentials(ak, sk)
client = AsClient.new_builder() \
.with_credentials(credentials) \
.with_region(AsRegion.value_of("cn-north-4")) \
.build()
try:
scaling_group_name = "chinaskills_as_group" # 替换为你的伸缩组名称
# 伸缩配置 ID、VPC ID、子网 ID、安全组 ID 等需要替换为实际的 ID
scaling_config_id = "your_scaling_config_id_here" # 替换为实际的伸缩配置 ID
vpc_id = "your_vpc_id_here" # 替换为 chinaskills_vpc 的 ID
subnet_id = "your_subnet_id_here" # 替换为 chinaskills_subnet 的 ID
security_group_id = "your_security_group_id_here" # 替换为 chinaskills_security_group 的 ID
# 检查伸缩组是否存在
list_groups_request = ListScalingGroupsRequest()
list_groups_response = client.list_scaling_groups(list_groups_request)
existing_group_id = None
for group in list_groups_response.scaling_groups:
if group.scaling_group_name == scaling_group_name:
existing_group_id = group.scaling_group_id
break
if existing_group_id:
# 删除已存在的伸缩组
delete_group_request = DeleteScalingGroupRequest(scaling_group_id=existing_group_id)
client.delete_scaling_group(delete_group_request)
print(f"已删除名为 {scaling_group_name} 的伸缩组")
# 创建新的伸缩组
scaling_group_option = CreateScalingGroupOption(
scaling_group_name=scaling_group_name,
scaling_configuration_id=scaling_config_id,
vpc_and_subnet=VpcAndSubnet(
vpc_id=vpc_id,
subnet_id=subnet_id
),
min_instance_number=1,
desired_instance_number=2,
max_instance_number=3,
security_groups=[security_group_id],
health_periodic_audit_method="NOVA_API",
health_periodic_audit_time=10,
instance_terminate_policy="OLD_CONFIG_OLD_INSTANCE",
protection_from_scale_in=False,
deletion_protection=False,
ip_to_launch_with=EipOption(
bandwidth=EipBandwidthOption(
size=5,
share_type="PER"
)
),
network_interface_count=1,
multi_az_priority_policy="PRIORITY_BASED"
)
create_scaling_group_request = CreateScalingGroupRequest()
create_scaling_group_request.body = scaling_group_option
create_scaling_group_response = client.create_scaling_group(create_scaling_group_request)
created_group_id = create_scaling_group_response.scaling_group_id
print("创建伸缩组成功:")
print(create_scaling_group_response)
# 获取伸缩组信息
show_group_request = ShowScalingGroupRequest(scaling_group_id=created_group_id)
show_group_response = client.show_scaling_group(show_group_request)
print("伸缩组详细信息:")
print(show_group_response)
# 输出伸缩组的详细信息
scaling_group_info = show_group_response.scaling_group
print(f"伸缩组名称:{scaling_group_info.scaling_group_name}")
print(f"伸缩组 ID:{scaling_group_info.scaling_group_id}")
print(f"最小实例数:{scaling_group_info.min_instance_number}")
print(f"期望实例数:{scaling_group_info.desired_instance_number}")
print(f"最大实例数:{scaling_group_info.max_instance_number}")
print(f"VPC ID:{scaling_group_info.vpc_and_subnet.vpc_id}")
print(f"子网 ID:{scaling_group_info.vpc_and_subnet.subnet_id}")
print(f"安全组 ID:{scaling_group_info.security_groups[0]}")
print(f"弹性公网 IP 带宽大小:{scaling_group_info.ip_to_launch_with.bandwidth.size} Mbit/s")
except exceptions.ClientRequestException as e:
print("请求失败:")
print(f"状态码:{e.status_code}")
print(f"请求ID:{e.request_id}")
print(f"错误代码:{e.error_code}")
print(f"错误信息:{e.error_msg}")
弹性伸缩组管理
在云服务器的/root/huawei目录下编写create_as_group.py文件,并导入赛项提供的huaweicloudapi.py文件获取连接。编写Python代码,调用auto_scaling类,创建华为云的弹性伸缩组,具体要求为
(1)伸缩组名称:chinaskills_as_group;
(2)区域配置:cn-north-4a;
(3)弹性伸缩配置:chinaskills_as_config;
(4)vpc配置:chinaskills_vpc;
(5)子网配置:chinaskills_subnet;
(6)安全组配置:chinaskills_security_group;
(7)云服务器数配置:最大实例3台、最小实例1台、期望实例2台;
(8)配置弹性公网IP随实例释放;
(9)以上需求可用直接使用其ID,例如:网络ID、安全组ID等等;
(10)如果弹性伸缩组已经存在,代码中需要先删除;
(11)使用其源码的get方法输出此弹性伸缩组的详细信息。
完成后提交云服务器节点的用户名、密码和IP地址到答题框。
# coding: utf-8
import os
from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkas.v1.region.as_region import AsRegion
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkas.v1 import (
CreateScalingGroupRequest,
CreateScalingGroupOption,
ListScalingGroupsRequest,
DeleteScalingGroupRequest,
ShowScalingGroupRequest,
VpcAndSubnet
)
if __name__ == "__main__":
# 从环境变量获取AK和SK
ak = "POK72LFEPD9SMELVI1SZ"
sk = "oL3k0BMSZoQXZdzVJt0kODTt1MKZ6gBQmIHVzBhL"
if not ak or not sk:
print("错误:请设置环境变量 CLOUD_SDK_AK 和 CLOUD_SDK_SK!")
exit(1)
credentials = BasicCredentials(ak, sk)
client = AsClient.new_builder() \
.with_credentials(credentials) \
.with_region(AsRegion.value_of("cn-north-4")) \
.build()
try:
scaling_group_name = "chinaskills_as_group" # 替换为你的伸缩组名称
# 伸缩配置 ID、VPC ID、子网 ID、安全组 ID 等需要替换为实际的 ID
scaling_config_id = "your_scaling_config_id_here" # 替换为实际的伸缩配置 ID
vpc_id = "your_vpc_id_here" # 替换为 chinaskills_vpc 的 ID
subnet_id = "your_subnet_id_here" # 替换为 chinaskills_subnet 的 ID
security_group_id = "your_security_group_id_here" # 替换为 chinaskills_security_group 的 ID
# 检查伸缩组是否存在
list_groups_request = ListScalingGroupsRequest()
list_groups_response = client.list_scaling_groups(list_groups_request)
existing_group_id = None
for group in list_groups_response.scaling_groups:
if group.scaling_group_name == scaling_group_name:
existing_group_id = group.scaling_group_id
break
if existing_group_id:
# 删除已存在的伸缩组
delete_group_request = DeleteScalingGroupRequest(scaling_group_id=existing_group_id)
client.delete_scaling_group(delete_group_request)
print(f"已删除名为 {scaling_group_name} 的伸缩组")
# 创建新的伸缩组
scaling_group_option = CreateScalingGroupOption(
scaling_group_name=scaling_group_name,
scaling_configuration_id=scaling_config_id,
vpc_and_subnet=VpcAndSubnet(
vpc_id=vpc_id,
subnet_id=subnet_id
),
min_instance_number=1,
desired_instance_number=2,
max_instance_number=3,
security_groups=[security_group_id],
health_periodic_audit_method="NOVA_API",
health_periodic_audit_time=10,
instance_terminate_policy="OLD_CONFIG_OLD_INSTANCE",
protection_from_scale_in=False,
deletion_protection=False,
ip_to_launch_with=EipOption(
bandwidth=EipBandwidthOption(
size=5,
share_type="PER"
)
),
network_interface_count=1,
multi_az_priority_policy="PRIORITY_BASED"
)
create_scaling_group_request = CreateScalingGroupRequest()
create_scaling_group_request.body = scaling_group_option
create_scaling_group_response = client.create_scaling_group(create_scaling_group_request)
created_group_id = create_scaling_group_response.scaling_group_id
print("创建伸缩组成功:")
print(create_scaling_group_response)
# 获取伸缩组信息
show_group_request = ShowScalingGroupRequest(scaling_group_id=created_group_id)
show_group_response = client.show_scaling_group(show_group_request)
print("伸缩组详细信息:")
print(show_group_response)
# 输出伸缩组的详细信息
scaling_group_info = show_group_response.scaling_group
print(f"伸缩组名称:{scaling_group_info.scaling_group_name}")
print(f"伸缩组 ID:{scaling_group_info.scaling_group_id}")
print(f"最小实例数:{scaling_group_info.min_instance_number}")
print(f"期望实例数:{scaling_group_info.desired_instance_number}")
print(f"最大实例数:{scaling_group_info.max_instance_number}")
print(f"VPC ID:{scaling_group_info.vpc_and_subnet.vpc_id}")
print(f"子网 ID:{scaling_group_info.vpc_and_subnet.subnet_id}")
print(f"安全组 ID:{scaling_group_info.security_groups[0]}")
print(f"弹性公网 IP 带宽大小:{scaling_group_info.ip_to_launch_with.bandwidth.size} Mbit/s")
except exceptions.ClientRequestException as e:
print("请求失败:")
print(f"状态码:{e.status_code}")
print(f"请求ID:{e.request_id}")
print(f"错误代码:{e.error_code}")
print(f"错误信息:{e.error_msg}")
弹性伸缩组策略管理
在/root/huawei 目录下编写 crerate_as_policy_daily.py 文件,并导入提供的huaweicloudapi.py 文件获取连接。编写 Python 代码,调用 auto_scaling 类,创建华为云的弹性伸缩组策略,具体要求如下:
(1) 基于伸缩组:chinaskills_as_group(不允许直接使用其 ID)
(2) 伸缩策略名称:chinaskills_as_policy_daily
(3) 策略类型:周期策略
(4) 重复周期:按天
(5) 触发时间:00:00
(6) 生效时间: 2021-06-10T00:00Z 到 2021-12-31T00:00Z
(7) 执行动作:增加 1 实例
(8) 冷却时间:900 (秒)
(9) 如果伸缩策略已经存在,代码中需要先删除
(10) 使用其源码的 get 方法输出此伸策略的详细信息
# coding: utf-8
import os
from datetime import datetime, timezone
from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkas.v1.region.as_region import AsRegion
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkas.v1 import (
CreateScalingPolicyRequest,
CreateScalingPolicyOption,
ListScalingPoliciesRequest,
DeleteScalingPolicyRequest,
ShowScalingPolicyRequest,
ScalingPolicyAction,
RecurrenceValue,
ScheduledPolicy,
ScalingPolicy
)
if __name__ == "__main__":
# 从环境变量获取AK和SK
ak = "POK72LFEPD9SMELVI1SZ"
sk = "oL3k0BMSZoQXZdzVJt0kODTt1MKZ6gBQmIHVzBhL"
if not ak or not sk:
print("错误:请设置环境变量 CLOUD_SDK_AK 和 CLOUD_SDK_SK!")
exit(1)
credentials = BasicCredentials(ak, sk)
client = AsClient.new_builder() \
.with_credentials(credentials) \
.with_region(AsRegion.value_of("cn-north-4")) \
.build()
try:
scaling_policy_name = "chinaskills_as_policy_daily" # 伸缩策略名称
scaling_group_name = "chinaskills_as_group" # 基于伸缩组名称
# 获取伸缩组 ID
list_groups_request = ListScalingGroupsRequest()
list_groups_response = client.list_scaling_groups(list_groups_request)
scaling_group_id = None
for group in list_groups_response.scaling_groups:
if group.scaling_group_name == scaling_group_name:
scaling_group_id = group.scaling_group_id
break
if not scaling_group_id:
print(f"错误:找不到名为 {scaling_group_name} 的伸缩组!")
exit(1)
# 检查伸缩策略是否存在
list_policies_request = ListScalingPoliciesRequest()
list_policies_response = client.list_scaling_policies(list_policies_request)
existing_policy_id = None
for policy in list_policies_response.policies:
if policy.policy_name == scaling_policy_name:
existing_policy_id = policy.policy_id
break
if existing_policy_id:
# 删除已存在的伸缩策略
delete_policy_request = DeleteScalingPolicyRequest(policy_id=existing_policy_id)
client.delete_scaling_policy(delete_policy_request)
print(f"已删除名为 {scaling_policy_name} 的伸缩策略")
# 创建新的伸缩策略
scaling_policy_option = CreateScalingPolicyOption(
scaling_group_id=scaling_group_id,
policy_name=scaling_policy_name,
scheduled_action=ScalingPolicyAction(
operation="ADD",
value=1,
cooldown=900
),
scheduled_policy=ScheduledPolicy(
task_enabled=True,
start_time="2021-06-10T00:00Z",
end_time="2021-12-31T00:00Z",
recurrence_value=RecurrenceValue(
period="Daily",
begin_time="00:00"
)
)
)
create_policy_request = CreateScalingPolicyRequest()
create_policy_request.body = scaling_policy_option
create_policy_response = client.create_scaling_policy(create_policy_request)
created_policy_id = create_policy_response.policy_id
print("创建伸缩策略成功:")
print(create_policy_response)
# 获取伸缩策略信息
show_policy_request = ShowScalingPolicyRequest(policy_id=created_policy_id)
show_policy_response = client.show_scaling_policy(show_policy_request)
print("伸缩策略详细信息:")
print(show_policy_response)
# 输出伸缩策略的详细信息
scaling_policy_info = show_policy_response.policy
print(f"伸缩策略名称:{scaling_policy_info.policy_name}")
print(f"伸缩策略 ID:{scaling_policy_info.policy_id}")
print(f"生效开始时间:{scaling_policy_info.scheduled_policy.start_time}")
print(f"生效结束时间:{scaling_policy_info.scheduled_policy.end_time}")
print(f"重复周期:{scaling_policy_info.scheduled_policy.recurrence_value.period}")
print(f"触发时间:{scaling_policy_info.scheduled_policy.recurrence_value.begin_time}")
print(f"执行动作:增加 {scaling_policy_info.scheduled_action.value} 实例")
print(f"冷却时间:{scaling_policy_info.scheduled_action.cooldown} 秒")
except exceptions.ClientRequestException as e:
print("请求失败:")
print(f"状态码:{e.status_code}")
print(f"请求ID:{e.request_id}")
print(f"错误代码:{e.error_code}")
print(f"错误信息:{e.error_msg}")
【版权声明】本文为华为云社区用户原创内容,未经允许不得转载,如需转载请自行联系原作者进行授权。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
作者其他文章
评论(0)