Referencing Security Groups in EC2 Powershell

So I ran into something that isn't particularly well explained in the EC2 security group documentation.

EC2 has a useful feature that allows you to reference another security group by id as a source/destination when creating rules on security groups.

However upon perusing the EC2 Powershell documentation it wasn't immediately clear to be how to do this with Powershell.

To add a IP based rule you would do something like the following:
$rule = new-object Amazon.EC2.Model.IpPermission $rule.IpProtocol = "tcp" $rule.FromPort = 3389 $rule.ToPort = 3389 $rule.IpRanges.Add("10.0.0.0/8") Grant-EC2SecurityGroupIngress -GroupId $sgid -IpPermissions @($rule)

I initially tried adding the security group id to the IpRanges attribute with no success.

After some google-fu and rtfm-ing it turns out you need to use the UserIdGroupPair attribute of the IpPermissions object. This attribute accepts input in the form of the Amazon.EC2.Model.UserIdGroupPair object.

$securityGroup = New-Object Amazon.EC2.Model.UserIdGroupPair $securityGroup.GroupId = "sg-123456"

Where sg-123456 is the group you wish to reference.
Leading to your overall rule creation process looking like this.

$rule = new-object Amazon.EC2.Model.IpPermission $rule.IpProtocol = "tcp" $rule.FromPort = 3389 $rule.ToPort = 3389 $rule.UserIdGroupPair = $securityGroup Grant-EC2SecurityGroupIngress -GroupId $sgid -IpPermissions @($rule)

comments powered by Disqus