Rust AWS SDK: create keys with IAM role on the fly? - rust

I'm trying to create temporary(?) credentials using an IAM role. From what I learned in the package's GitHub issues, they implemented the feature for Rust but I just can't figure where it is.
The equivalent code in NodeJS is:
import * as aws from 'aws-sdk'
ecsCredentials = new aws.ECSCredentials()
await ecsCredentials.getPromise()
aws.config.credentials = ecsCredentials

I ended up doing:
use aws_config::ecs::EcsCredentialsProvider;
// When run in AWS, this uses the execution role to create temporary credentials.
let credentials_provider_builder = EcsCredentialsProvider::builder();
let creadentials_provider = credentials_provider_builder.build();
let credentials = creadentials_provider.credentials();
// Convert to Config object and connect.
let conf = aws_config::from_env().credentials_provider(credentials).region("us-east-1").load().await;
let conf = Config::new(&conf);
let client = Client::from_conf(conf);

Related

How to Get Azure Event Hub Connection String in C#?

Given a Event Hub Name, how can I get connection string in C#?
I googled a bit, but nothing useful found so far.
Thanks
Using AAD authentication for an EventHub
var credential = new DefaultAzureCredential();
// or use
// var credential = new Azure.Identity.ClientSecretCredential("tenantId", "clientId", "clientSecret");
EventHubProducerClient producerClient = new EventHubProducerClient(txtNamespace.Text, txtEventHub.Text, credential
var consumerClient = new EventHubConsumerClient(EventHubConsumerClient.DefaultConsumerGroupName, txtNamespace.Text, txtEventHub.Text, credential)
Full example and docs
Acquiring the Connection Strings of configured Access Policies
You can use these two Nuget packages:
Azure.ResourceManager.EventHubs
Azure.Identity
Then you can use the resource group name and the eventhub name to retrieve the connection string. You will need to iterate the subscriptions and resource groups if you don't have this information.
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.EventHubs;
ArmClient client = new ArmClient(new DefaultAzureCredential());
// Or use
// ArmClient client = new ArmClient(new Azure.Identity.ClientSecretCredential("tenantId", "clientId", "clientSecret"));
var subscription = await client.GetDefaultSubscriptionAsync();
var resourceGroup = await subscription.GetResourceGroupAsync("myresourcegroup");
var eventhubNamespace = await resourceGroup.Value.GetEventHubsNamespaceAsync("namespacename");
var rules = eventhubNamespace.Value.GetEventHubsNamespaceAuthorizationRules();
foreach (var rule in rules)
{
var keys = await rule.GetKeysAsync();
Console.WriteLine(keys.Value.PrimaryConnectionString);
Console.WriteLine(keys.Value.SecondaryConnectionString);
}
Not sure if this is what you mean, but if you want to access an Event Hub through C# you need to provide the EH connection string into your code. This can be retrieved by adding a Shared access policy for the Event hub that you are trying to access.
Edit: If you are trying to actually create the connection string yourself you could follow this sample where you create the SAS-token yourself. But you would still need to provide the Primary key that is set on the policy from Azure.

How to retrieve temporary credentials using rest api or by using AssumeRole in AWS SDK , facing these issues currently with my approach

ive been trying to retrieve temporary credentials using role arn but getting an error of EC2 Metadata not found in AWS SDK . here is my approach
AssumeRoleRequest request = new AssumeRoleRequest();
request.RoleArn = "arn:aws:iam::532634566192:role/ap-redshift";
request.RoleSessionName = "newsessionanme";
client = new AmazonSecurityTokenServiceClient();
AssumeRoleResponse resp = client.AssumeRole(request);
Console.WriteLine(resp.Credentials);
Console.ReadLine();
2nd approach
client = new AmazonSecurityTokenServiceClient();
var response = client.AssumeRole(new AssumeRoleRequest
{
RoleArn = "arn:aws:iam::532634566192:role/ap-redshift",
RoleSessionName = "newsessionanme"
});
AssumedRoleUser assumedRoleUser = response.AssumedRoleUser;
Credentials credentials = response.Credentials;
This is the error i am getting "Unable to get IAM security credentials from EC2 Instance Metadata Service.'" as also shown in the picture .
enter image description here

Reference to type 'IResourceGroups' claims it is defined in 'Microsoft.Azure.Management.ResourceManager.Fluent', but it could not be found

I am getting this error when trying to call azure.ResourceGroups.List() where azure is an instance of Iazure.
project.json
Please have a try to following code to get list of resources. I test it on my side, it works correctly. We also could use the Resources - List By Resource Group Rest API to do that.
I install Microsoft.Azure.Management.ResourceManager.Fluent 1.0.0 as you and use console app to test. Here is my testing code:
var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantId, AzureEnvironment.AzureGlobalCloud);
var subscriptionId = "your_subscriptionId";
var azure = new ResourceManagementClient(credentials) { SubscriptionId = subscriptionId };
var resource = azure.ResourceGroups.ListAsync().Result;

How authenticate with gcloud credentials an Dialogflow API

