Visual Studio AWSSDK.Athena C#您未被授权错误-如何在代码中切换角色

yeotifhr  于 2023-06-24  发布在  C#
关注(0)|答案(2)|浏览(187)

我正在使用AWSSDK. Athena从VS 2022 C#连接到https://davidpallmann.hashnode.dev/hello-athena
在C#代码var result = await _client.StartQueryExecutionAsync(queryRequest)中,我得到以下错误。

"You are not authorized to perform: athena:StartQueryExecution on the resource. After your AWS administrator or you have updated your permissions, please try again."

当我在AWS Athena上查询时,我需要将角色切换为“myRole”,并且还需要将工作组从主工作组切换到另一个工作组,例如“mycompany-workgroup”,然后我才能成功运行查询。如果我不将工作组切换到“mycompany-workgroup”,我会收到类似的错误

"You are not authorized to perform: athena:GetWorkGroup on the resource. After your AWS administrator or you have updated your permissions, please try again."

如何在C#代码中将Role切换为“myRole”?

_client = new AmazonAthenaClient(Amazon.RegionEndpoint.USEast1);

    var queryRequest = new StartQueryExecutionRequest
    {
        QueryString = "SELECT * from myDB.myTable",

        QueryExecutionContext = new QueryExecutionContext()
        {
            Database = "myDB"
        },
        WorkGroup = "myWorkgroup"
    };

谢谢你

bis0qfac

bis0qfac1#

我得到了一个使用.NET服务客户端(V3)的Athena查询。在这里查看输出:

下面是可以工作的.NET代码。请确保您指定您的桶名称等,以获得此程序成功地工作。注意,您可以在StartQueryExecutionRequest对象上指定工作组。有关详细信息,请参阅How workgroups work

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Amazon;
using Amazon.Athena;
using Amazon.Athena.Model;
using Amazon.Runtime;

namespace AthenaDotNet
{
    class StartQueryExample
    {
        //  Demonstrates how to query a table with a comma-separated value (CSV) table.
        //  For information, see https://docs.aws.amazon.com/athena/latest/ug/work-with-data.html
        public static int CLIENT_EXECUTION_TIMEOUT = 100000;
        public static string ATHENA_OUTPUT_BUCKET = "s3://<MYBUCKET>"; // change the Amazon S3 bucket name to match your environment
        public static string ATHENA_SAMPLE_QUERY = "SELECT * FROM <BUCKET>;"; // change the Query statement to match your environment
        public static long SLEEP_AMOUNT_IN_MS = 1000;
        public static string ATHENA_DEFAULT_DATABASE = "mydatabase"; // change the database to match your database
        static async Task Main(string[] args)
        {
            // Set up the credentials using Environment Variables
            var credentials = new EnvironmentVariablesAWSCredentials();
            var athenaClient = new AmazonAthenaClient(credentials,RegionEndpoint.USWest2);

            string queryExecutionId = await SubmitAthenaQuery(athenaClient);
            await WaitForQueryToComplete(athenaClient, queryExecutionId);
            await ProcessResultRows(athenaClient, queryExecutionId);
        }

        // Submits a sample query to Amazon Athena and returns the execution ID of the query.
        static async Task<string> SubmitAthenaQuery(AmazonAthenaClient athenaClient)
        {
            try
            {
                // The QueryExecutionContext allows us to set the database.
                var queryExecutionContext = new QueryExecutionContext
                {
                    Database = ATHENA_DEFAULT_DATABASE
                };

                // The result configuration specifies where the results of the query should go.
                var resultConfiguration = new ResultConfiguration
                {
                    OutputLocation = ATHENA_OUTPUT_BUCKET
                };

                var startQueryExecutionRequest = new StartQueryExecutionRequest
            {
                QueryString = ATHENA_SAMPLE_QUERY,
                QueryExecutionContext = queryExecutionContext,
                ResultConfiguration = resultConfiguration,
                WorkGroup = "MyGroup"
            };

                var startQueryExecutionResponse = await athenaClient.StartQueryExecutionAsync(startQueryExecutionRequest);
                return startQueryExecutionResponse.QueryExecutionId;
            }
            catch (AmazonAthenaException e)
            {
                Console.WriteLine("Error submitting query: " + e.Message);
                throw;
            }
        }

