DSCResources/Grani_HostsFile/Grani_HostsFile.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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
#region Initialize

function Initialize {
    # hosts location
    $script:hostsLocation = "$env:SystemRoot\System32\drivers\etc\hosts";
    $script:encoding = "UTF8";

    # Enum for Ensure
    Add-Type -TypeDefinition @"
        public enum EnsureType
        {
            Present,
            Absent
        }
"@
 -ErrorAction SilentlyContinue; 

    # Enum for Reference
    Add-Type -TypeDefinition @"
        public enum ReferenceType
        {
            DnsServer,
            StaticIp
        }
"@
 -ErrorAction SilentlyContinue; 
}

. Initialize;

#endregion

#region Message Definition

Data VerboseMessages {
    ConvertFrom-StringData -StringData @"
        CheckHostsEntry = Check hosts entry is exists.
        CreateHostsEntry = Create hosts entry {0} : {1}.
        HostsEntryFound = Found a hosts entry {0} : {1}.
        HostsEntryNotFound = Did not find a hosts entry {0} : {1}.
        ReferenceDnsServer = Reference is DnsServer. Trying to connect to DnsServer and get first A record. {0}
        ReferenceStaticIp = Reference is StaticIp. IPAddress will directly used. {0}
        RemoveHostsEntry = Remove hosts entry {0} : {1}.
        RemoveHostsEntryBeforeAdd = Remove duplicate hostname entry before adding host entry. This will ignore IPAddress because correct host entry will add right after remove. hostname : {0}
        RemovedEntryIP = Removed Entry for {0} : {1}.{2}.{3}.{4}
"@

}

Data DebugMessages {
    ConvertFrom-StringData -StringData @"
"@

}

Data ErrorMessages {
    ConvertFrom-StringData -StringData @"
        CouldNotResolveIpWithDnsServer = Could not resolve A revord with DnsServer. IpAddress : {0}
"@

}

#endregion

#region *-TargetResource

function Get-TargetResource {
    [OutputType([Hashtable])]
    [CmdletBinding()]
    param
    (
        [parameter(Mandatory = $true)]
        [string]$HostName,
        
        [parameter(Mandatory = $true)]
        [ValidateSet('Present', 'Absent')]
        [string]$Ensure = [EnsureType]::Present,

        [parameter(Mandatory = $true)]
        [string]$IpAddress,

        [parameter(Mandatory = $false)]
        [ValidateSet("DnsServer", "StaticIp")]
        [String]$Reference = "DnsServer"
    )  
    
    $Configuration = @{
        HostName  = $HostName
        IPAddress = $IpAddress
        Reference = $Reference
    };

    Write-Verbose $VerboseMessages.CheckHostsEntry;

    try {
        $ipEntry = ResolveIpAddressReference -IpAddress $IpAddress -HostName $HostName -Reference $Reference;
        if (TestIsHostEntryExists -IpAddress $ipEntry -HostName $HostName) {
            Write-Verbose ($VerboseMessages.HostsEntryFound -f $HostName, $ipEntry);
            $Configuration.Ensure = [EnsureType]::Present;
        }
        else {
            Write-Verbose ($VerboseMessages.HostsEntryNotFound -f $HostName, $ipEntry);
            $Configuration.Ensure = [EnsureType]::Absent;
        }
    }
    catch {
        Write-Error $_;
    }

    return $Configuration;
}

function Set-TargetResource {
    [OutputType([Void])]
    [CmdletBinding()]
    param
    (
        [parameter(Mandatory = $true)]
        [string]$HostName,
        
        [parameter(Mandatory = $true)]
        [ValidateSet('Present', 'Absent')]
        [string]$Ensure = [EnsureType]::Present,

        [parameter(Mandatory = $true)]
        [string]$IpAddress,

        [parameter(Mandatory = $false)]
        [ValidateSet("DnsServer", "StaticIp")]
        [String]$Reference = "DnsServer"
    )  

    try {
        $ipEntry = ResolveIpAddressReference -IpAddress $IpAddress -HostName $HostName -Reference $Reference
        $hostEntry = "`n{0}`t{1}" -f $ipEntry, $HostName

        # Absent
        if ($Ensure -eq [EnsureType]::Absent.ToString()) {
            Write-Verbose ($VerboseMessages.RemoveHostsEntry -f $HostName, $ipEntry);
            ((Get-Content $script:hostsLocation) -notmatch "^\s*$") -notmatch "^[^#]*$ipEntry\s+$HostName" | Set-Content -Path $script:hostsLocation -Force -Encoding $script:encoding;
            return;
        }
        else {
            # Present
            Write-Verbose ($VerboseMessages.RemoveHostsEntryBeforeAdd -f $HostName);
            ((Get-Content $script:hostsLocation) -notmatch "^\s*$") -notmatch "^[^#]*(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\s+$HostName" | Set-Content -Path $script:hostsLocation -Force -Encoding $script:encoding;

            Write-Verbose ($VerboseMessages.CreateHostsEntry -f $HostName, $ipEntry);
            Add-Content -Path $script:hostsLocation -Value $hostEntry -Force -Encoding $script:encoding;
        }
    }
    catch {
        throw $_;
    }
}

function Test-TargetResource {
    [OutputType([boolean])]
    [CmdletBinding()]
    param
    (
        [parameter(Mandatory = $true)]
        [string]$HostName,
        
        [parameter(Mandatory = $true)]
        [ValidateSet('Present', 'Absent')]
        [string]$Ensure = [EnsureType]::Present,

        [parameter(Mandatory = $true)]
        [string]$IpAddress,

        [parameter(Mandatory = $false)]
        [ValidateSet("DnsServer", "StaticIp")]
        [String]$Reference = "DnsServer"
    )  

    return (Get-TargetResource -HostName $HostName -IpAddress $IpAddress -Ensure $Ensure -Reference $Reference).Ensure -eq $Ensure;
}

#endregion

#region Helper Function

function TestIsHostEntryExists ([string]$IpAddress, [string] $HostName) {
    return ((Get-Content -Path $script:hostsLocation -Encoding $script:encoding) -match "^[^#]*$ipAddress\s+$HostName" | measure).Count -ne 0;
}

function ResolveIpAddressReference ([string]$IpAddress, [string]$HostName, [ReferenceType]$Reference) {
    $ipEntry = if ($Reference -eq [ReferenceType]::StaticIp) {
        # Reference is StaticIp
        Write-Verbose ($VerboseMessages.ReferenceStaticIp -f $IpAddress);
        $IpAddress;
    }
    elseif ($Reference -eq [ReferenceType]::DnsServer) {
        # Reference is DnsServer
        Write-Verbose ($VerboseMessages.ReferenceDnsServer -f $IpAddress);
        $resolveIp = Resolve-DnsName -Name $HostName -Server $IpAddress -DnsOnly | where Type -eq A | sort IPAddress;
        if ($null -eq $resolveIp) {
            throw New-Object System.NullReferenceException ($ErrorMessages.CouldNotResolveIpWithDnsServer -f $IpAddress);
        }
        ($resolveIp | select -First 1).IPAddress;
    }

    return $ipEntry;
}

#endregion

Export-ModuleMember -Function *-TargetResource;