How to save SSH keys generated inside the CICD pipeline as CICD variables?

Per the documentation, I’m using manually created SSH public and private key data in my CI CD pipeline via CICD variables to help provision server infrastructure. I’m using Terraform to manage the infrastructure, and everything is 100% managed by gitlab

However, as the infrastructure grows, I don’t want to use the same SSH key pair for all the infrastructure. Instead, I want to create the key pair dynamically so each has its own. Specifically, here are the goals I’d like to achieve:

  1. dynamically create the SSH key pair. So far, I’m doing that with this before_script code:
    ssh-keygen -b 4096 -N '' -q -f ~/.ssh/id_rsa <<< y

  2. dynamically save the id_rsa and id_rsa.pub values as file-type CI/CD variables in the projects CICD settings area.

Step 2 is where I’m getting tripped up. I’m not sure how to make the project interact with itself via its own pipeline, although I’m assuming it can be done since the docker executor clones a copy of the repo to kick of everything the pipeline needs to do. I don’t want to add my personal keys as those are God-mode for the entire gitlab project.

I didn’t see any examples of this in Gitlab’s ssh projects. If anyone is doing this, pleae share the code or some how-to info, or if there is a project, a link to that.

Thinking through this, each item of infrastructure has its own folder. It has its own $TF_STATE, $TF_ROOT, $TF_CACHE, etc. I thought about using a pipeline job to dynnamically create a gitlab terraform resource and adding it to the infrastructure’s directory. Something like this (rough pseudo code)

before_script:
  - dynamically create ssh keys with the above code
  - | > 
TF_VAR_gitlab_token
    cat <<EOF > proj_dir/server_keys.tf
# Configure the GitLab Provider
provider "gitlab" {
  token = var.gitlab_token # <- available via pre-configured token for this project in current CICD vars
}
resource "gitlab_project_variable" "this_infras_ssh_private_key" {
  project   = ${CI_PROJECT_ID}
  key       = "project_variable_key"
  value     = "project_variable_value"
  protected = true
  type = file
EOF

# after terraform fmt and validate, I need to somehow get this new page dynamically added back to the current branch
- git add <new_tf_file> ; git commit -m "server keys for this unique infrastructure"; git push
}

This feels elegant since terraform will manage and then destroy the keys as part of the destroy process when the infrastructure is no longer needed. Or, I’m overthinking it and a simple bash script is better? Plus, adding this new tf file back to the branch I’ve currently checked out is a circular reference, and I haven’t figured out how to work that one out yet.

Thoughts?

Thanks!