繁体   English   中英

AWS Cloudformation - 使用 cfn-init 安装软件包

[英]AWS Cloudformation - Installing packages with cfn-init

我已经通过 cloudformation 创建了一个 EC2 实例,我试图让它直接通过 cloudformation 在实例上安装 postgres。 但是,当我通过 SSH 连接到我的实例并尝试通过命令行运行psql ,我不断收到:

bash: psql: command not found

我试过手动执行,使用以下命令安装 postgres,它工作正常。

sudo yum install postgresql postgresql-server postgresql-devel postgresql-contrib postgresql-docs

可能是因为我只是更新堆栈,从而更新 ec2 实例而不是创建一个新实例?

下面是来自 cloudformation 模板的片段。 当我更新模板时一切正常,但似乎仍未安装 postgres ......

  DbWrapper:
    Type: AWS::EC2::Instance
    Metadata:
      AWS::CloudFormation::Init: 
        config: 
          packages: 
            yum:
              postgresql: []
              postgresql-server: []
              postgresql-devel: []
              postgresql-contrib: []
              postgresql-docs: []
    Properties:
      ImageId: ami-f976839e #AMI aws linux 2
      InstanceType: t2.micro
      AvailabilityZone: eu-west-2a
      SecurityGroupIds:
      - !Ref Ec2SecurityGroup
      SubnetId: !Ref SubnetA
      KeyName: !Ref KeyPairName
      UserData:
        Fn::Base64:
          !Join [ "", [
            "#!/bin/bash -xe\n",
            "sudo yum update\n",
            "sudo yum install -y aws-cfn-bootstrap\n", #download aws helper scripts
            "sudo /opt/aws/bin/cfn-init -v ", #use cfn-init to install packages in cloudformation init
            !Sub "--stack ${AWS::StackName} ",
            "--resource DbWrapper ",
            "--configsets Install ",
            !Sub "--region ${AWS::Region} ",
            "\n" ] ]

如果有人遇到相同的问题,则解决方案的确是您需要删除实例并从头开始重新创建。 只是更新堆栈是行不通的。

到这里有点晚了(我发现这是在寻找另一个问题),但是您可以使用片段中的这段代码重新运行CF Launch Config:

      UserData:
        Fn::Base64:
          !Join [ "", [
            "#!/bin/bash -xe\n",
            "sudo yum update\n",
            "sudo yum install -y aws-cfn-bootstrap\n", #download aws helper scripts
            "sudo /opt/aws/bin/cfn-init -v ", #use cfn-init to install packages in cloudformation init
            !Sub "--stack ${AWS::StackName} ",
            "--resource DbWrapper ",
            "--configsets Install ",
            !Sub "--region ${AWS::Region} ",
            "\n" ] ]

/opt/aws/bin/cfn-init命令是从指定的启动配置(定义包的位置)中运行元数据配置的内容。

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-init.html

删除实例并重新创建实例的原因是,它重新运行了上面EC2部分中的UserData

这与您使用尚未定义的--configsets值调用cfn-init有关。 您需要将下面的configSets部分添加到您的元数据部分:

Metadata:
  AWS::CloudFormation::Init:
    configSets:
      Install:
        - "config"
    config: 
      packages: 
        yum:
          postgresql: []
          postgresql-server: []
          postgresql-devel: []
          postgresql-contrib: []
          postgresql-docs: []

否则从您的cfn-init原始调用中取出--configset

参考:

cfn-init

AWS::CloudFormation::Init

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM