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

时间:2018-10-04 17:35:54

标签: bash postgresql amazon-web-services amazon-ec2 amazon-cloudformation

我已经通过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" ] ]

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

在这里有点晚了(我发现这是在寻找另一个问题),但是您可以使用代码段中的这段代码重新运行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