为啥我的 Ubuntu EC2 实例的 DataUser 部分中的脚本没有运行?我正在使用 Cloudformation

Posted

技术标签:

【中文标题】为啥我的 Ubuntu EC2 实例的 DataUser 部分中的脚本没有运行?我正在使用 Cloudformation【英文标题】:Why is the script in the DataUser section of my Ubuntu EC2 instance not running? I am using Cloudformation为什么我的 Ubuntu EC2 实例的 DataUser 部分中的脚本没有运行?我正在使用 Cloudformation 【发布时间】:2017-09-14 10:48:27 【问题描述】:

我正在使用 CloudFormation 创建一个运行 Ubuntu 的 EC2 实例。我在 EC2 实例的 UserData 属性中插入了一个安装 pip 的命令和一个安装 cfn cloudformation 帮助程序脚本的命令。也就是说,关键的cloudformation模板片段是:

"UserData" : 
      "Fn::Base64" : 
        "Fn::Join": ["", [
          "#!/bin/bash -xe","\n",
          "apt-get update","\n",
          "apt-get install -y python-pip","\n",
          "apt-get install -y python3","\n",
          "apt-get install -y heat-cfntools","\n"
          ]
        ]
      
    

不,我没有元数据部分。问题:为什么脚本没有运行?这是我在新创建的 EC2 实例上得到的输出:

ubuntu@ip-10-0-0-121 :~$ curl -s http://169.254.169.254/latest/user-data

#/bin/bash -xe
apt-get update
apt-get install -y python-pip
apt-get install -y heat-cfntools

脚本从 Cloudformation 模板中 EC2 资源列表的 DataUser 部分传输到实时 EC2 实例,但如下所示,该脚本未执行:

ubuntu@ip-10-0-0-121:~$ pip

The program 'pip' is currently not installed. You can install it by typing:
sudo apt install python-pip

ubuntu@ip-10-0-0-121:~$ vi /var/log/cloud-init.log

log show nothing that stands out.

ubuntu@ip-10-0-0-121:~$ cfn-init

The program 'cfn-init' is currently not installed. You can install it by typing:  
sudo apt install heat-cfntools

注意:当我不使用 Cloudformation 而是使用 EC2 控制台时,我在 EC2 的 UserData 部分运行相同的脚本没有任何问题。

编辑:我经常使用 aws cloudformation validate-template [NameOfTemplate] 命令。但是,这个工具只能让我验证模板是否完全符合 JSON 语法。该工具不会验证其他任何内容。如果模板被破坏,运行 Cloudformation 将导致回滚。 Cloudformation 一直运行,直到报告完成。

【问题讨论】:

尝试使用aws cloudformation validate-template 验证您的模板,如下所示。 ***.com/questions/11854772/… 检查实例的系统日志,您可以从 aws 控制台本身检查,看看在执行用户数据部分时是否记录了任何内容。 分享/var/log/cloud-init-output.log的完整输出。 【参考方案1】:

有些东西正在从 shebang (#!) 中移除你的 bang (!)。

在您的输出中,您有:

ubuntu@ip-10-0-0-121 :~$ curl -s http://169.254.169.254/latest/user-data
#/bin/bash -xe
apt-get update
apt-get install -y python-pip
apt-get install -y heat-cfntools

所以 cloudformation 正在读取 "#/bin/bash" 而不是 "#!/bin/bash" 并且不知道如何执行它并且不执行任何操作。

我不知道为什么会发生这种情况以及如何解决它,但可能与您的上传过程相关的原因是删除了 !

希望它对某人有所帮助,尽管这是一个老问题。

【讨论】:

"UserData": "Fn::Base64": "Fn::Join": [ "", [ "#/bin/bash -xe", "/n", " Ref": "UserData" ] ] 我在 userdata 参数 "apt-get update","\n","apt-get install -y apache2","\n","apt- get install -y php","\n" 它也不起作用@GMartinez 如何通过userdata参数达到同样的效果

以上是关于为啥我的 Ubuntu EC2 实例的 DataUser 部分中的脚本没有运行?我正在使用 Cloudformation的主要内容,如果未能解决你的问题,请参考以下文章