如何在 request_spot_instances 中附加 VPC 和子网?

How to attach VPC and subnet in request_spot_instances?

我们有多个子网和 VPC。如何在 request_spot_instances 期间定义特定的子网和 VPC?

以下是我的代码:

client = boto3.client('ec2')

response = client.request_spot_instances(
    DryRun=False,
    ClientToken=''.join(random.choices(string.ascii_lowercase + string.digits, k=10)),
    InstanceCount=1,
    Type='one-time',
    LaunchSpecification={
        'ImageId': 'ami-db710fa3',
        'KeyName': 'my_key',
        'InstanceType': 'm4.4xlarge',
        'Placement': {
            'AvailabilityZone': 'us-east-2a',
        },
        'BlockDeviceMappings': [
            {
                'Ebs': {
                    # 'SnapshotId': 'snap-f70deff0',
                    'VolumeSize': 100,
                    'DeleteOnTermination': True,
                    'VolumeType': 'gp2',
                    'Iops': 300,
                    'Encrypted': False
                },
            },
        ],

        'EbsOptimized': True,
        'Monitoring': {
            'Enabled': True
        },
        'SecurityGroupIds': ['sg-1231231' ],
        'NetworkInterfaces': [
            {
                'DeviceIndex': 123,
                'SubnetId': 'Subnet-df123123'
            },
        ],

    }
)

但是,上面的代码会抛出错误,

botocore.exceptions.ClientError: An error occurred (InvalidParameterCombination) when calling the RequestSpotInstances operation: Network interfaces and an instance-level security groups may not be specified on the same request

感谢任何帮助谢谢

错误说明了一切:不能在同一请求上指定网络接口和实例级安全组

这是因为 NetworkInterfaces 有一个名为 Groups 的子参数,您可以在其中指定安全组。这是必需的,因为可以指定多个网络接口,每个接口具有不同的安全组。

如果 NetworkInterfaces 未指定 ,您可以使用 SecurityGroupIds(与 NetworkInterfaces 处于同一级别)并且组将是应用于使用实例创建的默认网络接口。

因此,如果您实际上并不需要 'DeviceIndex': 123,只需删除整个 NetworkInterfaces 位就可以了。