Amazon ECS Task, how to get public IP in NodeJS - amazon-web-services

I have a task (written in NodeJS) running in an ECS Fargate cluster. The task has a public IP assigned to it, but I would like to know the public IP, inside the task.
Previously I ran on EC2 and there this was pretty straightforward. I just did:
const AWS = require('aws-sdk')
const meta = new AWS.MetadataService()
async function getPublicIp() {
return new Promise((resolve, reject) => {
meta.request("/latest/meta-data/public-ipv4", function (err, data) {
if(err) {
return reject(err)
}
resolve(data)
})
})
}
The problem is I find no such thing for ECS.

Related

Pulumi automation api in google cloud function

My goal is to develop an end point using google cloud function that would update a pulumi stack configuration.
I am using pulumi automation api for it.
exports.updateServiceImageVersion = async(req, res) => {
const auto = require("#pulumi/pulumi/automation");
const pulumiProgram = async() => {
console.log("test")
}
const args = {
stackName: "xxx",
projectName: "xxx-service",
program: pulumiProgram
};
try {
const stack = await auto.LocalWorkspace.selectStack(args);
await stack.setConfig("aws:region", {
value: "us-west-2"
});
await stack.refresh({
onOutput: console.info
});
} catch (err) {
console.log(err.message);
}
res.status(200).send("test");
};
I get the below error when selectStack method is called. Could you help me in solving this error. The documentation mentions that Pulumi Automation Api requires pulumi cli to be installed and available in PATH variable. How can I do that for Google Cloud Function.
enter image description here

AWS: Get the public Image id's (AMI), for an Account, which are used to launch EC2 instances

We are trying to create an Config rule, which should warn and notify when an public image is used to launch our EC2 instances in an account. This is to avoid any security issues and unwanted user scripts to be run against our instances. We use NODE to develop the logic and I am using describeImages method of ec2, to get the public images, by passing the is-public filter, the results are actually all the public images available in that account, but we need only public images which are being used to launch our instances, I couldn't figure out how to achieve this. Any help would be greatly appreciated. Sample code, which I am using to test this is as follows.
const aws = require ('aws-sdk')
aws.config.update({ region: 'us-west-2' });
const ec2 = new aws.EC2()
const getPublicImages = async ()=>{
let publicImages
const params = {
DryRun: false,
Filters: [
{
Name: 'is-public',
Values: ['true']
}
]
// Owners: [event['accountId']]
}
publicImages = await ec2
.describeImages(params)
.promise()
.then(images => {
return (images)
})
.catch(err => {
return err
})
return publicImages
}
const handleGetPublicImages = async ()=>{
const res = await getPublicImages()
console.log(res);
}
handleGetPublicImages()

GCP cloud function to suspend and resume the GCP instances

