Reputation: 2261
I was successful in starting a task using AWS-SDK for node js but this response does not contain the IP address of the instance on which the task was initiated. Is there any way I can retrieve the IP of the instance in the same reply ?
What are the possible options ? However I do see the containerInstanceArn in the reply.
var ecs = new ECS_AWS.ECS({apiVersion: '2014-11-13'});
var params = {
family: 'test-code123',
containerDefinitions: [
{
environment: [],
name: 'simple-app',
image: 'abc/cbuild:2',
cpu: 1024,
memory: 500,
portMappings: [
{
containerPort: 8000,
hostPort: 8000
}
],
command: [
'node',
'/src1/server.js',
'8000'
],
essential: true
}
]
};
ecs.registerTaskDefinition(params, function(err, data) {
if (err) console.log("ECS error" + err + err.stack); // an error occurred
else console.log(data);
Once the task is created I make a runTask API Call
var ecs = new ECS_AWS.ECS({apiVersion: '2014-11-13'});
var params = {
taskDefinition: 'arn:aws:ecs:ap-southeast-1:32:task-definition/test-code123:5', /* required */
count: 1,
};
ecs.runTask(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
Upvotes: 4
Views: 7605
Reputation: 13
Here's an example of how to get the IP for a running task using the AWS SDK:
import { DescribeNetworkInterfacesCommand, EC2Client } from "@aws-sdk/client-ec2"
import { DescribeTasksCommand, ECSClient, ListTasksCommand, Service } from "@aws-sdk/client-ecs"
async function ipForService(service: Service, clusterId: string) {
const ecs = new ECSClient()
const ec2 = new EC2Client({})
if(!service.runningCount) {
return undefined
}
const listTasksCommand = new ListTasksCommand({
cluster: clusterId,
serviceName: service.serviceName
})
const listTasksResult = await ecs.send(listTasksCommand)
const taskArns = listTasksResult.taskArns ?? []
if(!taskArns.length) {
return undefined
}
const describeTasksCommand = new DescribeTasksCommand({
cluster: clusterId,
tasks: taskArns,
})
const describeTasksResult = await ecs.send(describeTasksCommand)
// In this example, we assume that there's only one running task
// Modify this logic if you need the IP for a specific task
const task = describeTasksResult.tasks![0]
const taskEni = task.attachments![0].details!.find(detail => detail.name === "networkInterfaceId")!.value!
const describeNetworkInterfacesCommand = new DescribeNetworkInterfacesCommand({
NetworkInterfaceIds: [taskEni]
})
const describeNetworkInterfacesResult = await ec2.send(describeNetworkInterfacesCommand)
return describeNetworkInterfacesResult.NetworkInterfaces?.[0].Association?.PublicIp
}
Upvotes: -1
Reputation: 8401
Based on the existing ECS apis, there is no direct API to get the IP of the instance where the task started.
You will need to use describeContainerInstances
API of ecs to get the physical id of the instance and then call ec2 APIs to get the IP of the instance where the task was started.
Upvotes: 6