Search code examples
powershellamazon-ec2aws-cliaws-powershell

How to launch an EC2 instance into a VPC with a public IP address in PowerShell?


I have been trying to use the following script, but haven't been successful:

$Ami=Get-EC2ImageByName WINDOWS_2012_BASE

New-EC2Instance -ImageId $Ami[0].ImageId -MinCount 1 -MaxCount 1 -KeyName uckey -InstanceType `
t1.micro -SubnetId subnet-56738b33 -AssociatePublicIp $true

The error is:

New-EC2Instance : Object reference not set to an instance of an object.
At line:1 char:1
+ New-EC2Instance -ImageId $Ami[0].ImageId -MinCount 1 -MaxCount 1 -KeyName uckey  ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (Amazon.PowerShe...2InstanceCmdlet:NewEC2InstanceCmdlet)  
   [New-EC2Instance], InvalidOperationException
    + FullyQualifiedErrorId : System.NullReferenceException,Amazon.PowerShell.Cmdlets.EC2.NewEC2InstanceC 
   mdlet

The problem is about the parameter -AssociatePublicIp without it, the script works.

Thanks for reading


Solution

  • I ran into the same problem, and a possible workaround while still using PowerShell is to create the network interface first, and then associating it with the instance:

    $subnetId = "subnet-56738b33"
    $keyName = "uckey"
    $instanceType = "t1.micro"
    
    $Ami = Get-EC2ImageByName WINDOWS_2012_BASE
    $ImageId = $Ami[0].ImageId
    
    $networkInterface = New-EC2NetworkInterface -SubnetId $subnetId -Description "Primary network interface"
    
    $interfaceSpec = New-Object Amazon.EC2.Model.InstanceNetworkInterfaceSpecification -property @{"NetworkInterfaceId"=$networkInterface.NetworkInterfaceId}
    
    $reservation = New-EC2Instance -ImageId $ImageId -MinCount 1 -MaxCount 1 -InstanceType $instanceType -KeyName $keyName -NetworkInterfaces $interfaceSpec
    

    The InstanceNetworkInterfaceSpecification has a property to indicate if the interface needs a public IP address (see the docs)