Dynamic inventory can take a long time to fetch hosts in group (aws_ec2)

I have a dynamic inventory created with the aws_ec2 inventory plugin. I added a new group and now my inventory is taking a noticeably long time to load:

groups:

u: “tags.get(‘Name’) | regex_search(‘u[\d]+’)”

I’ve written a short python program to test how long this is taking:

import os
import time

runs = 50

start = time.time()
for i in range(runs):
os.system(“ansible --list u”)
end = time.time()

print(f"Runtime: {end - start:.2f} for {runs} runs")
print(f"Avergae runtime: {(end - start) / runs:.2f}")

Some results:

runs | avg time per run (s)
1 | 2.5
5 | 4.4
10 | 2.3
25 | 5.3
50 | 2.7

From these results I am concluding that sometimes this can take very long… 5 or more seconds to wait for a command like ansible --list u is brutal.

  1. Why is this taking so long???
  2. Is there a better way to accomplish what I have here?