In one of my older posts I discussed already how to create a custom Python modules for Ansible which you can read HERE. For PowerShell we can do the same, which is not that hard also. Creating modules is the preferred way when you want to reuse your script for multiple tasks in multiple playbooks or workflows. Another good reason is that your playbooks stay clean and you don’t have to parse output or scripts.
In this example I will create a Veeam Quickbackup PowerShell Ansible module.
A valid PowerShell Ansible module have 2 files:
Python: Veeam_quickbackup.py <- This file is for documenting the module with examples
PowerShell: Veeam_quickbackup.ps1 <- This file contains the actual functions.
Lets start with the PowerShell file, I will highlight the important things which you need.
- Parameters: As you can see I use only one parameter in this example. But you can use as much parameters as you like. In different types for example: list, bool, str etc
- Module object: Creating a PowerShell module object for storing all the values and outcomes from the script.
- Fail-Json: If there is any executing exception you can pass this back to Ansible. The command supports returning of the failing object and a message.
- Messages and results: Another way to interact with the Ansible PowerShell engine is to give the $module object values. As you may know from other playbooks there is a “Changed” state. Changing this in a PowerShell playbook can be done by setting the $module.Result.changed = $true . With the same $module object you can specify the result messages. $module.Result.msg = “Succesfully created the quickbackups”
- Exit the module: $module.ExitJson()
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 |
#!powershell #Requires -Module Ansible.ModuleUtils.Legacy #AnsibleRequires -OSVersion 6.2 #AnsibleRequires -CSharpUtil Ansible.Basic $spec = @{ options = @{ vmhostname = @{ type = "list" } } } $module = [Ansible.Basic.AnsibleModule]::Create($args, $spec) $ErrorActionPreference = "Stop" Set-StrictMode -Version 2.0 # Functions Function Connect-VeeamServer { try { Add-PSSnapin -PassThru VeeamPSSnapIn -ErrorAction Stop | Out-Null } catch { Fail-Json -obj @{} -message "Failed to load Veeam SnapIn on the target: $($_.Exception.Message)" } try { Connect-VBRServer -Server localhost } catch { Fail-Json -obj @{} -message "Failed to connect VBR Server on the target: $($_.Exception.Message)" } } Function Disconnect-VeeamServer { try { Disconnect-VBRServer } catch { Fail-Json -obj @{} -message "Failed to disconnect VBR Server on the target: $($_.Exception.Message)" } } # Connect Connect-VeeamServer #Quickbackup logic $result = New-Object PSObject; Set-Attr $result "changed" $false; $VMEnts = $module.Params.vmhostname $viEntis = @() Foreach($VMEnt in $VMEnts){ #Find VMWare entity $a = $null $a = Find-VBRViEntity -name $VMEnt if(!$a){ Fail-Json -obj @{} -message "Could not find $VMEnt" } Else { $viEntis += $a #Find JObobject $JobObject = get-vbrjob | Get-VBRJobObject -Name $VMEnt if(!$JobObject){ Fail-Json -obj @{} -message "$VMEnt NOT in a backupjob, cant make quickbackup" } } } $result = Start-VBRQuickBackup -vm $viEntis -wait -ErrorAction Continue if (!$Result) { Fail-Json -obj @{} -message "NO Quickbackup has been created.." } Elseif ($Result.Result -eq "Succes" -or $result.Result -eq "Warning") { $module.Result.msg = "Succesfully created the quickbackups" $module.Result.changed = $true } Elseif ($Result.Result -eq "Failed") { Fail-Json -obj @{} -message "Quick Backup Failed. See Veeam B&R Console for more details!" } Else {} # Disconnect Disconnect-VeeamServer # Return result $module.ExitJson() |
About the Python file I’ve not much to say. Just follow the Ansible guidelines for documenting custom modules. A important chapter is the example.
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 |
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2020, Rob Verhees # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: veeam_quickbackup version_added: '1.0' short_description: Create Quickbackup Veeam Ansible Powershell description: - With the module you can create quickbackup in Ansible. requirements: - Veeam Backup & Replication 9.5 Update 4a notes: - posted on robvit.com author: - Rob Verhees ''' EXAMPLES = r''' - name: VeeamQuickBackup hosts: all gather_facts: no vars: vmhostname: "{{ vmhostname }}" tasks: - name: Start Quikbackup veeam_quickbackup: vmhostname: "{{ vmhostname }}" register: result - debug: var: result ''' RETURN = r''' ---- ''' |
Hello.
Regarding your tutorial, at least in my computer, both file names need to be lowercase to match the name of the ansible module. Otherwise, I get a “couldn’t resolve module” error.
This means that they should be named:
veeam_quickbackup.py
veeam_quickbackup.ps1