Including Powershell module_utils

Hello,

I am trying to move some shared client stuff to a module_util so I can reuse it in my Powershell scripts. I used Windows module development walkthrough — Ansible Community Documentation for documentation.

Situation:

  • Local repo (not a collection)
  • Folders plugins/module_utils and plugins/modules

In the module_utils directory I have a file client.psm1 with 1 class, 1 function and an Export-ModuleMember for this function.

In the modules directory I have a file Get-ClientStuff.ps1 with a line #AnsibleRequires -PowerShell ..module_utils.client.

When I run the playbook that calls Get-ClientStuff I get the error Could not find collection imported module support code for '..module_utils.client".

I tried searching for this error but couldn’t find anything wrong.

Is this because I can’t use classes in module_utils, or am I doing something else wrong?

Joost

  • Local repo (not a collection)

The plugins/ structure is designed for collections and not the role directory structure. The name of module utils in a role directory should be Ansible.ModuleUtils.Name.ps1 and it would be referenced with #AnsibleRequires -PowerShell Ansible.ModuleUtils.Name. I highly recommend using a collection though as that is what most of the documentation is geared towards.

I solved the AnsibleRequires error with the following steps:

  • Add ./plugins/module_utils to module_utils in ansible.cfg.
  • Change the AnsibleRequires line to #AnsibleRequires -PowerShell ansible.module_utils.myapplication

Next problem: The exported command is not found:

The term 'Connect-MyApplication' is not recognized as the name of a cmdlet,
  function, script file, or operable program. Check the spelling of the name, or
  if a path was included, verify that the path is correct and try again.

The contents of myapplication.psm1:

class MyApplication {
 /* Class Definition */
}

function Connect-MyApplication {
  param(
    [parameter(Mandatory = $false)]$apihost = 'api.myapplication.com',
    [parameter(Mandatory = $true)]$apiuser,
    [parameter(Mandatory = $true)]$apikey
  )
  return [MyApplication]::New($apihost, $apiuser, $apikey)
}

Export-ModuleMember -Function Connect-MyApplication