【问题标题】:How to get AWS account id as custom variable in serverless framework?如何在无服务器框架中获取 AWS 账户 ID 作为自定义变量?
【发布时间】:2020-02-07 05:10:11
【问题描述】:

在无服务器框架中,我想将部署桶设置为

<project_name>-<stage>-<account_id>

我可以使用自定义变量获取舞台,例如:

custom:
    stage: ${opt:stage, self:provider.stage}

但我怎样才能获得 aws 帐户 ID?我已经尝试使用 serverless-pseudo-parameters,如下所示,但没有成功。

custom:
    account_id: #{AWS::AccountId}
plugins:
  - serverless-pseudo-parameters

有人可以帮我将帐户 ID 设置为自定义变量吗?

【问题讨论】:

    标签: amazon-web-services serverless-framework


    【解决方案1】:

    根据documentation,获取Account Id,可以使用外部js文件:

    // myCustomFile.js
    module.exports.getAccountId = async (context) => {
        return context.providers.aws.getAccountId();
    };
    

    .

    # serverless.yml
    service: new-service
    provider: aws
    custom:
      accountId: ${file(../myCustomFile.js):getAccountId}
    

    【讨论】:

    • 有效,我必须设置我想用来获取帐户的个人资料,但有效...
    【解决方案2】:

    对于使用无服务器且具有“假定角色”的任何人,其中您的 IAM 用户在主 AWS 账户中定义,并且您尝试使用该子账户中的角色在子账户中进行部署:文档化解决方案 - 上面接受的答案中的那个 - 不起作用

    此设置在此处详细描述:https://theithollow.com/2018/04/30/manage-multiple-aws-accounts-with-role-switching/。在将无服务器与 --aws-profile 配置为代入另一个账户中定义的角色一起使用时,sts.getCallerIdentity() 从默认配置文件中返回您的主账户的账户信息,而不是代入角色的账户。

    为了获取假定角色的帐户 ID(我们正在部署的位置),我执行了以下操作:

    const { STS } = require('aws-sdk');
    
    module.exports.getAccountId = async (context) => {
      // This loads the AWS credentials Serverless is currently using
      // They contain the role ARN of the assumed role
      const credentials = context.providers.aws.getCredentials();
    
      // init STS using the same credentials
      const sts = new STS(credentials);
      const identity = await sts.getCallerIdentity().promise();
      return identity.Account;
    };
    

    编辑:

    找到了一种更好的方法,它比无服务器文档中介绍的方法更简单,并且也适用于假定的角色:

    module.exports.getAccountId = async (context) => {
      return context.providers.aws.getAccountId();
    };
    

    【讨论】:

    • 谢谢@Dan C.,我会试试你的
    【解决方案3】:

    您应该能够按照以下示例在下面访问它们https://serverless.com/framework/docs/providers/aws/guide/variables/

    Resources:
    
    
    - 'Fn::Join':
          - ':'
          - - 'arn:aws:logs'
            - Ref: 'AWS::Region'
            - Ref: 'AWS::AccountId'
            - 'log-group:/aws/lambda/*:*:*'
    

    【讨论】:

    • 我在文档中找到了这个,但我想在自定义变量中包含帐户 ID,您的答案显示了如何在资源中获取帐户 ID,即使用 cloudformation
    【解决方案4】:

    您的语法似乎是错误的。试试

    custom:
        account_id: ${AWS::AccountId}
    

    因为至少在您提供的示例中,您使用的是#{AWS::AccountId}

    注意到你的标签吗?

    【讨论】:

    • 不幸的是${AWS::AccounId} 仅适用于资源部分,不适用于自定义。我的 # 语法是 serverless-pseudo-parameters 插件中使用的语法。
    猜你喜欢
    • 2019-05-01
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 2019-10-07
    • 2021-02-01
    • 2014-02-03
    • 1970-01-01
    • 2018-12-28
    相关资源
    最近更新 更多