本文介绍如何使用Alibaba Cloud SDK for Python为一个专有网络类型的ECS实例绑定一个弹性公网IP(EIP)。

前提条件

在使用Alibaba Cloud SDK for Python前,您需要完成以下准备工作:
  • 您需要一个阿里云账号和访问密钥(AccessKey)。 请在阿里云控制台中的AccessKey管理页面上创建和查看您的AccessKey。
  • 确保您已经安装了Alibaba Cloud SDK for Python,请参见aliyun-python-sdk-vpc 3.0.12
  • 下载阿里云专有网络Python SDK场景示例的VPC Python Example库
    进入 setup.py所在的目录,执行以下命令,完成环境初始化配置。
    1
    python setup.py install

背景信息

本文代码示例中包含以下操作:
  1. 在华东1(杭州)地域创建一个EIP。
  2. 将创建的EIP绑定到ECS。
  3. 查询绑定到ECS上的EIP。
  4. 修改EIP的带宽峰值和名称。
  5. 查询修改后的EIP。
  6. 将EIP与ECS解绑。
  7. 释放EIP。

操作步骤

  1. 在下载的SDK目录中,打开$aliyun-openapi-python-sdk-examples\sdk_examples\examples\eip文件夹。
  2. 使用编辑器打开eip_quick_start.py文件,根据实际情况配置相关参数,保存退出。
    完整代码示例如下:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    #encoding=utf-8
    import sys
    import json
    from aliyunsdkcore.acs_exception.exceptions import ServerException, ClientException
    from aliyunsdkvpc.request.v20160428 import AllocateEipAddressRequest
    from aliyunsdkvpc.request.v20160428 import AssociateEipAddressRequest
    from aliyunsdkvpc.request.v20160428 import DescribeEipAddressesRequest
    from aliyunsdkvpc.request.v20160428 import UnassociateEipAddressRequest
    from aliyunsdkvpc.request.v20160428 import ModifyEipAddressAttributeRequest
    from aliyunsdkvpc.request.v20160428 import ReleaseEipAddressRequest
    from sdk_lib.exception import ExceptionHandler
    from sdk_lib.check_status import CheckStatus
    from sdk_lib.consts import *
    from sdk_lib.common_util import CommonUtil
     
    """
    创建EIP->绑定EIP到ECS->查询EIP->修改EIP配置和名称->查询EIP->解绑EIP->释放EIP
    """
    class Eip(object):
        def __init__(self, client):
            self.client = client
     
        def allocate_eip_address(self, params):
            """
            allocate_eip_address: 申请弹性公网IP(EIP)
     
            """
            try:
                request = AllocateEipAddressRequest.AllocateEipAddressRequest()
                response = self.client.do_action_with_exception(request)
                response_json = json.loads(response)
                if CheckStatus.check_status(TIME_DEFAULT_OUT, DEFAULT_TIME,
                                            self.describe_eip_status,
                                            AVAILABLE, response_json["AllocationId"]):
                    return response_json
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
     
        def associate_eip_address(self, params):
            """
            associate_eip_address: 将EIP绑定到同地域的云产品实例上
     
            """
            try:
                request = AssociateEipAddressRequest.AssociateEipAddressRequest()
                # EIP的ID
                request.set_AllocationId(params['allocation_id'])
                # 要绑定的云产品实例的类型
                request.set_InstanceType(params['instance_type'])
                # 要绑定的实例ID
                request.set_InstanceId(params['instance_id'])
                response = self.client.do_action_with_exception(request)
                response_json = json.loads(response)
                if CheckStatus.check_status(TIME_DEFAULT_OUT, DEFAULT_TIME,
                                            self.describe_eip_status,
                                            InUse, params['allocation_id']):
                    return response_json
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
     
        def describe_eip_address(self, allocation_id):
            """
            describe_eip_status: 查询指定地域已创建的EIP
     
            """
            try:
                request = DescribeEipAddressesRequest.DescribeEipAddressesRequest()
                # EIP的ID
                request.set_AllocationId(allocation_id)
                response = self.client.do_action_with_exception(request)
                response_json = json.loads(response)
                return response_json
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
     
        def describe_eip_status(self, allocation_id):
            """
            describe_eip_status: 查询指定地域已创建的EIP的状态
     
            """
            # EIP的ID
            response = self.describe_eip_address(allocation_id)
            return response["EipAddresses"]["EipAddress"][0]["Status"]
     
     
        def unassociate_eip_address(self, params):
            """
            unassociate_eip_address: 将EIP从绑定的云资源上解绑
     
            """
            try:
                request = UnassociateEipAddressRequest.UnassociateEipAddressRequest()
                # EIP的ID
                request.set_AllocationId(params['allocation_id'])
                # 要解绑的资源类型
                request.set_InstanceType(params['instance_type'])
                # 要解绑的云产品的实例ID
                request.set_InstanceId(params['instance_id'])
                response = self.client.do_action_with_exception(request)
                response_json = json.loads(response)
                if CheckStatus.check_status(TIME_DEFAULT_OUT, DEFAULT_TIME,
                                            self.describe_eip_status,
                                            AVAILABLE, params['allocation_id']):
                    return response_json
                return response_json
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
     
        def modify_eip_address(self, params):
            """
            modify_eip_address: 修改指定EIP的名称、描述信息和带宽峰值
     
            """
            try:
                request = ModifyEipAddressAttributeRequest.ModifyEipAddressAttributeRequest()
                # EIP的ID
                request.set_AllocationId(params['allocation_id'])
                # EIP的带宽峰值,单位为Mbps
                request.set_Bandwidth(params['bandwidth'])
                # EIP的名称
                request.set_Name(params['name'])
                response = self.client.do_action_with_exception(request)
                response_json = json.loads(response)
                return response_json
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
     
        def release_eip_address(self, params):
            """
            release_eip_address: 释放指定的EIP
     
            """
            try:
                request = ReleaseEipAddressRequest.ReleaseEipAddressRequest()
                # 要释放的EIP的ID
                request.set_AllocationId(params['allocation_id'])
                response = self.client.do_action_with_exception(request)
                response_json = json.loads(response)
                return response_json
            except ServerException as e:
                ExceptionHandler.server_exception(e)
            except ClientException as e:
                ExceptionHandler.client_exception(e)
     
    def main():
     
        client = AcsClient(
                '<your-access-key-id>',     # 您的AccessKey ID
                '<your-access-key-secret>', # 您的AccessKey Secret
                '<your-region-id>')         # 您的地域ID
     
        params = {}
        # 创建EIP
        eip_response_json = eip.allocate_eip_address(params)
        CommonUtil.log("allocate_eip_address", eip_response_json)
     
        # 绑定EIP到ECS
        params['allocation_id'] = eip_response_json["AllocationId"]
        params['instance_id'] = ECS_INSTANCE_ID
        params['instance_type'] = 'EcsInstance'
        eip_response_json = eip.associate_eip_address(params)
        CommonUtil.log("associate_eip_address", eip_response_json)
     
        # 查询EIP
        eip_response_json = eip.describe_eip_address(params['allocation_id'])
        CommonUtil.log("describe_eip_address", eip_response_json)
     
        # 修改EIP配置和名称
        params['bandwidth'] = BANDWIDTH_50
        params['name'] = EIP_NEW_NAME
        eip_response_json = eip.modify_eip_address(params)
        CommonUtil.log("modify_eip_address", eip_response_json)
     
        # 查询EIP
        eip_response_json = eip.describe_eip_address(params['allocation_id'])
        CommonUtil.log("describe_eip_address", eip_response_json)
     
        # 解绑EIP
        eip_response_json = eip.unassociate_eip_address(params)
        CommonUtil.log("unassociate_eip_address", eip_response_json)
     
        # 释放EIP
        eip_response_json = eip.release_eip_address(params)
        CommonUtil.log("release_eip_address", eip_response_json)
     
    if __name__ == '__main__':
        sys.exit(main())
  3. 进入eip_quick_start.py所在的目录,执行如下命令,将EIP绑定到ECS实例。
    1
    python eip_quick_start.py

