5

I'm trying to test an API that needs AWS credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN). Right now I'm setting them explicitly in the Postman environment, but I need to do this every time I'm refreshing my credentials. So I'm looking for a way to automatically add these and found Postman pre-request scripts.

Unfortunately there is no process.env and also no fs.readFileSync(to read ~/.aws/credentials). Is there another way to pass information from outside Postman?

Nino
  • 429
  • 2
  • 8

2 Answers2

2

You could pass those values in with Newman:

The --env-var flag can be using the resolve placeholder variables in a collection {{token}} to the value passed at runtime.

When using Newman from the Command Line

newman run collection.json --env-var "token=$TOKEN"

When using Newman as a library:

const newman = require('newman')

newman.run({
  collection: 'collection.json',
  envVar: [ 
      { "key":"token", "value":`${process.env.TOKEN}`}
  ],
})
Danny Dainton
  • 23,069
  • 6
  • 67
  • 80
  • Thanks Danny, this already helps a lot. Nevertheless I would still like to have this functionality in the Postman UI when I develop my collection. – Nino Jun 08 '21 at 19:36
0

This is how I resolved it,

  1. Built an API that runs in my machine at port 8080. This GET API endpoint will read my AWS credentials located at ~/.aws/credentials and will return them as

{ "aws_access_key_id": "", "aws_secret_access_key": "" }

  1. Within Postman client tool, I have created collection variables called key and secret
  2. Within collection Pre-request Script added this code, purpose of this code is to call API endpoint running on my machine and accept payload response and update collection variables
pm.sendRequest({
    url: "http://localhost:8080/aws/credentials",
    method: "GET",
    }, function (_, response) {
        if (response.status == "OK") {
            const body = response.json()
            pm.collectionVariables.set("key", body.aws_access_key_id)
            pm.collectionVariables.set("secret", body.aws_secret_access_key)
            return
        } else {
            throw new Error(response.text() || "Error fetching aws credentials")
        }
    }
)
  1. My API requests within collection can now use key and secret variable values to execute followup steps.

One drawback I see is each developer in a team has to have this local API endpoint. I'm interested to know if there is a better way to solve this problem.

ChaseD20
  • 119
  • 1
  • 4