# Extracting hostname via JS

**URL:** <https://community.dynatrace.com/t/extracting-hostname-via-js/51545>\
**Category:** Automations\
**Tags:** workflows, javascript\
**Created:** [May 8, 2025, 8:49pm UTC](https://community.dynatrace.com/t/extracting-hostname-via-js/51545 "2025-05-08T20:49:10Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Dyno193](https://avatars.discourse-cdn.com/v4/letter/d/57b2e6/32.png) [@Dyno193](https://community.dynatrace.com/u/Dyno193)\
**Post date:** [May 8, 2025, 8:49pm UTC](https://community.dynatrace.com/t/extracting-hostname-via-js/51545/1 "2025-05-08T20:49:10Z")

</div>

Struggling to extract hostname via JS, can someone look at this - I keep getting Constratins Violated

try {  
// Use entitySelector that just gets all HOSTS  
console.log(`Searching for all hosts first…`);  
const allHostsResponse = await monitoredEntitiesClient.getEntities({  
entitySelector: `type(“HOST”)`,  
fields: ‘+properties.monitoringState’  
});

console.log(`Found ${allHostsResponse.totalCount} hosts in total`);

// Manually filter for the hostname  
const matchedHosts = allHostsResponse.entities.filter(entity =\>  
entity.displayName === hostname ||  
entity.entityId.includes(hostname.toUpperCase())  
);

if (matchedHosts.length === 0) {  
console.warn(`Host ${hostname} not found in Dynatrace environment`);  
results.push({  
hostname,  
status: “error”,  
message: “Host not found in Dynatrace environment”  
});  
continue;  
}

Snippet of Code

---

<div class="post-metadata">

**Author:** ![AravindhanV](https://avatars.discourse-cdn.com/v4/letter/a/ed8c4c/32.png) [@AravindhanV](https://community.dynatrace.com/u/AravindhanV)\
**Post date:** [May 9, 2025, 7:22am UTC](https://community.dynatrace.com/t/extracting-hostname-via-js/51545/2 "2025-05-09T07:22:51Z")

</div>

Hi&nbsp;[@Dyno193](https://community.dynatrace.com/user/90188),&nbsp;If the requirement is to get the hostnames from the environment, then u can get it from the notebook, with the query,

fetch dt.entity.host  
| fields entity.name

Or if any automation then u can use this code to get the entity name and add ur condition on top of it.

export default async function ({ executionId }) {  
try {  
const query = `  
fetch dt.entity.host  
| fields entity.name`;

const queryResponse = await queryExecutionClient.queryExecute({ body: { query } });

if (queryResponse.requestToken) {  
const pollQuery = async (requestToken) =\> {  
let pollResponse;  
do {  
pollResponse = await queryExecutionClient.queryPoll({ requestToken });  
if (pollResponse.state === ‘RUNNING’) {  
await new Promise((resolve) =\> setTimeout(resolve, 1000));  
}  
} while (pollResponse.state === ‘RUNNING’);  
return pollResponse;  
};

const finalResponse = await pollQuery(queryResponse.requestToken);  
console.log(finalResponse.result.records);  
}  
} catch (error) {  
console.error(`Dynatrace API Error:`, error);  
return { error: error.message };  
}  
}

Thanks,