I have a Node JS app that make requests to a Dialogflow agent. I actually use a temporally token based request, but how can i change this to do it through google service credentials? (https://cloud.google.com/docs/authentication/getting-started). I have a credencial created (with billing added), and the service_account json file.
I would like to use the Dialogflow package in node (https://www.npmjs.com/package/dialogflow) but i don't underestand how to use it with the json file.
const projectId = 'ENTER_PROJECT_ID_HERE';
const sessionId = 'quickstart-session-id';
const query = 'hello';
const languageCode = 'en-US';
// Instantiate a DialogFlow client.
const dialogflow = require('dialogflow');
const sessionClient = new dialogflow.SessionsClient();
// Define session path
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
The example of the package use Project ID and Session ID, but not with a json file like the example of the google services (or using big query like How to authenticate with gcloud big query using a json credentials file?). Anyway, where can i get this project and session id?
Please, if someone can help me or guide how to do this in a better way?. Thanks
First you have to create a service account and download a .JSON format file of credentials on your local system.
Now, there are three ways to use that credentials for authentication/authorisation in dialogflow library.
Method 1
Create a environment variable GOOGLE_APPLICATION_CREDENTIALS and it's value should be the absolute path of that JSON credentials file.By this method, google library will implicitly loads the file and use that credentials for authentication. We don't need to do anything inside our code relating to this credentials file.
export GOOGLE_APPLICATION_CREDENTIALS="<absolute-path-of-json-file>" # for UNIX,LINUX
# then run your code, google library will pick credentials file and loads it automatically
Method 2
Assume, you know the absolute path of your JSON file and put that as value in below snippet of credentials_file_path variable.
// You can find your project ID in your Dialogflow agent settings
const projectId = '<project-id-here>';
const sessionId = '<put-chat-session-id-here>';
// const sessionid = 'fa2d5904-a751-40e0-a878-d622fa8d65d9'
const query = 'hi';
const languageCode = 'en-US';
const credentials_file_path = '<absolute-file-path-of-JSON-file>';
// Instantiate a DialogFlow client.
const dialogflow = require('dialogflow');
const sessionClient = new dialogflow.SessionsClient({
projectId,
keyFilename: credentials_file_path,
});
Method 3
You can note down the project_id, client_email and private_key from the JSON, use them in your code for authentication explicitly.
// You can find your project ID in your Dialogflow agent settings
const projectId = '<project-id-here>';
const sessionId = '<put-chat-session-id-here>';
// const sessionid = 'fa2d5904-a751-40e0-a878-d622fa8d65d9'
const query = 'hi';
const languageCode = 'en-US';
const credentials = {
client_email: '<client-email-here>',
private_key:
'<private-key-here>',
};
// Instantiate a DialogFlow client.
const dialogflow = require('dialogflow');
const sessionClient = new dialogflow.SessionsClient({
projectId,
credentials,
});
Here is how you can do it with a service account code sample is in kotlin and definitely can be translated into the node.js sdk
val credentialsProvider = FixedCredentialsProvider.create(ServiceAccountCredentials
.fromStream(Classes.getResourceAsStream([YOUR JSON CONFIG FILE GOES HERE])))
val sessionsSettings = SessionsSettings.newBuilder().setCredentialsProvider(credentialsProvider).build()
sessionsClient = SessionsClient.create(sessionsSettings)
You can get the service account from Dialogflow settings click on the service account links and then create a json config file there in ur cloud console.

Pull data from azure keyvault with node

I'm trying to pull data from Azure KeyVault with Node. I installed azure-keyvault with npm and read some of the guides that Microsoft released (e.g. https://www.npmjs.com/package/azure-keyvault) but I can't get data to output. Just for testing purposes I'd like to do something like View contents of Secret in Azure KeyVault with node.
var KeyVault = require('azure-keyvault');
var util = require('util');
var Crypto = require('crypto');
var AuthenticationContext = require('adal-node').AuthenticationContext;
var clientId = 'xxx';
var clientSecret = 'xxx';
var vaultUri = 'xxx';
I can't find an API with a list of commands that I can do with the keyvault var, how do I pull data from keyvault?
Edit: so I have var KeyVault = require('azure-keyvault');
and the KeyVault variable can be used as an object with methods listed in here: http://azure.github.io/azure-sdk-for-node/azure-keyvault/latest/?
Here is the 'azure-keyvault' library docs: http://azure.github.io/azure-sdk-for-node/azure-keyvault/latest/
I can't find an API with a list of commands that I can do with the keyvault var
you use the "keyvault var" to create a keyvault client. in the link above, see the side menu for a list of all commands.
how do I pull data from keyvault?
For example, you can use the KeyVaultClient.getSecrets function: http://azure.github.io/azure-sdk-for-node/azure-keyvault/latest/KeyVaultClient.html#getSecrets
The package azure-keyvault has been deprecated in favor of the new packages to deal with Keyvault keys, secrets and certificates separately. For your scenario, you can use the new #azure/keyvault-secrets package.
The readme at for #azure/keyvault-secrets has a variety of code snippets you can refer to. You can refer to the entire sample set for secrets too.
To read secrets from azure key vault you can use npm library read-azure-secrets, in which you will need to pass client ID, client secret, and vault URI. It will return all secrets from your key vault.
Example -
const secretClient = require('read-azure-secrets');
async function loadKeyVaultValues() {
let applicationID = '';
let applicationSecret = '';
let vaultURL = 'https://<your-key-vault-name>.vault.azure.net/';
let secrets = await secretClient.getSecrets(applicationID, applicationSecret, vaultURL);
secrets.forEach(secret => {
console.log(secret);
});
}
loadKeyVaultValues();

Resources