Initialize.ps1 not run, Trigger "Server Started" not triggered for keyvault registration

Product: PowerShell Universal
Version: 3.7.7

Hello!
I’m trying to automatically register an azure keyvault in my PSU instance running on Azure with SQL and Git active.

The trigger:

New-PSUTrigger -Name "Register Azure KeyVault" -EventType "ServerStarted" -Environment "Integrated" -TriggerScript "Register Az.KeyVault.ps1"

When triggered manually, the script does its job successfully, and I can then create variables in the secret store. However, the trigger does not execute the script when I reboot the server. I do have a single instance, however every reboot list a new instance in the computers list on the server. Does that confuse PSU?

Similar, I have setup initialize.ps1 to register the Keyvault as well, which is not executed, as far as I can tell. I guess I’d prefer the initialize.ps1 way so the secrets are available when the other config files (authentication.ps1) are evaluated so I can store the openid client secret in the keyvault instead of plaintext in the code and in git… But I seem to do something wrong here… Unfortunately the initialize.ps1 is not really documented, it seems…

Can someone hint me in a good direction? Are more information needed? Thankful for any help here :slight_smile:

Best regards, Oliver

I had the same problem last week. I created an initialize.ps1 script with the intention to register key vault, however this would not start on boot. I am currently running the script manually when reboot my container with the intention to pick this problem up later down the line.

Thanks for your reply! Glad (and sad) to hear I’m not alone then. Hopefully we’ll find a solution here, can’t be running an automation system when we can’t even automate its startup, can we :wink:

1 Like

I have taken another look at my Initialize.ps1 script.

I have left in there my script to register keyvault and thrown in another line just to check the file actually runs

Invoke-PSUScript -environment "Integrated" -name "KeyVaultRegister.ps1"
Write-Output "Am I working?" > /root/.PowerShellUniversal/Repository/.universal/test.txt

On boot, I can see the test file is created. So, I know the script is running.

Following the boot, I run the 1st line again in another script, and it seems to kick KeyVault into action.

I suspect the problem is the KeyVault module is not loaded yet:

2023-01-25 09:19:31.490 +00:00 [ERR] Failed to read secret :The term 'Az.KeyVault\Get-AzKeyVaultSecret' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

I will continue to look into this.

I haven’t found any indication that the initialize script was run on my end, but I’ll modify it like your example and test again. I have a few lines in there manually loading the module, let me see if I can find my source again

Got it: Sharing an example of using the Initialize.ps1 to connect an Azure KeyVault

OK, I think I have it…

I had to modify my Initialize.ps1 script to load to following:

Import-Module -Name /root/.PowerShellUniversal/Repository/Modules/Az.Accounts/ -verbose | Out-Null
Import-Module -Name /root/.PowerShellUniversal/Repository/Modules/Az.KeyVault/ -verbose | Out-Null
Invoke-PSUScript -environment "Integrated" -name "KeyVaultRegister.ps1"

I had to import the modules and give them a chance to load. Following that, my keys registered.

Hmm I’m wondering, running in a linux container, if I need to capitalize my script name to Initialize.ps1 too? Let me try that in a bit

Yep, Linux will do that to you (The way it should be :slight_smile: )

I’m Running the Linux Container too on Azure Container Instances.

:person_facepalming: Well, needs some documentation :joy: Thanks for the insights!

Anytime :slight_smile:

No luck even with capitalization, no hint in the log that it ran or failed…

If it’s finding the script and trying to run it, you should see a log message. Here’s the associated code from the PSU server.

            var repoPath = configurationService.GetSetting(ConfigurationSetting.RepositoryPath);
            var initScript = Path.Combine(repoPath, ".universal", "initialize.ps1");
            if (!File.Exists(initScript)) return;

            SetLoadingInfo("Running initialization script...");

            try
            {
                using (var rs = GetRunspace())
                {
                    using (var powerShell = PowerShell.Create())
                    {
                        powerShell.AddStatement().AddScript($". '{initScript}'");
                        powerShell.Invoke();

                        if (powerShell.HadErrors)
                        {
                            foreach (var error in powerShell.Streams.Error)
                            {
                                logger.LogError(error.Exception, "Exception:");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Error running initialization script.");
            }

Hi Adam,
thanks for the codeblock, I’ll take a look at the situation again later.

Best, Oliver

Hi there
I found this article because I have problems to import modules in initilize.ps1. I want to import Az.Accounts and Az.KeyVault, that I am able to connect our Azure KeyVault to PowerShell Universal. We have PowerShell Universal installed as docker in our Azure.

I can not connect our Azure KeyVault in initilize.ps1 because of this error:
System.Management.Automation.CommandNotFoundException: The term ‘Connect-AzAccount’ is not recognized as a name of a cmdlet, function, script file, or executable program

I try to import the modules which are installed in Modules, but I get this error when I try to import:
System.IO.FileNotFoundException: The specified module ‘Modules/Az.Accounts’ was not loaded because no valid module file was found in any module directory.
2023-09-12 13:59:42.004 +00:00 [ERR] Exception:
System.IO.FileNotFoundException: The specified module ‘Modules/Az.KeyVault/4.11.0/Az.KeyVault.psd1’ was not loaded because no valid module file was found in any module directory.
2023-09-12 13:59:42.004 +00:00 [ERR] Exception:

As you see in the log: I tried with name, with folder-path and also with the whole path from the .psd1 or also the .psm1 file… everytime the same error “no valid module file was found in any module directory”

Do I have to import it differently because of the docker-installation?

Thank you for your inputs.

Best,
Mario

Addendum: initialize.ps1 runs, because I also tested if the script is creating the test.txt file in the directory “.universal” > it does.

Hi @mario_beeler ,

What docker image are you using?

The ‘modules’ images have AZ.keyvault and AZ.accounts built in so it should work ‘out the box’

the link to the modules line of images is here. when running those containers you should not need to put anything in the Initialize.ps1 file.

I also updated the documentation here: Variables - PowerShell Universal

Please let me know how you get on. once you log on for the 1st time, log in via service principal and register key vault, this should all work out the box once you reboot your container.

Hi @Matt.Harris

Thank you for your answer. We are using “ironmansoftware/universal:latest”

I try to do that. But when I activate managed Identity for my app, give them Reader-Permissions to the subscription and SecretReader-Permissions to the key vault it ends with “Application Error” when i start up the app service again.

I will figure it out why this error happens here and come back how it works.

Best,
Mario

I recommend not using universal:latest. This gives you no version control.

In your use case (at the time of writing), use 4.0.12-modules.

4.1.0 came out a few hours ago and is a big release. Give that a few days so we know everythings as it should be then start looking at the 4.1 branch.

Once you have loaded the 4.0.12-modules container, run some one time scripts to connect to azure, set your az context, reboot, make sure your connection persists by running a get-azcontext and then start registering your KeyVault’s.

Let me know if you run into any roadblocks. This integrated KeyVault modules release is a pretty new thing.

@mario_beeler - Forgot to add, if you are using azure, consider using a Managed User Identity. This should allow you to connect using Connect-AZAccount -Identity

1 Like

I will try it with the 4.0.12-modules later that day and will let you know.

The application error is gone, i just had to wait a few minutes and Universal was starting up without error. Now I don’t have an error when i connect to the Azure Key Vault, but it is not connected. I will load the older version, try it again and will let you know.