CloudFormation如何导出变量

时间:2017-03-14 10:58:07

标签: linux amazon-web-services amazon-cloudformation amazon-linux

以下是我们模板的一部分。我们在那里导出路径变量。但是,从模板运行,这不起作用。如果我SSH到服务器并运行相同的行,它可以工作,我可以使用gradle。但只是从模板中,它以某种方式无法执行。其他chmod命令有效,因此该块明显执行。任何帮助都非常感谢。

...
        "LaunchConfiguration": {
            "Type": "AWS::AutoScaling::LaunchConfiguration",
            "Metadata": {
                "AWS::CloudFormation::Init": {
                  "config": {
                    "packages": {
                      "yum": {
                        "java-1.8.0-openjdk-devel": []
                      }
                    },
                    "sources": {
                      "/opt": "https://services.gradle.org/distributions/gradle-3.4.1-bin.zip",
                      "/home/ec2-user": "https://github.com/ABC/XYZ/archive/master.zip"
                    },
                    "files": {
                      "/tmp/gradle_config": {
                        "content": {
                          "Fn::Join": ["",
                            [
                              "#!/bin/bash -ex\n",
                              "chmod -R 755 gradle-3.4.1/\n",
                              "export PATH=$PATH:/opt/gradle-3.4.1/bin\n" //<<<< This does not work
                            ]
                          ]
                        },
                        "mode": "000500",
                        "owner": "root",
                        "group": "root"
                      },
                      "/tmp/app_config": {
                        "content": {
                          "Fn::Join": ["",
                            [
                              "#!/bin/bash -ex\n",
                              "chmod -R 777 XYZ-master/\n"
                            ]
                          ]
                        },
                        "mode": "000500",
                        "owner": "root",
                        "group": "root"
                      }
                    },
                    "commands": {
                      "01_config": {
                          "command": "/tmp/gradle_config",
                           "cwd" : "/opt"
                      },
                      "02_config": {
                          "command": "/tmp/app_config",
                           "cwd" : "/home/ec2-user"
                      }
                    }
                  }
                }
            }, ...

1 个答案:

答案 0 :(得分:1)

我找到了解决方案。所有这些行都以root用户身份执行。因此,export PATH...不适用于我的ec2-user。我处理的方法是将路径变量(全局)放入/etc/environment文件。

在我的代码段中,只需替换

"export PATH=$PATH:/opt/gradle-3.4.1/bin\n",

"echo \"PATH=$PATH:/opt/gradle-3.4.1/bin\" >> /etc/environment"",