【问题标题】:Load credential from IAM role EC2 Instance instead of env in nodejs从 IAM 角色 EC2 实例而不是 nodejs 中的 env 加载凭证
【发布时间】:2021-05-28 13:48:41
【问题描述】:

我目前正在从 env 获取凭据以获取存储桶的凭据。我目前使用的代码是:

import  AWS  from "aws-sdk";

export const S3Bucket = (req, res) => {
  const BUCKET_NAME = process.env.BUCKET_NAME;
  const IAM_USER_KEY = process.env.IAM_USER_KEY;
  const IAM_USER_SECRET = process.env.IAM_USER_SECRET;
  try {
    
  
  let s3bucket = new AWS.S3({
    accessKeyId: IAM_USER_KEY,
    secretAccessKey: IAM_USER_SECRET,
    Bucket: BUCKET_NAME
  });
  s3bucket.createBucket(() => {
      const params = {
        Bucket: BUCKET_NAME,
        Key: `path/${fileName}`,
        Body: JSON.stringify(data)
      };
      s3bucket.upload(params, (err, data) => {

        if(!data) res.status(500).json(data);
        else
        res.status(200).json(data);
      });
  });
 } catch (error) {
    res.status(500).json(error);
  }
};

我正在寻找应从 IAM 角色加载凭据的替代代码。我试过阅读文档,但没有得到太多见解。

【问题讨论】:

    标签: node.js amazon-web-services amazon-s3 aws-sdk amazon-iam


    【解决方案1】:

    您只需要担任该角色并使用那里的凭据,前提是您有权担任上述角色。如下所示:

    sts_assumerole.js

    const AWS = require('aws-sdk');
    // Set the region 
    AWS.config.update({region: 'REGION'});
    
    var roleToAssume = {RoleArn: 'arn:aws:iam::123456789012:role/RoleName',
                        RoleSessionName: 'session1',
                        DurationSeconds: 900,};
    var roleCreds;
    
    // Create the STS service object    
    var sts = new AWS.STS({apiVersion: '2011-06-15'});
    
    //Assume Role
    sts.assumeRole(roleToAssume, function(err, data) {
        if (err) console.log(err, err.stack);
        else{
            roleCreds = {accessKeyId: data.Credentials.AccessKeyId,
                         secretAccessKey: data.Credentials.SecretAccessKey,
                         sessionToken: data.Credentials.SessionToken};
            stsGetCallerIdentity(roleCreds);
        }
    });
    
    //Get Arn of current identity
    function stsGetCallerIdentity(creds) {
        var stsParams = {credentials: creds };
        // Create STS service object
        var sts = new AWS.STS(stsParams);
            
        sts.getCallerIdentity({}, function(err, data) {
            if (err) {
                console.log(err, err.stack);
            }
            else {
                console.log(data.Arn);
            }
        });    
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-07
      • 2018-07-15
      • 2019-08-23
      • 2020-02-01
      • 2018-02-07
      • 1970-01-01
      • 2018-07-09
      • 2020-09-02
      • 2016-11-21
      相关资源
      最近更新 更多