Private/EC2/Get-SecurityGroupWithStack.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
function Get-SecurityGroupWithStack
{
    <#
        .SYNOPSIS
            Return security group ID with the name of the stack that created the group
            Helps us to spot default SGs created by EB
    #>

    [CmdletBinding()]
    param
    (
        [Parameter(ValueFromPipelineByPropertyName)]
        [string[]]$GroupId
    )

    begin
    {}

    process
    {
        $GroupId |
        ForEach-Object {
            $sg = Get-EC2SecurityGroup -GroupId $_

            if ($null -ne $sg)
            {
                # Determine how it was created from tags
                $stackName = $sg.Tags |
                Where-Object {
                    $_.Key -ieq 'aws:cloudformation:stack-name'
                } |
                Select-Object -ExpandProperty Value

                if (-not $stackName)
                {
                    $stackName = '*NONE*'
                }

                New-Object PSObject -Property @{
                    SecurityGroupId = $_
                    OwningStack     = $stackName
                } |
                Add-Member -PassThru -MemberType ScriptMethod -Name ToString -Force -Value {
                    "$($this.SecurityGroupId) ($($this.OwningStack))"
                }
            }
        }
    }

    end
    {}
}