-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathAnsibleWinModuleGen.ps1
375 lines (278 loc) · 13.4 KB
/
AnsibleWinModuleGen.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
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
Function Invoke-AnsibleWinModuleGen {
<#
.SYNOPSIS
A Powershell function for generating Ansible modules from PowerShell DSC resources.
.DESCRIPTION
Using Invoke-AnsibleWinModuleGen you can generate Ansible modules based on the PowerShell DSC resources.
.PARAMETER DscResourceName
.PARAMETER DscModuleName
.PARAMETER TargetPath
.PARAMETER TargetModuleName
.PARAMETER HelpObject
<Why use an object not additional properties or psd1 file with data?>
.PARAMETER CopyrightData
.PARAMETER RequiredDscResourceVersion
.PARAMETER SourceDir
.EXAMPLE
Invoke-AnsibleWinModuleGen -DscResourceName "file" -TargetPath "C:\Ansiblemodules" -TargetModuleName "win_file"
Generate the Ansible win_file module based on the file DSC resource
.LINK
https://github.com/trondhindenes/AnsibleDscModuleGenerator
.NOTES
Initial Author: Trond Hindenes
Credits
- Wojciech Sciesinski, wojciech[at]sciesinski[dot]net
Version:
- 0.4.0 - 2016-09-13 - warnings generated by PSScriptAnalyzer 0.7.0 corrected, skeleton of comments based help added
LICENSE:
See LICENSE.md
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory=$true)]
$DscResourceName,
[Parameter(Mandatory=$true)]
$DscModuleName,
[Parameter(Mandatory=$true)]
$TargetPath,
[Parameter(Mandatory=$true)]
$TargetModuleName,
[Parameter(Mandatory = $false)]
$HelpObject,
[Parameter(Mandatory = $false)]
$CopyrightData,
[Parameter(Mandatory=$false)]
$RequiredDscResourceVersion,
[Parameter(Mandatory = $false)]
$SourceDir = $psscriptroot
)
#$ErrorActionPreference = "Stop"
#LowerCase for target module name
$TargetModuleName = $TargetModuleName.tolower()
#Setup a work folder
$GenGuid = [system.guid]::NewGuid().tostring()
$GenPath = Join-Path $env:temp $genguid
New-item -Path $genpath -ItemType directory | out-null
Write-Verbose "Genpath is $genpath"
$DscResource = Get-DscResource -Name $DscResourceName -Verbose:$false
$DscResourceProperties = @()
$DscResourceProperties += $DscResource.Properties
#Create target path
if (!(test-path $TargetPath -PathType Container))
{
new-item $TargetPath -force -itemtype "Directory" | out-null
}
#Strip out the dependson prop, we're not using that in Ansible
[array]$DscResourceProperties = $DscResourceProperties | Where-Object -FilterScript {$_.Name -ne "DependsOn"}
#add empty description/defaultvalue fields
$DscResourceProperties | ForEach-Object -Process {$_ | Add-Member -MemberType NoteProperty -Name Description -Value "" -force}
$DscResourceProperties | ForEach-Object -Process {$_ | Add-Member -MemberType NoteProperty -Name DefaultValue -Value "" -force}
#Setup the Ansible module (copy placeholder files to $targetPath with names $TargetModuleName.ps1/py)
Copy-item $SourceDir\PlaceHolderFiles\PowerShell1.ps1 -Destination "$GenPath\$TargetModuleName.ps1" -Force
#Add some ansible-specific properties to the resource
$CredentialObjects = @()
$AutoInstallModuleProp = "" | Select-Object -Property Name, PropertyType, IsMandatory, Values, DefaultValue, Description
$AutoInstallModuleProp.Name = "AutoInstallModule"
$AutoInstallModuleProp.PropertyType = "[bool]"
$AutoInstallModuleProp.IsMandatory = $false
$AutoInstallModuleProp.DefaultValue = "false"
$AutoInstallModuleProp.Description = "If true, the required dsc resource/module will be auto-installed using the Powershell package manager"
$AutoInstallModuleProp.Values = "true","false"
$DscResourceProperties += $AutoInstallModuleProp
$AutoSetLcmProp = "" | Select-Object -Property Name, PropertyType, IsMandatory, Values, DefaultValue, Description
$AutoSetLcmProp.Name = "AutoConfigureLcm"
$AutoSetLcmProp.PropertyType = "[bool]"
$AutoSetLcmProp.DefaultValue = "false"
$AutoSetLcmProp.IsMandatory = $false
$AutoSetLcmProp.Description = "If true, LCM will be auto-configured for directly invoking DSC resources (which is a one-time requirement for Ansible DSC modules)"
$AutoSetLcmProp.Values = "true","false"
$DscResourceProperties += $AutoSetLcmProp
Foreach ($prop in $DscResourceProperties)
{
$Mandatory = $prop.IsMandatory
$PropName = $prop.Name
$defaultvalue = $prop.defaultvalue
if (!$defaultvalue){$defaultvalue = ""}
$Description = $prop.Description
if (!$Description){$Description = ""}
Write-Verbose "Prop is $propname, mandatory: $mandatory"
#Build the content object
if (($prop.DefaultValue) -and ($null -ne $prop.DefaultValue))
{
#Prop has a default value
$PropContent = @'
#ATTRIBUTE:<PROPNAME>;MANDATORY:<MANDATORY>;DEFAULTVALUE:<DEFAULTVALUE>;DESCRIPTION:<DESCRIPTION>;CHOICES:<CHOICES>
$<PROPNAME> = Get-Attr -obj $params -name <PROPNAME> -failifempty $<MANDATORY> -resultobj $result -default <DEFAULTVALUE>
'@
}
Else
{
$PropContent = @'
#ATTRIBUTE:<PROPNAME>;MANDATORY:<MANDATORY>;DEFAULTVALUE:<DEFAULTVALUE>;DESCRIPTION:<DESCRIPTION>;CHOICES:<CHOICES>
$<PROPNAME> = Get-Attr -obj $params -name <PROPNAME> -failifempty $<MANDATORY> -resultobj $result
'@
}
if ($prop.PropertyType -eq "[PSCredential]")
{
$PropContent = @'
#ATTRIBUTE:<PROPNAME>_username;MANDATORY:<MANDATORY>;DEFAULTVALUE:<DEFAULTVALUE>;DESCRIPTION:<DESCRIPTION>;CHOICES:<CHOICES>
$<PROPNAME>_username = Get-Attr -obj $params -name <PROPNAME>_username -failifempty $<MANDATORY> -resultobj $result
#ATTRIBUTE:<PROPNAME>_password;MANDATORY:<MANDATORY>;DEFAULTVALUE:<DEFAULTVALUE>;DESCRIPTION:<DESCRIPTION>;CHOICES:<CHOICES>
$<PROPNAME>_password = Get-Attr -obj $params -name <PROPNAME>_password -failifempty $<MANDATORY> -resultobj $result
'@
#Store the credential objects, as we need to parse them into a proper cred object before invoking the dsc resource
$CredentialObjects += $PropName
Write-Verbose "Prop $propname is a credential type"
}
Else
{
}
$PropContent =$PropContent.Replace("<PROPNAME>", $PropName)
$PropContent =$PropContent.Replace("<MANDATORY>", $Mandatory.ToString())
$PropContent =$PropContent.Replace("<DEFAULTVALUE>", "$defaultvalue")
$PropContent =$PropContent.Replace("<DESCRIPTION>", "$Description")
if ($prop.values -gt 0)
{
$PropContent =$PropContent.Replace("<CHOICES>", $prop.Values -join ",")
}
Else
{
$PropContent =$PropContent.Replace("<CHOICES>","")
}
add-content -Path "$GenPath\$TargetModuleName.ps1" -Value $PropContent
}
#For properties that have valid values, ensure that the supplied params are valid:
$PropsWithValues = $DscResourceProperties | Where-Object -FilterScript {($_.Values.count) -gt 0}
foreach ($Prop in $PropsWithValues)
{
$PropName = $prop.Name
$Values = $prop.Values
Add-Content -path "$GenPath\$TargetModuleName.ps1" -Value @'
If ($<PROPNAME>)
{
If ((<VALIDVALUES>) -contains $<PROPNAME> ) {
}
Else
{
Fail-Json $result "Option <PropName> has invalid value $<PROPNAME>. Valid values are <VALIDVALUES>"
}
}
'@
$PropContent =$PropContent.Replace("<DESCRIPTION>", "$Description")
$ValuesString = ""
Foreach ($value in $values)
{
$ValuesString += "'" + $value + "'"
$ValuesString += ","
}
$ValuesString = $ValuesString.trim(",")
(Get-content -Path "$GenPath\$TargetModuleName.ps1" -Raw) -replace "<VALIDVALUES>", $ValuesString | Set-Content -Path "$GenPath\$TargetModuleName.ps1"
(Get-content -Path "$GenPath\$TargetModuleName.ps1" -Raw) -replace "<PROPNAME>", $PropName | Set-Content -Path "$GenPath\$TargetModuleName.ps1"
}
#Take care of the Credential things
Foreach ($credobject in $CredentialObjects)
{
#Take the _username and _password strings and mash them togheter in a happy PsCredentialObject
Add-Content -path "$GenPath\$TargetModuleName.ps1" -Value @'
if ($<CREDNAME>_username)
{
$<CREDNAME>_securepassword = $<CREDNAME>_password | ConvertTo-SecureString -asPlainText -Force
$<CREDNAME> = New-Object System.Management.Automation.PSCredential($<CREDNAME>_username,$<CREDNAME>_securepassword)
}
'@
(Get-content -Path "$GenPath\$TargetModuleName.ps1" -Raw) -replace "<CREDNAME>", $credobject | Set-Content -Path "$GenPath\$TargetModuleName.ps1"
}
#At this point we need the dsc resource to exist on the target node
Add-Content -path "$GenPath\$TargetModuleName.ps1" -Value '$DscResourceName = "<DscResourceName>"'
(Get-content -Path "$GenPath\$TargetModuleName.ps1" -Raw) -replace "<DscResourceName>", $DscResourceName | Set-Content -Path "$GenPath\$TargetModuleName.ps1"
if ($RequiredDscResourceVersion)
{
Add-Content -path "$GenPath\$TargetModuleName.ps1" -Value '$RequiredDscResourceVersion = "<RequiredDscResourceVersion>"'
(Get-content -Path "$GenPath\$TargetModuleName.ps1" -Raw) -replace "<RequiredDscResourceVersion>", $RequiredDscResourceVersion | Set-Content -Path "$GenPath\$TargetModuleName.ps1"
}
if ($DscModuleName)
{
Add-Content -path "$GenPath\$TargetModuleName.ps1" -Value '$DscModuleName = "<dscmodulename>"'
(Get-content -Path "$GenPath\$TargetModuleName.ps1" -Raw) -replace "<dscmodulename>", $DscModuleName | Set-Content -Path "$GenPath\$TargetModuleName.ps1"
}
#Copy in the powershell2_dscresourceverify.ps1 into the file
Get-content "$SourceDir\PlaceHolderFiles\powershell2_dscresourceverify.ps1" -Raw | Add-Content "$GenPath\$TargetModuleName.ps1"
Get-content "$SourceDir\PlaceHolderFiles\powershell3_dscparser.ps1" -Raw | Add-Content "$GenPath\$TargetModuleName.ps1"
#Docs file
$DocsFilePath = "$GenPath\$TargetModuleName.py"
Copy-item $SourceDir\PlaceHolderFiles\python1.py -Destination $DocsFilePath -Force
#Populate docs file
$DocsFileAttributeMatches = @()
$DocsFileAttributeMatches += get-content "$GenPath\$TargetModuleName.ps1" | Select-String "#ATTRIBUTE"
$DocsFileAttributes = @()
Foreach ($match in $DocsFileAttributeMatches)
{
$DocsFileAttributes += $match.ToString()
}
$MetaString = @'
module: <TARGETMODULENAME>
version_added: <ANSIBLEVERSIONADDED>
short_description: <SHORTDESCRIPTION>
description:
- <LONGDESCRIPTION>
options:
'@
$MetaString = $MetaString.Replace("<TARGETMODULENAME>", $TargetModuleName)
$MetaString = $MetaString.Replace("<ANSIBLEVERSIONADDED>", $helpobject.AnsibleVersion)
$MetaString = $MetaString.Replace("<SHORTDESCRIPTION>", $helpobject.Shortdescription)
$MetaString = $MetaString.Replace("<LONGDESCRIPTION>", $helpobject.LongDescription)
Add-Content -Path $DocsFilePath -Value $MetaString
Foreach ($docsattribute in $DocsFileAttributes)
{
Write-verbose "Processing $docsattribute"
$docsattributeobj = $docsattribute.split(";")
$OptionName = $docsattributeobj[0]
$OptionName = $OptionName.Replace("#ATTRIBUTE:","")
$IsMandatory = $docsattributeobj[1]
$IsMandatory = $IsMandatory.Replace("MANDATORY:","")
$DefaultValue = $docsattributeobj[2]
$DefaultValue = $DefaultValue.Replace("DEFAULTVALUE:","")
$Description = $docsattributeobj[3]
$description = $Description.replace("DESCRIPTION:","")
$choices = $docsattributeobj[4]
$choices = $choices.replace("CHOICES:","")
$OptionAttribute = @'
<OPTIONNAME>:
description:
- <DESCRIPTION>
required: <MANDATORY>
default: <DEFAULTVALUE>
aliases: []
'@
$OptionAttribute = $OptionAttribute.Replace("<OPTIONNAME>", $OptionName)
$OptionAttribute = $OptionAttribute.Replace("<MANDATORY>", $IsMandatory)
$OptionAttribute = $OptionAttribute.Replace("<DEFAULTVALUE>", $DefaultValue)
$OptionAttribute = $OptionAttribute.Replace("<DESCRIPTION>", $Description)
if ($choices -ne "")
{
#Add the choices thingy to the help file
$optionAttribute += " choices:" + "`r"
$choicearray = $choices.split(",")
#The counter variable should be probably removed in the next version
#$counter = 1
foreach ($choice in $choicearray)
{
$OptionAttribute += " - $choice" + "`r"
}
}
Else
{
#$OptionAttribute = $OptionAttribute.replace(" choices:","")
}
Add-Content -Path $DocsFilePath -Value $OptionAttribute
}
#Copy to target
Write-Verbose "copying generated files to $targetpath"
get-childitem $GenPath | copy-item -Destination $TargetPath
#Cleanup GenPath
Write-Verbose "Cleaning up $genpath"
Remove-item $genpath -recurse -force
Write-Verbose "finished"
#Remove module from scope
Remove-Module -name $DscModuleName -Force -ErrorAction SilentlyContinue
}