使用公有 IP 在 VPC 中启动 EC2 实例

本文关键字:启动 EC2 实例 VPC IP | 更新日期: 2023-09-27 17:56:23

InstanceNetworkInterfaceSpecification vpc = new InstanceNetworkInterfaceSpecification()
{
SubnetId = "subnet-sadfsadf",
    AssociatePublicIpAddress = true,
    DeleteOnTermination = false
};
List<InstanceNetworkInterfaceSpecification> temp= new List<InstanceNetworkInterfaceSpecification>();
            temp.Add(vpc);
//Create and initialize a RunInstanceRequest
RunInstancesRequest newInstanceRequest = new RunInstancesRequest()
{
   ImageId = appdbAMI,
   InstanceType = appdbType,
   MinCount = 1,
   MaxCount = appdbQuantity,
   KeyName = ec2Key,
   NetworkInsterfaces = temp,
   BlockDeviceMappings = resp.Images[0].BlockDeviceMappings
   //DisableApiTermination = true
};

这不会在具有公有 IP 地址的 VPC 中启动实例。它有什么问题?我想在 VPC 中启动一个实例,该 VPC 还为其分配了一个公有 IP 地址。

使用公有 IP 在 VPC 中启动 EC2 实例

正确的格式:我忘了在实例网络接口规范中添加设备索引。我为安全组创建字符串列表。然后,我创建 createnetworkinterfacerequest 对象并添加子网 ID 和安全组。然后创建创建网络接口响应对象并创建接口。接下来,我创建实例网络接口规范项并将其添加到列表中。最后我运行运行实例请求并砰的一声,它起作用了。

List<string> secgrps = new List<string>(new string[] { "sg-2143", "sg-1234" });
CreateNetworkInterfaceRequest cnireq = new CreateNetworkInterfaceRequest()
{ 
SubnetId = "subnet-1234", 
Groups = secgrps 
};
CreateNetworkInterfaceResponse cniresp = ec2Client.CreateNetworkInterface(cnireq);
InstanceNetworkInterfaceSpecification inis = new InstanceNetworkInterfaceSpecification()
{ 
SubnetId = cniresp.NetworkInterface.SubnetId, 
Groups = secgrps, 
AssociatePublicIpAddress = true, 
DeviceIndex=0 
};
List<InstanceNetworkInterfaceSpecification> inisList = new List<InstanceNetworkInterfaceSpecification>();
inisList.Add(inis);
//Create and initialize a RunInstanceRequest
RunInstancesRequest newInstanceRequest = new RunInstancesRequest()
{
    ImageId = appdbAMI,
    InstanceType = appdbType,
    MinCount = 1,
    MaxCount = appdbQuantity,
    KeyName = ec2Key,
    //SecurityGroups = appdbSecurity,
    NetworkInterfaces = inisList,
    BlockDeviceMappings = resp.Images[0].BlockDeviceMappings
    //DisableApiTermination = true
};