Here’s a script to start an EC2 instance and assign an elastic ip to said instance. I knocked this together from a couple of other scripts, to which I don’t have the link to anymore.
param( [string]$instanceID = "InstanceID", [string]$keyID = "KeyID", [string]$accessKeyID = "SecretAccessKeyID", [string]$EIP = "xx.xx.xx.xx", [string]$ServiceURL="https://ec2.us-east-1.amazonaws.com" ) cls Add-Type -Path "C:\Program Files (x86)\AWS SDK for .NET\bin\AWSSDK.dll" $config=New-Object Amazon.EC2.AmazonEC2Config $config.ServiceURL = $ServiceURL $ec2 = [Amazon.AWSClientFactory]::CreateAmazonEC2Client($keyID,$accessKeyID, $config) $startReq = New-Object amazon.EC2.Model.StartInstancesRequest $startReq.InstanceId.Add($instanceID); $startResponse = $ec2.StartInstances($startReq) $startResult = $startResponse.StartInstancesResult; $startResult $request = New-Object -TypeName Amazon.EC2.Model.DescribeAddressesRequest [void]$request.WithPublicIp($EIP) $result = New-Object -TypeName Amazon.EC2.Model.DescribeAddressesResponse try { $result = $client.DescribeAddresses($request) } catch { echo "Failed to validate EIP $instanceEIP, ensure that it is allocated and associated with your account. Aborting." exit 2 } # See if an instanceID is already assigned to this EIP $xml = $result.ToXML() $assignedInstanceID = [string]($xml.DescribeAddressesResponse.DescribeAddressesResult.Address.InstanceId) # Run this block if an Instance already has this EIP associated to it... just in case changes would # result in downtime (i.e. if we are launching a test system from a cloned production one). if ($assignedInstanceID) { echo "Address $EIP already assigned to: $assignedInstanceID, aborting." exit 1 } # If we get here, the IP is free and clear, go ahead and associate it. $request = New-Object -TypeName Amazon.EC2.Model.AssociateAddressRequest [void]$request.WithInstanceId($instanceID) [void]$request.WithPublicIp($EIP) $result = $client.AssociateAddress($request) if ($result) { echo "Address $EIP assigned to $instanceID successfully." exit 0 } else { echo "Failed to assign $EIP to $instanceID." exit 3 }
Here is the code to stop an instance.
param( [string]$instanceID = "InstanceID", [string]$keyID = "KeyID", [string]$accessKeyID = "AccessKeyID" ) Add-Type -Path "C:\Program Files (x86)\AWS SDK for .NET\bin\AWSSDK.dll" $ec2 = [Amazon.AWSClientFactory]::CreateAmazonEC2Client($keyID,$accessKeyID) $stopReq = New-Object amazon.EC2.Model.StopInstancesRequest $stopReq.InstanceId.Add($instanceID); $stopResponse = $ec2.StopInstances($stopReq) $stopResult = $stopResponse.StopInstancesResult;