EC2 metadata not available in runCommand

Very new to NixOS, trying to figure out where I’m being stupid here.

I’m using the latest official AMI to launch an EC2, and I’m trying to read some secrets from AWS Secrets Manager as part of the initial build using runCommand. The IAM role attached to the instance has permissions to read from my secret.

Even though I can read the secrets if I use the CLI after the build is complete, it seems that runCommand doesn’t have any of the networking/system setup that would allow it to use the EC2 instance metadata. I know that setup must come from some of the imported modules in the virtualisation directory, but I can’t for the life of me figure out how to actually “import” that environment into a runCommand.

Here's my configuration.nix:
{ modulesPath, config, pkgs, ... }: {

  imports = [
    "${modulesPath}/virtualisation/amazon-image.nix"
  ];

  ec2.hvm = true;

  environment.systemPackages = with pkgs; [
    vim
    wget
    curl
    awscli2
    consul
  ];

  services.consul = {
    enable = true;
    extraConfigs = {
      tlsCertKey = 
        let
          secrets = pkgs.runCommand "secrets" {
            buildInputs = [ pkgs.awscli2 ];
          } ''
            aws secretsmanager get-secret-value --secret-id mycluster/testsecret > $out
          '';
        in
          builtins.readFile secrets;
    };
  }
}

I then get errors either like this:

$ nixos-rebuild switch
building Nix...
building the system configuration...
building '/nix/store/q99bkqx0f0q2rn8sxpc26wpznyisvdji-secrets.drv'...

You must specify a region. You can also configure your region by running "aws configure".

Or if I supply a region, then this:

$ nixos-rebuild switch
building Nix...
building the system configuration...
building '/nix/store/vfsp64hisbgwr2j0vfxcfqvd8pyfsysc-secrets.drv'...

Unable to locate credentials. You can configure credentials by running "aws configure".

So what am I missing here? Is my approach all wrong, or do I just need to pass something to get the instance metadata / AWS network dependency inside of a runCommand?

Ok so I think my strategy here is actually going to be a systemd oneshot script that runs after nixos-rebuild switch.

I will update the thread with my solution once it’s complete.