Christopher Littlewood
Christopher Littlewood

Reputation: 803

Authenticating and Running an EC2 Instance: AWS

I am attempting to create an EC2 instance and then add it to my Auto Scaling group. I am having a lot of issues trying to authenticate. I am looking for a simple way to authenticate a request using my access key to simply start an instance. What I have tried so far:

//Authenticate AWS:
var myCredentials = new AWS.CognitoIdentityCredentials({
  IdentityPoolId:'us-west-2:IdentityPoolID'
}); 

var myConfig = new AWS.Config({
  credentials: myCredentials, region: 'us-west-2'
});

AWS.config = myConfig

var minInst = 1;
var maxInst = 3;

var ec2 = new AWS.EC2();
//Set up parameters for EC2 Instances:
var params = {
  ImageId: 'ami-6e1a0117',
  MaxCount: minInst,
  MinCount: maxInst, 
  InstanceInitiatedShutdownBehavior: 'terminate',
  InstanceType: 't2.micro',
  Monitoring: {
    Enabled: false
  },
  NetworkInterfaces: [{
    AssociatePublicIpAddress: true,
    DeleteOnTermination: true,
  }],
  Placement: {
    AvailabilityZone: 'us-west-2',
  },
  SecurityGroupIds: [
    'sg-b0307ccd',
  ],
  SecurityGroups: [
    'CAB432Assignment2SG',
  ],

};
ec2.runInstances(params, function(err, data) {
  if (err){
    console.log(err, err.stack); //An error occurred
  }
  else{
    console.log(data); //Successful Response
  }
});

I know this code is wrong. I just don't know to fix it. The error I get is:

CredentialsError: Missing credentials in config

Any help would be greatly appreciated.

Upvotes: 1

Views: 556

Answers (1)

Mark B
Mark B

Reputation: 200537

Delete this section of code entirely:

//Authenticate AWS:
var myCredentials = new AWS.CognitoIdentityCredentials({
  IdentityPoolId:'us-west-2:IdentityPoolID'
}); 

var myConfig = new AWS.Config({
  credentials: myCredentials, region: 'us-west-2'
});

AWS.config = myConfig

Change this:

var ec2 = new AWS.EC2();

To this:

var ec2 = new AWS.EC2({region: 'us-west-2'});

Then go read this page in the Setting Credentials in Node.js documentation. In particular, you need to do one of the following:

  • Add an IAM role to your EC2 instance, if this is running on EC2.
  • Add an IAM execution role to your Lambda function if this is running on Lambda.
  • Create either a ~/.aws/credentials file with your keys. This can be done with the aws configure command if you have the AWS CLI installed.
  • Set the keys as environment variables.

Upvotes: 2

Related Questions