PSTerraformParser.psm1

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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
using module .\PSTerraformParser-Classes.psm1
function Get-ModuleNames {
    param(
        [parameter(Mandatory, ValueFromPipeline)]
        [string]
        $string
    )

    process {
        $output = @()
        $sendIt = $false
        foreach ($element in $string.split(".")) {
            if ($true -eq $sendIt) {
                $output += $element
            }

            $sendIt = $element -eq "module"
        }

        Write-Output ($output -join '.')
    }
}

function Read-TerraformPlan {
    param(
        # Specifies a path to one or more locations.
        [Parameter(Mandatory = $true,
            Position = 0,
            ValueFromPipeline = $true,
            ValueFromPipelineByPropertyName = $true)]
        [Alias("PSPath")]
        [ValidateNotNullOrEmpty()]
        [string]
        $Path
    )

    begin {
        $noChangesStr = 'No changes. Infrastructure is up-to-date.'
        $contentStartStr = 'Terraform will perform the following actions:'
        $contentEndStr = 'Plan:'
        $changesSeperator = ' => '
        $newResourceForced = ' (forces new resource)'

        $actionMapping = @{
            '+'   = [action]::create
            '-'   = [action]::destroy
            '-/+' = [action]::replace
            '~'   = [action]::update
            '<='  = [action]::read
        }
    }

    process {
        $Data = Get-Content $Path

        $result = [terraformplan]::new()

        # error out if no start is found
        if (($data -match "^$contentStartStr").count -eq 0) {
            $result.errors += [error]@{
                code    = "UNABLE_TO_FIND_STARTING_POSITION_WITHIN_FILE"
                message = "Did not find magic starting string: $contentStartStr"
            }
            return $result
        }

        # error out if no end is found
        if (($data -match "^$contentEndStr").count -eq 0) {
            $result.errors += [error]@{
                code    = "UNABLE_TO_FIND_ENDING_POSITION_WITHIN_FILE"
                message = "Did not find magic ending string: $contentEndStr"
            }
            return $result
        }

        # return empty result because no changes were found
        if ($data -match $noChangesStr) {
            return $result
        }

        $startDetected = $false
        $newResource = $true

        foreach ($line in $data) {
            # start processing since we've found the start
            if ($false -eq $startDetected -and $line -match "^$contentStartStr") {
                $startDetected = $true
                continue
            }

            # stop if at the end
            if ($startDetected -and $line -match "^$contentEndStr") {
                break;
            }

            if ($true -eq $startDetected) {
                # ignore blanks lines and start new resources
                if ([string]::IsNullOrWhiteSpace($line)) {
                    if ($null -ne $changedResource) {
                        if ($changedResource.action -eq [action]::read) {
                            $result.changedDataSources += $changedResource
                        } else {
                            $result.changedResources += $changedResource
                        }
                        $changedResource = $null
                    }
                    $newResource = $true
                    continue
                }

                # process new resources
                if ($true -eq $newResource) {
                    $newResource = $false
                    $changedResource = [change]::new()

                    if ($line -match '^ *(?<action>[\+\-\/~<=]+) (?<resource>\S+)(( \(((?<tainted>tainted)|(?<newresource>new resource required))\))*)?') {
                        $changedResource.action = $actionMapping[$matches.action]
                        $changedResource.path = $matches.resource

                        $resourceComponents = $matches.resource.Split(".")
                        $changedResource.name = $resourceComponents[-1]
                        $changedResource.type = $resourceComponents[-2]
                        $changedResource.tainted = (![string]::IsNullOrEmpty($matches.tainted))
                        $changedResource.newResourceRequired = (![string]::IsNullOrEmpty($matches.newresource))
                        $changedResource.module = $changedResource.path | Get-ModuleNames

                    } else {
                        $result.errors += [error]@{
                            code    = "UNABLE_TO_PARSE_CHANGE_LINE"
                            message = "Unable to parse '$line' (ignoring)"
                        }
                    }
                }

                # add properties to new resource
                if ($null -ne $changedResource -and $line -match '^ +(?<attribute>\S+): *(?<value>.+)') {
                    $attributechanges = [changedattribute]::new()

                    $old, $new = $matches.Value.split("=>").trim()

                    $attributechanges.old = [attributevalue]::new($old)

                    if ($null -ne $new) {
                        $attributechanges.new = [attributevalue]::new($new)
                    }

                    $attributechanges.forcesNewResource = $value -match ' \(forces new resource\) *$'

                    $attribute = @{$matches.attribute = $attributechanges }

                    $changedResource.changedAttributes += $attribute
                }
            }
        }

        return $result
    }
}
Export-ModuleMember -Function Read-TerraformPlan