How to start an Amazon EC2 instance programmatically in .NET

前端 未结 5 1793
醉话见心
醉话见心 2020-12-28 09:03

I have been attempting to start an instance of EC2 in C# without luck.

When passing in an instance id to start the instance I get an error that the instance cannot b

5条回答
  •  旧巷少年郎
    2020-12-28 09:32

    Try something like this with the AWSSDK to start new instances of an "image id":

    RunInstancesResponse response = Client.RunInstances(new RunInstancesRequest()
      .WithImageId(ami_id)
      .WithInstanceType(instance_type)
      .WithKeyName(YOUR_KEYPAIR_NAME)
      .WithMinCount(1)
      .WithMaxCount(max_number_of_instances)
      .WithUserData(Convert.ToBase64String(Encoding.UTF8.GetBytes(bootScript.Replace("\r", ""))))
    );
    

    (Note: The .WithUserData() is optional and is used above to pass a short shell script.)

    If the call is successful the response should contain a list of instances. You can use something like this to create a list of "instance ids":

    if (response.IsSetRunInstancesResult() && response.RunInstancesResult.IsSetReservation() && response.RunInstancesResult.Reservation.IsSetRunningInstance())
    {
         List instance_ids = new List();
         foreach (RunningInstance ri in response.RunInstancesResult.Reservation.RunningInstance)
         {
              instance_ids.Add(ri.InstanceId);
         }
    
         // do something with instance_ids
         ...
    }
    

提交回复
热议问题