Search code examples
jsonterraformjsondecodervaultkey-pair

How to use jsondecode for to decode public aws ssh keys from vault


I am trying to see how to go about retrieving some aws public ssh keys from vault using terraform. Vault is returning a string instead of an array of strings, so I looks like it would have to treat the whole response as a json object. How would I use jsondecode to help me decode that string?

terrform code 
 
    terraform {
      required_providers {
        aws = {
        source  = "hashicorp/aws"
        version = "~> 4.0"
      }
    }
  }

   # Configure the AWS Provider
     provider "aws" {
     region = "us-west-1"
     }

     provider "vault" {}


     resource "aws_instance" "web" {
      ami           = "ami-1123456789p9"
      instance_type = "t3.micro"
      vpc_security_group_ids = ["sg-55552f1"] 
      subnet_id = "subnet-dee55a55"
      key_name = aws_key_pair.tf-key.key_name
  
     }

     resource "aws_key_pair" "tf-key" {
     key_name = "linuxkey"
     public_key = data.vault_kv_secret_v2.linux_key.data_json

     }


     data "vault_kv_secret_v2" "linux_key" {
     mount = "test/test/test/secret"
     name = "chef/linux_users/user"
       }

      output "testing123" {
      value = data.vault_kv_secret_v2.linux_key.data_json
      sensitive = true
      }

      output response 
    {
    "format_version": "1.1",
    "terraform_version": "1.4.3-dev",
     "planned_values": {
        "outputs": {
        "testing123": {
        "sensitive": true,
        "type": "string",
        "value": "{\"groups\":[\"itadmins\"],\"shell\":\"/bin/bash\",\"ssh_keys\": 
     [\"ssh-rsa XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX etc."}"
        }
       },

Solution

  • The jsondecode function performs the serialization and marshalling required to convert the JSON formatted string into a HCL2 type. The documentation also provides the information on type coercion during the conversion.

    After jsondecode(data.vault_kv_secret_v2.linux_key.data_json) returns the HCL2 type, one can then access values as usual:

    jsondecode(data.vault_kv_secret_v2.linux_key.data_json)["ssh_keys"][0]
    

    To access (for example) the zeroth element of the list containing the ssh keys in the JSON response from the Vault server.