The correct way to fix apt-get warning “Key is stored in legacy trusted.gpg keyring” in Debian and Ubuntu

If you used a PPA or added an external repository in Debian 11, Ubuntu 22.04, chances are that you recently have been seeing a message like this every time you run apt-get:

W: https://{{some_reporsitory_url}}: Key is stored in legacy trusted.gpg keyring (/etc/apt/trusted.gpg), see the DEPRECATION section in apt-key(8) for details.

This is a warning that apt-key is printing out. The tool apt-key was responsible for managing the list of keys used by apt to authenticate packages. Packages which could be authenticated using these keys were considered trusted.

The reason behind the warning is clear: apt-key is deprecated and will no longer be available in versions beyond Debian 11 and beyond Ubuntu 22.04.

There are several answers on stackoverflow.com, askubuntu.com, stackexchange.com and other similar sites, as well as on several blogs, where authors suggest exporting the keys from /etc/apt/trusted.gpg and adding them to /etc/apt/trusted.gpg.d/repository_keyring.gpg. However, that introduces a security concern, as the keys in that folders can be used to authenticate any repository, which is the exact reason why apt-key got deprecated in the first place. So by taking that advice, we undo the work that has been done to improve the security of Debian and Ubuntu.

The correct way to deal with this issue is mentioned in the Recommendation under the DEPRECATION section in the apt-key documentation. It explicitly states to place the key files anywhere on the filesystem except in the /etc/apt/trusted.gpg.d/ folder, and then to add references to those keys in apt repositories files that are usually in /etc/apt/sources.list.d/{{repository}}.

Ok let’s do it:

First we find the offending key(s). The following is a fancy way to get the list of keys that are exists in /etc/apt/trusted.gpg:

apt-key --keyring /etc/apt/trusted.gpg list 2>/dev/null |
grep -A 1 "pub " |grep -v "pub " | grep -v '\-\-' | awk -v OFS="" '{$1=$1}1'

Now for every offending {{key}} we export the key from /etc/apt/trusted.gpg, dearmor it and save the output in a separate gpg file:

apt-key --keyring /etc/apt/trusted.gpg export {{key}} | gpg --dearmor -o /etc/apt/keyrings/{{key}}.gpg

Then {{key}} in the related {{repository}}. That means editing the related apt repository file usually under /etc/apt/sources.list.d/{{repository}} and add [singed-by=/etc/apt/keyrings/{{key}}.gpg] between deb and the repository url that follows

deb [singed-by=/etc/apt/keyrings/{{key}}.gpg] {{repository_url}} {{release}} {{package}}

And we repeat for all offending {{key}}s... and That's it.

I would like to automate that task with ansible. 
Any ideas on how to implement that?

Looking forward for suggestions!