执行结果

系统回显结果如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
---------------------------allocate_eip_address---------------------------
{
  "EipAddress": "47.XX.XX.23",
  "ResourceGroupId": "rg-acfm4od****",
  "RequestId": "C438312E-F7A4-4A04-901F-D22FE23EDB4D",
  "AllocationId": "eip-bp1wybucvhhx5****"
}
---------------------------associate_eip_address---------------------------
{
  "RequestId": "6EC6605E-3D2B-4EE8-BD13-F1964CD1EAB1"
}
---------------------------describe_eip_address---------------------------
{
  "TotalCount": 1,
  "PageNumber": 1,
  "PageSize": 10,
  "EipAddresses": {
    "EipAddress": [
      {
        "ISP": "BGP",
        "ExpiredTime": "",
        "InternetChargeType": "PayByBandwidth",
        "IpAddress": "47.XX.XX.23",
        "AllocationId": "eip-bp1wybucvhhx5****",
        "PrivateIpAddress": "",
        "Status": "InUse",
        "BandwidthPackageId": "",
        "InstanceId": "i-bp1e82xlhob2****",
        "InstanceRegionId": "cn-hangzhou",
        "RegionId": "cn-hangzhou",
        "AvailableRegions": {
          "AvailableRegion": [
            "cn-hangzhou"
          ]
        },
        "ResourceGroupId": "rg-acfm4od****",
        "HasReservationData": false,
        "InstanceType": "EcsInstance",
        "AllocationTime": "2019-04-17T11:57:43Z",
        "Name": "",
        "OperationLocks": {
          "LockReason": []
        },
        "Mode": "NAT",
        "BandwidthPackageType": "",
        "BandwidthPackageBandwidth": "",
        "Bandwidth": "5",
        "HDMonitorStatus": "OFF",
        "ChargeType": "PostPaid",
        "SecondLimited": false,
        "Descritpion": ""
      }
    ]
  },
  "RequestId": "8715A878-A808-4CC4-AAD5-E414FDAB5B0E"
}
---------------------------modify_eip_address---------------------------
{
  "RequestId": "2108AE1C-94FB-475D-BFEE-EC88598BF6A6"
}
---------------------------describe_eip_address---------------------------
{
  "TotalCount": 1,
  "PageNumber": 1,
  "PageSize": 10,
  "EipAddresses": {
    "EipAddress": [
      {
        "ISP": "BGP",
        "ExpiredTime": "",
        "InternetChargeType": "PayByBandwidth",
        "IpAddress": "47.XX.XX.23",
        "AllocationId": "eip-bp1wybucvhhx5****",
        "PrivateIpAddress": "",
        "Status": "InUse",
        "BandwidthPackageId": "",
        "InstanceId": "i-bp1e82xlhob2****",
        "InstanceRegionId": "cn-hangzhou",
        "RegionId": "cn-hangzhou",
        "AvailableRegions": {
          "AvailableRegion": [
            "cn-hangzhou"
          ]
        },
        "ResourceGroupId": "rg-acfm4od****",
        "HasReservationData": false,
        "InstanceType": "EcsInstance",
        "AllocationTime": "2019-04-17T11:57:43Z",
        "Name": "EIP_NEW_NAME",
        "OperationLocks": {
          "LockReason": []
        },
        "Mode": "NAT",
        "BandwidthPackageType": "",
        "BandwidthPackageBandwidth": "",
        "Bandwidth": "50",
        "HDMonitorStatus": "OFF",
        "ChargeType": "PostPaid",
        "SecondLimited": false,
        "Descritpion": ""
      }
    ]
  },
  "RequestId": "6694D35B-B5DD-4506-8AB1-2D16477646DE"
}
---------------------------unassociate_eip_address---------------------------
{
  "RequestId": "EDE86CF6-EE68-4922-B919-85A4F11BF668"
}
---------------------------release_eip_address---------------------------
{
  "RequestId": "53FEE062-B595-4D64-AB47-834015D32888"
}