Home > Software design >  Passing key:value pairs to Python Dictionary
Passing key:value pairs to Python Dictionary

Time:08-09

I am trying to iterate over a key:value list and insert into a python dict() within the hvac method to create or update a secret within Vault.

I have a key:value list in a file:

key1:value1
key2:value2
key3:value3
import hvac


def write_secret():
    client = hvac.Client(url='http://localhost:8200')
    print(f" Is client authenticated: {client.is_authenticated()}")
    with open("keylist.txt") as keyfile:
        for line in keyfile:
            key, value = line.split(":", 1)
            key=key.strip()
            value=value.strip()
            client.secrets.kv.v2.create_or_update_secret(    
                path = 'keys',
                secret = dict(
                    key=value
                ),
                cas = 0,
                )
write_secret()

What ends up happening in the above script is that a single key:value pair will get written to Vault.

The expected behavior would be to have the following in Vault:

key1:value1
key2:value2
key3:value3

What I get is:

key:value3 --> it seems like the values are iterating but the keys are not getting passed in

Any help would be appreciated! If more info is needed I will update the post.

Thanks!

CodePudding user response:

Use a comprehension approach with the dict constructor to build the desired secret object:

file_contents = """
key1:value1
key2:value2
key3:value3
""".strip()

secret = dict(line.split(':', 1) for line in file_contents.split())

print(secret)

Out:

{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

CodePudding user response:

You can use the csv library:

import csv

with open("file.txt") as f:
    data = dict(csv.reader(f, delimiter=":"))

{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

CodePudding user response:

This solved my issue:

def write_secret():
    client = hvac.Client(url='http://localhost:8200')
    print(f" Is client authenticated: {client.is_authenticated()}")
    with open("keylist.txt") as keyfile:
            client.secrets.kv.v2.create_or_update_secret(    
                path = 'keys',
                secret = dict(
                    line.split(':', 1) for line in keyfile
                ),
                )
write_secret()

By updating where the key:value iteration happens I was able to achieve the desired effect.

enter image description here

  • Related