We can use GCP cloud functions to start and stop the GCP instances but I need to work on scheduled suspend and resume of GCP instances using cloud function and scheduler.
From GCP documentation, I got that we can do start and stop using cloud functions available below
https://github.com/GoogleCloudPlatform/nodejs-docs-samples/tree/master/functions/scheduleinstance
Do we have same node JS or other language Pcgks available to suspend and resume GCP instances?
If not can we create our own for suspend/resume.
When I tried one I got below error
"TypeError: compute.zone(...).vm(...).resume is not a function
Edit, thanks Chris and Guillaume, after going through you links i have edited my code and below is my index.js file now.
For some reason when I do
gcloud functions deploy resumeInstancePubSub --trigger-topic resume-instance --runtime nodejs10 --allow-unauthenticated
i always get
Function 'resumeInstancePubSub1' is not defined in the provided module.
resumeInstancePubSub1 2020-09-04 10:57:00.333 Did you specify the correct target function to execute?
i have not worked on Node JS Or JS before, I was expecting something similar to start/stop documentation which I could make work easily using below git repo
https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git
My index.js file,
// BEFORE RUNNING:
// ---------------
// 1. If not already done, enable the Compute Engine API
// and check the quota for your project at
// https://console.developers.google.com/apis/api/compute
// 2. This sample uses Application Default Credentials for authentication.
// If not already done, install the gcloud CLI from
// https://cloud.google.com/sdk and run
// `gcloud beta auth application-default login`.
// For more information, see
// https://developers.google.com/identity/protocols/application-default-credentials
// 3. Install the Node.js client library by running
// `npm install googleapis --save`
const {google} = require('googleapis');
var compute = google.compute('beta');
authorize(function(authClient) {
var request = {
// Project ID for this request.
project: 'my-project', // TODO: Update placeholder value.
// The name of the zone for this request.
zone: 'my-zone', // TODO: Update placeholder value.
// Name of the instance resource to resume.
instance: 'my-instance', // TODO: Update placeholder value.
resource: {
// TODO: Add desired properties to the request body.
},
auth: authClient,
};
exports.resumeInstancePubSub = async (event, context, callback) => {
try {
const payload = _validatePayload(
JSON.parse(Buffer.from(event.data, 'base64').toString())
);
const options = {filter: `labels.${payload.label}`};
const [vms] = await compute.getVMs(options);
await Promise.all(
vms.map(async (instance) => {
if (payload.zone === instance.zone.id) {
const [operation] = await compute
.zone(payload.zone)
.vm(instance.name)
.resume();
// Operation pending
return operation.promise();
}
})
);
// Operation complete. Instance successfully started.
const message = `Successfully started instance(s)`;
console.log(message);
callback(null, message);
} catch (err) {
console.log(err);
callback(err);
}
};
compute.instances.resume(request, function(err, response) {
if (err) {
console.error(err);
return;
}
// TODO: Change code below to process the `response` object:
console.log(JSON.stringify(response, null, 2));
});
});
function authorize(callback) {
google.auth.getClient({
scopes: ['https://www.googleapis.com/auth/cloud-platform']
}).then(client => {
callback(client);
}).catch(err => {
console.error('authentication failed: ', err);
});
}
Here and here is the documetation for the new beta verison of the api. You can see that you can suspend an instance like:
compute.instances.suspend(request, function(err, response) {
if (err) {
console.error(err);
return;
}
And you can resume a instance in a similar way:
compute.instances.resume(request, function(err, response) {
if (err) {
console.error(err);
return;
}
GCP recently added "create schedule" feature to start and stop the VM instances based on the configured schedule.
More details can be found at
https://cloud.google.com/compute/docs/instances/schedule-instance-start-stop#managing_instance_schedules

Not able to connect to AWS documentDb from Lambda

I'm trying to connect to AWS documentDB from Lambda function but, not able to connect.
MongoClient.connect never calls the callback function connected.
TLS is off on documentDB Cluster. I'm able to connect via mongo shell.
Lambda & documentDB are in same VPC & Security group.
'use strict';
module.exports.search = async (event, context, callback) => {
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://xxx:xxxx#xxx-db.cluster-xxx.us-east-2.docdb.amazonaws.com:27017";
console.log("Starting");
MongoClient.connect(url,
{
useNewUrlParser: true
},
function(err, client) {
if(err)
throw err;
console.log("Connected");
db = client.db('mydb');
col = db.collection('mycollection');
col.find({}).toArray().then(result => {
console.log(result);
return { statusCode: 200, body: result };
}).catch(err => {
console.log('=> an error occurred: ', err);
return { statusCode: 500, body: 'error' };
});
});
};
Output only prints starting which was consoled before calling Mongo.Connect.
How to identify or debug the issue ?
Just from looking at the current code I am pretty sure your function exit before it is able to complete. Therefore, your callback is not executed
Because MongoClient.connect runs asynchronously
Try to take a look at some resource around async/await/promise and Lambda
https://medium.com/tensult/async-await-on-aws-lambda-function-for-nodejs-2783febbccd9
How to wait for async actions inside AWS Lambda?

lambda task timed out error while using rekognition

I'm building a React native app with serverless framework using AWS services.
I created a RESTapi with lambda function (nodeJs8.10 environment) and API gateway to use rekognition services such as indexFaces, listCollection, etc. My lambda is in VPC with RDS( later I'll Aurora) to store faceID and other data.
Everything works fine except rekognition services.
When I call any rekognition services it shows Task timed out after 270.04 seconds.But it works when I call locally using serverless-offline-plugin
I attach all necessary permissions to my lambda like AmazonRekognitionFullAccess
Here is my code
index.js
app.post('/myapi', function (req, res) {
var params = {
MaxResults: 3,
};
const rekognition = aws_config(); <-- rekognition configuration
rekognition.listCollections(params, function(err, data) {
if (err) {
res.json(err.stack);
console.log(err, err.stack);
}
else{
res.json(data);
console.log(data);
}
});
});
function aws_config(){
const $options = {
'region' : 'ap-southeast-2',
'version' : '2016-06-27',
'accessKeyId ' : config.ENV.aws_key,
'secretAccessKey ' : config.ENV.aws_secret,
};
return new AWS.Rekognition($options);
}
How to solve this timeout error as it doesn't show any error on CloudWatch logs?