        // Wait for an Amazon Athena query to complete, fail, or be canceled.
        static async Task WaitForQueryToComplete(AmazonAthenaClient athenaClient, string queryExecutionId)
        {
            var getQueryExecutionRequest = new GetQueryExecutionRequest
            {
                QueryExecutionId = queryExecutionId
            };

            bool isQueryStillRunning = true;
            while (isQueryStillRunning)
            {
                var getQueryExecutionResponse = await athenaClient.GetQueryExecutionAsync(getQueryExecutionRequest);
                var queryState = getQueryExecutionResponse.QueryExecution.Status.State;

                if (queryState == QueryExecutionState.FAILED)
                {
                    throw new Exception("The Amazon Athena query failed to run with error message: " + getQueryExecutionResponse.QueryExecution.Status.StateChangeReason);
                }
                else if (queryState == QueryExecutionState.CANCELLED)
                {
                    throw new Exception("The Amazon Athena query was cancelled.");
                }
                else if (queryState == QueryExecutionState.SUCCEEDED)
                {
                    isQueryStillRunning = false;
                }
                else
                {
                    // Sleep an amount of time before retrying again.
                    await Task.Delay(CLIENT_EXECUTION_TIMEOUT);
                }

                Console.WriteLine("The current status is: " + queryState);
            }
        }

        // This code retrieves the results of a query.
        static async Task ProcessResultRows(AmazonAthenaClient athenaClient, string queryExecutionId)
        {
            try
            {
                // Max Results can be set but if it's not set,
                // it will choose the maximum page size.
                var getQueryResultsRequest = new GetQueryResultsRequest
                {
                    QueryExecutionId = queryExecutionId
                };

                var getQueryResultsResponse = await athenaClient.GetQueryResultsAsync(getQueryResultsRequest);
                var resultSet = getQueryResultsResponse.ResultSet;
                var columnInfoList = resultSet.ResultSetMetadata.ColumnInfo;
                var results = resultSet.Rows;

                ProcessRow(results, columnInfoList);
            }
            catch (AmazonAthenaException e)
            {
                Console.WriteLine("Error processing result rows: " + e.Message);
                throw;
            }
        }

        static void ProcessRow(List<Row> rows, List<ColumnInfo> columnInfoList)
        {
            foreach (var row in rows)
            {
                var allData = row.Data;
                foreach (var data in allData)
                {
                    Console.WriteLine("The value of the column is " + data.VarCharValue);
                }
            }
        }
    }
}
jhkqcmku

jhkqcmku2#

StartQueryExecutionRequest类中,有WorkGroup属性。可以使用该属性指定要在其中运行查询的工作组的名称。有关详细信息,请参阅StartQueryExecutionRequest
此外,您可以使用下面的代码通过假设另一个可以访问Athena工作组的角色来调用Athena。

var roleArnToAssume = "arn:aws:iam::123456789012:role/testAssumeRole";

// Create the SecurityToken client
var client = new Amazon.SecurityToken.AmazonSecurityTokenServiceClient(REGION);

// Create the request to use with the AssumeRoleAsync call.
var assumeRoleReq = new AssumeRoleRequest()
{
    DurationSeconds = 1600,
    RoleSessionName = "Session1",
    RoleArn = roleArnToAssume
};

// Finally assume the rol
var assumeRoleRes = await client.AssumeRoleAsync(assumeRoleReq);

// Access the credentials
var credentials = assumeRoleRes.Credentials;

// Finally, create athena client with those credentials
var athenaClient = new AmazonAthenaClient(Amazon.RegionEndpoint.USEast1, credentials: credentials);

相关问题