Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Create AWS security groups and configure ingress rules via lookups with PowerShell
#Requires Modules AWSPowerShell
$myonlyvpc = (Get-EC2Vpc).VpcId
$elbsg = New-EC2SecurityGroup -VpcId $myonlyvpc -GroupName "My ELB Security Group" -Description "Created by script on $((Get-Date).tostring('u'))"
New-EC2Tag -ResourceId $elbsg -Tag @{Key="Name"; Value="My ELB Security Group"}
$httpallowall = New-Object Amazon.EC2.Model.IpPermission -Property @{IpProtocol=”tcp”;FromPort=80;ToPort=80;IpRanges="0.0.0.0/0"}
$httpsallowall = New-Object Amazon.EC2.Model.IpPermission -Property @{IpProtocol=”tcp”;FromPort=443;ToPort=443;IpRanges="0.0.0.0/0"}
$elbsgpermissions = New-Object System.Collections.ArrayList
$elbsgpermissions.Add($httpallowall) | Out-Null
$elbsgpermissions.Add($httpsallowall) | Out-Null
Grant-EC2SecurityGroupIngress -GroupId $elbsg -IpPermission $elbsgpermissions
$websg = New-EC2SecurityGroup -VpcId $myonlyvpc -GroupName "My Web Server Security Group" -Description "Created by script on $((Get-Date).tostring('u'))"
New-EC2Tag -ResourceId $websg -Tag @{Key="Name"; Value="My Web Server Security Group"}
$elbuseridgrouppair = New-Object Amazon.EC2.Model.UserIdGroupPair
$elbuseridgrouppair.GroupId = $elbsg
$bastionhostuseridgrouppair = New-Object Amazon.EC2.Model.UserIdGroupPair
$bastionhostsgid = Get-EC2SecurityGroup -Filter @{Name=”vpc-id”;Value=$((Get-EC2Vpc).VpcId)} | ? {$_.GroupName -Match "My Bastion Host Security Group"} | Select-Object -ExpandProperty GroupId
$bastionhostuseridgrouppair.GroupId = $bastionhostsgid
$httpallowfromelb = New-Object Amazon.EC2.Model.IpPermission -Property @{IpProtocol=”tcp”;FromPort=80;ToPort=80;UserIdGroupPair=$elbuseridgrouppair}
$sshallowfrombastionhost = New-Object Amazon.EC2.Model.IpPermission -Property @{IpProtocol=”tcp”;FromPort=22;ToPort=22;UserIdGroupPair=$bastionhostuseridgrouppair}
$websgpermissions = New-Object System.Collections.ArrayList
$websgpermissions.Add($httpallowfromelb) | Out-Null
$websgpermissions.Add($sshallowfrombastionhost) | Out-Null
Grant-EC2SecurityGroupIngress -GroupId $websg -IpPermission $websgpermissions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.