如何在.NET AWS SDK中扮演角色

时间:2020-05-21 16:24:59

标签: .net amazon-web-services amazon-dynamodb aws-sdk

我正在尝试构建一个.net核心mvc应用程序,该应用程序允许用户将数据发送到dynamodb,但我似乎无法承担描述表的权限。每次尝试时都会出现以下错误:

Unable to get IAM security credentials from EC2 Instance Metadata Service

首先我有我的控制器(索引是提交用户表单的位置)

public class RfiController : Controller
{
    private readonly IDynamoDBClient capture;
    public RfiController(IDynamoDBClient dynamodb)
    {
        capture = dynamodb;
    }
    . . .
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Index(ViewModel Model)
    {
            . . .
            ///ASSUME THE role
            ConfigProvider config = new ConfigProvider();
            config.AWSRoleName = "rolename";
            config.AWSRegion = "region";
            config.Environment = "dev";
            capture.DynamoDBClientService(config);
            return View(Model);
        }
    }
}

这将调用我创建的库来处理我的dynamodb连接和东西。这是课程:

public class DynamoDBClient: IDynamoDBClient
{
    private readonly IAmazonDynamoDB _client;
    public DynamoDBClient(IAmazonDynamoDB dynamoDBClient)
    {
         _client = dynamoDBClient;
    }

    public void DynamoDBClientService(ConfigProvider config)
    {
        try
        {
            DescribeTableRequest request = new DescribeTableRequest
            {
                TableName = "tablename"
            };
            var result = _client.DescribeTableAsync(request);

            var status = result.Result.Table.TableStatus;
        }
        catch (Exception ex) //I catch and error `Unable to get IAM security credentials from EC2 Instance Metadata Service` here
        {
            throw ex;
        }
    }

    static AssumeRoleResponse GetAssumeRoleResponseAsync(AmazonSecurityTokenServiceClient client, AssumeRoleRequest request)
    {
        AssumeRoleResponse response;
        try
        {
            response = client.AssumeRoleAsync(request).Result;

        }
        catch (Exception ex)
        {
            throw ex;
        }
        return response;
    }
}

我当然在凭证文件中使用我的AWS帐户。当我尝试运行该应用程序时,在指定的位置出现错误。我怎么做错了?我即将对aws sdk感到陌生,所以请原谅我的答案。

1 个答案:

答案 0 :(得分:1)

最好创建一个IAM角色并将其附加到运行.Net代码的实例上。

IAM角色:https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html

此外,请确保您可以从实例中访问元数据网址: http://169.254.169.254/latest/meta-data/

https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-retrieval.html