【问题标题】:Cross-stack reference within a lambda functionlambda 函数中的跨栈引用
【发布时间】:2020-07-14 21:23:22
【问题描述】:

绕着圈子把我的头发扯下来,非常感谢任何指点。

我有一个创建 EC2 实例的 CloudFormation 堆栈。我将其 ID 输出如下:

 Outputs:
  DevBoxInstanceId:
    Description: The instance ID of the EC2 Dev_Box.
    Value: !Ref TestInstance
    Export: 
      Name: DevBoxId

现在,在控制台中,我可以看到它会根据需要输出 ID。我的问题是我无法弄清楚如何在我的第二个堆栈中引用它。我没有太多使用 Fn::ImportValues 但出于明显的原因我想使用。我的第二个堆栈创建了一个 lambda 函数,它将停止一个实例。我想在函数中引用 DevBoxId - 我在这里误解了什么吗?我尝试了以下几种变体:

LambdaFunctionStop:
 Type: AWS::Lambda::Function
 Properties: 
  Runtime: python3.7
  Timeout: 30
  Code:
    ZipFile: |
      import boto3
      region = 'eu-west-2'
      instances = ['!ImportValue DevBoxId'] 
      ec2 = boto3.client('ec2', region_name=region)

      def handler(event, context):
        ec2.stop_instances(InstanceIds=instances)
        print('stopped your instances: ' + str(instances))
  Description: Automatically stop Dev_Env instances based on specified schedule.
  Handler: index.handler 
  Role: !GetAtt 'IAMRole.Arn'

我正在寻求帮助的相关部分是:

instances = ['!ImportValue DevBoxId']

我如何正确地写这个?

【问题讨论】:

    标签: aws-lambda yaml amazon-cloudformation


    【解决方案1】:

    您的 ZipFile 组件应该是一个字符串。因此,您需要引用该字符串之外的导出值,然后替换该字符串中的值。试试下面的

    LambdaFunctionStop:
     Type: AWS::Lambda::Function
     Properties: 
      Runtime: python3.7
      Timeout: 30
      Code:
        ZipFile: 
          !Sub
            - |
              import boto3
              region = 'eu-west-2'
              instances =  '${devboxvalue}'
              ec2 = boto3.client('ec2', region_name=region)
    
              def handler(event, context):
               ec2.stop_instances(InstanceIds=instances)
               print('stopped your instances: ' + str(instances))
            - { devboxvalue : !ImportValue "DevBoxId" }
      Description: Automatically stop Dev_Env instances based on specified schedule.
      Handler: index.handler 
      Role: !GetAtt 'IAMRole.Arn'
    

    【讨论】:

      【解决方案2】:

      您可以通过以下方式将实例 id 传递给 lambda 的环境变量: 然后你可以根据你读取环境变量的方式从你的代码中访问 if

      【讨论】:

        猜你喜欢
        • 2021-10-25
        • 1970-01-01
        • 2019-03-15
        • 1970-01-01
        • 2016-11-02
        • 2018-11-11
        • 2016-10-12
        • 2017-10-20
        • 1970-01-01
        相关资源
        最近更新 更多