Boto3:如何创建和标记虚拟专用网关[create_vpn_Gateway()]

2024-04-26 13:50:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我仍在琢磨boto3并试图找出如何正确地创建和标记Virtual Private Gateway并将其附加到VPC。在

ec2_inst = boto.Session(profile_name='my_profile').resource('ec2')
vpg = ec2_inst.create_vpn_gateway(Type='ipsec.1', AmazonSideAsn=64512)

但我得到:AttributeError: 'ec2.ServiceResource' object has no attribute 'create_vpn_gateway'(可能是因为显而易见的原因)。如果我将代码改为使用client('ec2'),那么它可以工作:

^{pr2}$

我知道resources()client()的高级包装器,并没有涵盖所有client()功能,但是有没有一种方法可以像我在其余代码中一样使用create_vpn_gateway()using resource()?在

另外,我如何Tag创建的网关和attach到VPC?这也不起作用:

vpg.create_tags(
    Tags = [ { 'Key': 'Name', 'Value': 'MY-VPG' }, ]
)
vpg.attach_to_vpc(VpcId=vpc.vpc_id)

为既没有“create”标记也没有“attach”vpn\u gateway属性的“dict”对象提供AttributeError。你知道我该怎么做吗?最好的!在


Tags: 代码标记clientcreatevpnec2profilevpc
1条回答
网友
1楼 · 发布于 2024-04-26 13:50:40

boto3.resource用于ec2操作,您可以从<ServiceResource>.meta.client访问客户机。在

import boto3

TAGS = [{'Key':'label', 'Value': 'test'}]

ec2 = boto3.resource('ec2')

vpc = list(ec2.vpcs.all())[0]  # or make a new vpc & subnet: 
# https://github.com/boto/boto3/tree/1.4.8/docs/source/guide/migrationec2.rst#creating-a-vpc-subnet-and-gateway

operation_result = ec2.meta.client.create_vpn_gateway(Type='ipsec.1')
try:
    gateway_id = operation_result['VpnGateway']['VpnGatewayId'] 
    ec2.meta.client.attach_vpn_gateway(VpcId=vpc.id, VpnGatewayId=gateway_id)

    ec2.create_tags(Tags=TAGS, Resources=[gateway_id])
except KeyError:
    print('Failed to create VPN gateway.')

相关问题 更多 >