AWS 用户数据不适用于 Windows Server 2019

问题描述

当前设置:

在 AWS 中手动启动带有节点应用程序的 Windows Server 2019 实例。 下面的命令在这个实例中运行良好

Pm2 delete myapp
Pm2 start

问题:

我们已经为上述实例创建了 AMI,并使用 cloudformation 模板启动了它。 在cloudformation模板的userdata中,我们对nodejs的config文件做了一些修改,并用上面的命令重启nodes应用。

输出

使用 cloduformation userdata 成功修改配置文件

错误

上述命令(Pm2 delete myapp 和 Pm2 start)在执行userdata时失败。下面是用户数据日志。

The errors from user scripts: pm2 : The term 'pm2' 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.
At C:\Windows\TEMP\UserScript.ps1:15 char:1
+ pm2 delete RenderWorker
+ ~~~
    + CategoryInfo          : ObjectNotFound: (pm2:String) [],CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
 
pm2 : The term 'pm2' is not recognized as the name of a cmdlet,verify that the path is correct and try again.
At C:\Windows\TEMP\UserScript.ps1:16 char:1
+ pm2 start
+ ~~~
    + CategoryInfo          : ObjectNotFound: (pm2:String) [],CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

其他发现:

Pm2 命令可用于新启动的 ec2 实例。

C:\Users\Administrator>pm2
usage: pm2 [options] <command>

pm2 -h,--help             all available commands and options
pm2 examples               display pm2 usage examples
pm2 <command> -h           help on a specific command

Access pm2 files in ~/.pm2

cloudofration 中的用户数据:

 UserData:
    Fn::Base64: !Sub |
      <powershell>
      $config = '{
      "MyENV": "${MyENV}","UR1L": "${URL1}","URL2": "${URL2}","BUCKET": "${MyBucket}","PATH": "${Mypath}"
      }'
      echo $config
      $config | Set-Content C:\Projects\myapp\settings\config.json
      cd 'C:\Projects\myapp'
      pm2 delete RenderWorker
      pm2 start
      </powershell>
      <runAsLocalSystem>true</runAsLocalSystem>
      <persist>true</persist>

解决方法

我怀疑您是否可以像这样直接运行 pm2,因为在 SYSTEM 路径下不存在 pm2 的路径。

您可能需要按如下方式包含它的完整路径才能运行命令。

例如,您的 pm2 位于 C:\etc\ 下,那么您需要包括以下内容:

C:\etc\.pm2 delete RenderWorker
C:\etc\.pm2 start

或者如果您熟悉路径,可以将其设置为环境变量。