Create a gist now

Instantly share code, notes, and snippets.

Globally Set AWS ELB SSL Policy
# AWS Global ELB SSL Policy
# Brian Dwyer - Intelligent Digital Services - 4/5/15
# Variables
$PolicyName="SSL-POLICY--$(Get-Date -Format yy-MM-ddTHHmmss)"
$ELBReferencePolicy='ELBSecurityPolicy-2015-03'
# Dependencies
Import-Module AWSPowerShell
Write-Host 'Finding AWS Regions containing ELBs...'
$RegionsWithELBs = @{}
ForEach ( $region in (Get-EC2Region).RegionName )
{
$ELB_Count = (Get-ELBLoadBalancer -Region $region).count
if ( $ELB_Count -ge 1 )
{
$RegionsWithELBs.Add($region, $ELB_Count)
}
}
# Display ELB Regions & Count
$tformat = @{Expression={$_.Name};Label="Region"}, @{Expression={$_.Value};Label="ELB Count"}
$RegionsWithELBs.GetEnumerator() | Sort-Object Value -Descending | Format-Table $tformat -AutoSize
ForEach ( $region in $RegionsWithELBs.Keys )
{
# Verify reference policy existence in region
if ( (Get-ELBLoadBalancerPolicy -Region $region).PolicyName -contains $ELBReferencePolicy )
{
Write-Host "`nModifying ELBs in region: '$region' `n"
# Loop through the ELBs
ForEach ( $lb in (Get-ELBLoadBalancer -Region $region ).LoadBalancerName )
{
# Verify ELB serves HTTPS
if ( (Get-ELBLoadBalancer -Region $region -LoadBalancerName $lb).ListenerDescriptions.Listener.Protocol -contains 'HTTPS' )
{
# Find Existing Policies (App/Cookie Stickiness, etc.)
$PoliciesToApply = @($PolicyName)
ForEach ( $currentpolicy in ((Get-ELBLoadBalancer -Region $region -LoadBalancerName $lb).ListenerDescriptions | Where-Object { $_.Listener.Protocol -contains 'HTTPS'}).PolicyNames )
{
if ( (Get-ELBLoadBalancerPolicy -Region $region -LoadBalancerName $lb -PolicyName $currentpolicy).PolicyTypeName -ne 'SSLNegotiationPolicyType' )
{
$PoliciesToApply += @($currentpolicy)
}
}
# Configure SSL Policy
Write-Host "`nCreating '$PolicyName' from '$ELBReferencePolicy' for $lb"
New-ELBLoadBalancerPolicy -Region $region -LoadBalancerName $lb -PolicyName $PolicyName `
-PolicyTypeName SSLNegotiationPolicyType `
-PolicyAttribute @{ AttributeName="Reference-Security-Policy";AttributeValue="$ELBReferencePolicy"} `
-Force
Write-Host "Activating policy '$PolicyName' for ELB: $lb"
Set-ELBLoadBalancerPolicyOfListener -Region "$region" -LoadBalancerName "$lb" -LoadBalancerPort 443 -PolicyName $PoliciesToApply
# Cleanup Old Policies
ForEach ($policy in (Get-ELBLoadBalancerPolicy -Region "$region" -LoadBalancerName "$lb" | Where-Object {$_.PolicyTypeName -eq 'SSLNegotiationPolicyType'}).PolicyName)
{
if ( $policy -ne $PolicyName -and $policy -ne $ELBReferencePolicy )
{
Write-Host "Removing old policy '$policy' from ELB: $lb"
Remove-ELBLoadBalancerPolicy -Region "$region" -LoadBalancerName "$lb" -PolicyName $policy -Force
}
}
}
}
}
Else
{
Write-Host "Region $region does not contain policy $ELBReferencePolicy"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment