[How2Tips] Call AWS APIs from EC2 instances with no credentials

Reading time : < 1 min

Sometimes you need to consume some AWS services directly from your EC2 instances. Usually, when you develop those consumers you will use your own credentials (for instance, credentials stored in ~/.aws/credentials). But when it comes to deploy your service on EC2 instances, you won’t put your own credentials on some config file:

  • It has some security issues : a malicious user gaining access to your config file can impersonate you
  • If you want to revoke your credentials, your services will not work until you upload your new credentials
  • Harder to track which instance has access to what

Fortunately, AWS provides a way to give temporary credentials to your EC2 instances. You can then associate permissions to your instances, and thus, design a way better security model.

Hence this behavior is pretty much undocumented, here are two examples. Note that, you need to configure IAM Role attached to your EC2 instance in order to test them:


require __DIR__ . '/vendor/autoload.php';

use Aws\Credentials\InstanceProfileProvider;
use Aws\Ec2\Ec2Client;

$client = new EC2Client([
    'credentials' => new InstanceProfileProvider(),
    'region'      => 'eu-west-1',
    'version'     => 'latest',


var AWS = require('aws-sdk');

AWS.config.region = 'eu-central-1';
AWS.config.apiVerison = 'latest';
AWS.config.credentials = new AWS.EC2MetadataCredentials({
  httpOptions: { timeout: 5000 }

AWS.config.credentials.get(function (err) {
  if (err) {


  var ec2 = new AWS.EC2();
  ec2.describeTags(function (err, data) {
    console.log(err, data);

Any questions ? Ping us at @KNPLabs

Thanks Albin for the article !