Question: Dynamic inventory create group based on 2 tags

I may be trying to over-complicate this and the solution is really simple and I’ve just overlooked it, but asking in case someone else has attempted this and has a solution.

I’m attempting to setup dynamic inventory of EC2 instances and they are currently tagged following a standard practice. I can easily use - key: tags.X | lower and - key: tags.Y | lower under keyed_groups and I get them grouped by the tags separately but what I really need is a group that is formatted underscore delimited like tags.X_tags.Y | lower if tags.Y is present otherwise omit it. I thought this would be possible as a jinja2 template but all attempts I’ve tried thus far have not produced the desired outcome.

TIA

I don’t have an EC2 account handy to test the ec2 inventory plugin against but ansible has a ternary operator that you can use to make a simple if/then/else condition. Here is an example playbook: