Cloud-init: Add apt source key gnupg not installed

aptcloud-init

I've a cloud-init script that is used to create and configure a Debian 10 VM and since I want to install nginx I have to add its repository to APT. I'm trying to do it like this:

apt:
  preserve_sources_list: true
  sources:
    nginx:
      source: "deb http://nginx.org/packages/debian $DEBIAN_RELEASE nginx"
      key: |
          -----BEGIN PGP PUBLIC KEY BLOCK-----
          Version: GnuPG v2.0.22 (GNU/Linux)

          mQENBE5OMmIBCAD+FPYKGriGGf7NqwKfWC83cBV01gabgVWQmZbMcFzeW+hMsgxH
          QxnZZIbETgcSwFtDun0XiqPwPZgyuXVm9PAbLZRbfBzm8wR/3SWygqZBBLdQk5TE
          ...
          =EWWI
          -----END PGP PUBLIC KEY BLOCK-----
packages:
  - nginx

It doesn't work and cloud-init's log file at /run/cloud-init/result.json shows the following:

{
 "v1": {
  "datasource": "DataSourceConfigDrive [net,ver=2][source=/dev/vdb]",
  "errors": [
   "('apt-configure', ProcessExecutionError(\"Unexpected error while running command.\\nCommand: ['apt-key', 'add', '-']\\nExit code: 255\\nReason: -\\nStdout: \\nStderr: E: gnupg, gnupg2 and gnupg1 do not seem to be installed, but one of them is required for this operation\"))"
  ]
 }
}

Why? It complaints it can't use apt-key because gnupg isn't present however how can I make sure it exists? According to /etc/cloud/cloud.cfg cloud-init runs the APT modules before installing packages so how am I supposed to get a working apt-key with gnupg?

Thank you.

Best Answer

Add this to your configuration, which causes apt-get to run after the network is up but before the official cloud-init sections:

bootcmd:
  - DEBIAN_FRONTEND=noninteractive apt-get -yq update
  - DEBIAN_FRONTEND=noninteractive apt-get -yq install gnupg

There's another solution on the Debian Bug Tracking System which shows you how to specify a new source and key without causing a call to gnupg, but (for me) that makes your cloud-init configuration less clear.