Trying to get a Lambda function to change the number of fleet instances from 0 to 1

I have been trying to make it so that if someone attempts to connect to the GameLift fleet while the current amount of instances are 0 then the Lambda function ConnectToClientServerTrust would then update the fleet instance count to 1 so that they are therefore able to play. We have the fleet at 0 instances so we do not incur costs while it is not in use but do not know what the best way is to put it back above 0 without just manually doing it each time. Below is the code of the Lambda function. Its mainly the code from the MegaFrogRace example.

const AWS = require(‘aws-sdk’);
const GameLift = new AWS.GameLift({region: ‘ap-southeast-2’});

const TrustFleetID = “fleet-5222c4b3-c6c5-439a-a175-fac99950f0e4”;

exports.handler = async (event, context) => {
let response;
let gameSessions;
let instanceCount;
let maxSize;

await GameLift.describeFleetCapacity({
    FleetIds: [
        TrustFleetID
    ],
    Limit: 1,
    NextToken: '1'
}). promise().then(data => {
    instanceCount = data.InstanceCounts.ACTIVE;
}).catch(err =>{
    response = err;
});

if(instanceCount <= 0){
    await GameLift.updateFleetCapacity({
    FleetId: TrustFleetID,
    DesiredInstances: 1,
    Location: 'ap-southeast-2',
    MaxSize: 1,
    MinSize: 0
}). promise().then(data => {
    maxSize = data.maxSize;
}).catch(err =>{
    response = err;
});
}


// find any sessions that have available players
await GameLift.searchGameSessions({
    FleetId: TrustFleetID,
    FilterExpression: "hasAvailablePlayerSessions=true"
}).promise().then(data => {
    gameSessions = data.GameSessions;
}).catch(err => {
    response = err;
});

// if the response object has any value at any point before the end of
// the function that indicates a failure condition so return the response
if(response != null) 
{
    return response;
}

// if there are no sessions, then we need to create a game session
let selectedGameSession;
if(gameSessions.length == 0)
{
    console.log("No game session detected, creating a new one");
    await GameLift.createGameSession({
        MaximumPlayerSessionCount: 2,   // only two players allowed per game
        FleetId: TrustFleetID
    }).promise().then(data => {
        selectedGameSession = data.GameSession;
    }).catch(err => {
       response = err; 
    });

    if(response != null)
    {
        return response;
    }
}
else
{
    // we grab the first session we find and join it
    selectedGameSession = gameSessions[0];
    console.log("Game session exists, will join session ", selectedGameSession.GameSessionId);
}

// there isn't a logical way selectedGameSession could be null at this point
// but it's worth checking for in case other logic is added
if(selectedGameSession != null) 
{
    // now we have a game session one way or the other, create a session for this player
    await GameLift.createPlayerSession({
        GameSessionId : selectedGameSession.GameSessionId ,
        PlayerId: context.awsRequestId
    }).promise().then(data => {
        console.log("Created player session ID: ", data.PlayerSession.PlayerSessionId);
        response = data.PlayerSession;
    }).catch(err => {
       response = err; 
    });

}
else
{
    response = {
      statusCode: 500,
      body: JSON.stringify({
          message: "Unable to find game session, check GameLift API status"
      })
    };
}

return response;

};

The error i get is Error in Lambda: {}.

Have you tried manually triggering the lambda? Either via the test event in the Lambda console or locally via a local main?

It does look like some of your code allows the response to be empty. So I would ensure all paths set the response.

And I would also add logging to your lambda (you will get a log group by default if using Cfn/CDK). You can set a small log retention policy to avoid incurring any real costs from CloudWatch logs.

Sorry i am very new to Gamelift and Lambda. I am not entirely sure on how to manually trigger the Lambda function.

Quick reply:

LambdaFunctionLogGroup:
Type: 'AWS::Logs::LogGroup'
DependsOn: MyLambda
Properties:
  RetentionInDays: 30
  LogGroupName: !Join 
    - ''
    - - /aws/lambda/
      - !Ref MyLambda

So i started checking the logs in CloudWatch and putting console logs. I got the first part fixed up but now it is erroring in the UpdateFleetCapacity section. The error that is being returned is Error in Lambda: {“message”:“Unexpected key ‘Location’ found in params”,“code”:“UnexpectedParameter”,“time”:“2021-04-13T04:29:28.761Z”}

Check your params on your UpdateFleetCapacity call. For python params should be simple ie

response = client.update_fleet_capacity(
                    FleetId=fleet_id,
                    DesiredInstances=0,
                    MaxSize=0
                )

Location is an optional new field, should be set to a region string, but only if you are using multi-region fleets and care to scale outside of the home region (I would assume).

If you are still having issues, can you provide:
a) your code snippet for calling UpdateFleetCapacity
b) your fleet id
c) a couple of approx times you may have made this call (please include time zone or UTC times)

And I can get the GameLift team to take a look as multi-region fleets are fairly new and maybe theres a problem with UpdateFleetCapacity