1 Commits

Author SHA1 Message Date
43773c33e8 Merge pull request 'jinja templates' (#6) from feature/tt/raw-templates into main
All checks were successful
continuous-integration/drone/tag Build is passing
continuous-integration/drone/push Build is passing
Reviewed-on: #6
2022-11-26 20:38:19 +00:00
10 changed files with 49 additions and 333 deletions

View File

@ -27,42 +27,8 @@ jobs:
version: v3.10.0 version: v3.10.0
- name: Run chart-releaser - name: Run chart-releaser
uses: helm/chart-releaser-action@v1.5.0 uses: helm/chart-releaser-action@v1.4.1
with: with:
charts_dir: charts charts_dir: charts
env: env:
CR_TOKEN: "${{ secrets.GITHUB_TOKEN }}" CR_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
- name: Get app version from chart
uses: mikefarah/yq@v4.30.8
id: app_version
with:
cmd: yq '.appVersion' charts/bitwarden-crd-operator/Chart.yaml
- name: Create SBOM
uses: anchore/sbom-action@v0
with:
image: lerentis/bitwarden-crd-operator:${{ steps.app_version.outputs.result }}
- name: Publish SBOM
uses: anchore/sbom-action/publish-sbom@v0
with:
sbom-artifact-match: ".*\\.spdx\\.json"
- name: Get Latest Tag
id: previoustag
uses: WyriHaximus/github-action-get-previous-tag@v1
- name: Download SBOM from github action
uses: actions/download-artifact@v3
with:
name: ${{ env.ANCHORE_SBOM_ACTION_PRIOR_ARTIFACT }}
- name: Add SBOM to release
uses: svenstaro/upload-release-action@v2
with:
repo_token: ${{ secrets.GITHUB_TOKEN }}
file_glob: true
file: lerentis-bitwarden-crd-operator_*.spdx.json
tag: ${{ steps.previoustag.outputs.tag }}
overwrite: true

View File

@ -1,17 +1,13 @@
FROM alpine:latest as builder FROM alpine:latest as builder
ARG BW_VERSION=2023.1.0 ARG BW_VERSION=2022.8.0
RUN apk add wget unzip RUN apk add wget unzip
RUN cd /tmp && wget https://github.com/bitwarden/clients/releases/download/cli-v${BW_VERSION}/bw-linux-${BW_VERSION}.zip && \ RUN cd /tmp && wget https://github.com/bitwarden/clients/releases/download/cli-v${BW_VERSION}/bw-linux-${BW_VERSION}.zip && \
unzip /tmp/bw-linux-${BW_VERSION}.zip unzip /tmp/bw-linux-${BW_VERSION}.zip
FROM alpine:3.17.2 FROM alpine:3.17
ARG PYTHON_VERSION=3.10.10-r0
ARG PIP_VERSION=22.3.1-r1
ARG GCOMPAT_VERSION=1.1.0-r0
COPY --from=builder /tmp/bw /usr/local/bin/bw COPY --from=builder /tmp/bw /usr/local/bin/bw
COPY requirements.txt requirements.txt COPY requirements.txt requirements.txt
@ -22,7 +18,7 @@ RUN set -eux; \
mkdir -p /home/bw-operator; \ mkdir -p /home/bw-operator; \
chown -R bw-operator /home/bw-operator; \ chown -R bw-operator /home/bw-operator; \
chmod +x /usr/local/bin/bw; \ chmod +x /usr/local/bin/bw; \
apk add gcc musl-dev libstdc++ gcompat=${GCOMPAT_VERSION} python3=${PYTHON_VERSION} py3-pip=${PIP_VERSION}; \ apk add gcc musl-dev libstdc++ gcompat python3 py-pip; \
pip install -r requirements.txt --no-warn-script-location; \ pip install -r requirements.txt --no-warn-script-location; \
apk del --purge gcc musl-dev libstdc++; apk del --purge gcc musl-dev libstdc++;
@ -30,5 +26,5 @@ COPY --chown=bw-operator:bw-operator src /home/bw-operator
USER bw-operator USER bw-operator
ENTRYPOINT [ "kopf", "run", "--log-format=json", "--all-namespaces", "--liveness=http://0.0.0.0:8080/healthz" ] ENTRYPOINT [ "kopf", "run", "--all-namespaces", "--liveness=http://0.0.0.0:8080/healthz" ]
CMD [ "/home/bw-operator/bitwardenCrdOperator.py", "/home/bw-operator/kv.py", "/home/bw-operator/dockerlogin.py", "/home/bw-operator/template.py"] CMD [ "/home/bw-operator/bitwardenCrdOperator.py", "/home/bw-operator/kv.py", "/home/bw-operator/dockerlogin.py", "/home/bw-operator/template.py"]

View File

@ -56,7 +56,7 @@ And you are set to create your first secret using this operator. For that you ne
```yaml ```yaml
--- ---
apiVersion: "lerentis.uploadfilter24.eu/v1beta4" apiVersion: "lerentis.uploadfilter24.eu/v1beta3"
kind: BitwardenSecret kind: BitwardenSecret
metadata: metadata:
name: name-of-your-management-object name: name-of-your-management-object
@ -65,11 +65,9 @@ spec:
- element: - element:
secretName: nameOfTheFieldInBitwarden # for example username secretName: nameOfTheFieldInBitwarden # for example username
secretRef: nameOfTheKeyInTheSecretToBeCreated secretRef: nameOfTheKeyInTheSecretToBeCreated
secretScope: login # for custom entries on bitwarden use 'fields'
- element: - element:
secretName: nameOfAnotherFieldInBitwarden # for example password secretName: nameOfAnotherFieldInBitwarden # for example password
secretRef: nameOfAnotherKeyInTheSecretToBeCreated secretRef: nameOfAnotherKeyInTheSecretToBeCreated
secretScope: login # for custom entries on bitwarden use 'fields'
id: "A Secret ID from bitwarden" id: "A Secret ID from bitwarden"
name: "Name of the secret to be created" name: "Name of the secret to be created"
namespace: "Namespace of the secret to be created" namespace: "Namespace of the secret to be created"
@ -98,7 +96,7 @@ For managing registry credentials, or pull secrets, you can create another kind
```yaml ```yaml
--- ---
apiVersion: "lerentis.uploadfilter24.eu/v1beta4" apiVersion: "lerentis.uploadfilter24.eu/v1beta3"
kind: RegistryCredential kind: RegistryCredential
metadata: metadata:
name: name-of-your-management-object name: name-of-your-management-object
@ -127,50 +125,6 @@ metadata:
type: dockerconfigjson type: dockerconfigjson
``` ```
## BitwardenTemplate
One of the more freely defined types that can be used with this operator you can just pass a whole template:
```yaml
---
apiVersion: "lerentis.uploadfilter24.eu/v1beta4"
kind: BitwardenTemplate
metadata:
name: name-of-your-management-object
spec:
filename: "Key of the secret to be created"
name: "Name of the secret to be created"
namespace: "Namespace of the secret to be created"
template: |
---
api:
enabled: True
key: {{ bitwarden_lookup("A Secret ID from bitwarden", "login or fields", "name of a field in bitwarden") }}
allowCrossOrigin: false
apps:
"some.app.identifier:some_version":
pubkey: {{ bitwarden_lookup("A Secret ID from bitwarden", "login or fields", "name of a field in bitwarden") }}
enabled: true
```
This will result in something like the following object:
```yaml
apiVersion: v1
data:
Key of the secret to be created: "base64 encoded and rendered template with secrets injected directly from bitwarden"
kind: Secret
metadata:
annotations:
managed: bitwarden-template.lerentis.uploadfilter24.eu
managedObject: namespace/name-of-your-management-object
name: Name of the secret to be created
namespace: Namespace of the secret to be created
type: Opaque
```
please note that the rendering engine for this template is jinja2, with an addition of a custom `bitwarden_lookup` function, so there are more possibilities to inject here.
## Short Term Roadmap ## Short Term Roadmap
- [ ] support more types - [ ] support more types

View File

@ -4,9 +4,9 @@ description: Deploy the Bitwarden CRD Operator
type: application type: application
version: "v0.5.2" version: "v0.4.0"
appVersion: "0.5.2" appVersion: "0.4.0"
keywords: keywords:
- operator - operator
@ -85,21 +85,23 @@ annotations:
--- ---
api: api:
enabled: True enabled: True
key: {{ bitwarden_lookup("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "fields", "key") }} key: {{ bitwarden_lookup("466fc4b0-ffca-4444-8d88-b59d4de3d928", "fields", "key") }}
allowCrossOrigin: false allowCrossOrigin: false
apps: apps:
"some.app.identifier:some_version": "some.app.identifier:some_version":
pubkey: {{ bitwarden_lookup("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "fields", "public_key") }} pubkey: {{ bitwarden_lookup("466fc4b0-ffca-4444-8d88-b59d4de3d928", "fields", "public_key") }}
enabled: true enabled: true
artifacthub.io/license: MIT artifacthub.io/license: MIT
artifacthub.io/operator: "true" artifacthub.io/operator: "true"
artifacthub.io/changes: | artifacthub.io/changes: |
- kind: added
description: "Added Template type"
- kind: added
description: "Added logo"
- kind: changed - kind: changed
description: "Bump alpine from 3.17.1 to 3.17.2" description: "BitwardenSecret now requires a 'secretScope' to be defined. Can eigher be 'login' or 'fields'"
- kind: changed - kind: fixed
description: "Bump bitwarden cli from 2022.11.0 to 2023.1.0" description: "fixed hardcoded reference to 'login' even tho secrets could also be in 'fields' scope"
- kind: changed
description: "Bump python version from 3.10.9-r1 to 3.10.10-r0"
artifacthub.io/images: | artifacthub.io/images: |
- name: bitwarden-crd-operator - name: bitwarden-crd-operator
image: lerentis/bitwarden-crd-operator:0.5.1 image: lerentis/bitwarden-crd-operator:0.4.0

View File

@ -4,14 +4,9 @@
Bitwarden CRD Operator is a kubernetes Operator based on [kopf](https://github.com/nolar/kopf/). The goal is to create kubernetes native secret objects from bitwarden. Bitwarden CRD Operator is a kubernetes Operator based on [kopf](https://github.com/nolar/kopf/). The goal is to create kubernetes native secret objects from bitwarden.
<p align="center">
<img src="https://github.com/Lerentis/bitwarden-crd-operator/blob/main/logo.png?raw=true" alt="Bitwarden CRD Operator Logo" width="200"/>
</p>
> DISCLAIMER: > DISCLAIMER:
> This project is still very work in progress :) > This project is still very work in progress :)
## Getting started ## Getting started
You will need a `ClientID` and `ClientSecret` ([where to get these](https://bitwarden.com/help/personal-api-key/)) as well as your password. You will need a `ClientID` and `ClientSecret` ([where to get these](https://bitwarden.com/help/personal-api-key/)) as well as your password.
@ -56,7 +51,7 @@ And you are set to create your first secret using this operator. For that you ne
```yaml ```yaml
--- ---
apiVersion: "lerentis.uploadfilter24.eu/v1beta4" apiVersion: "lerentis.uploadfilter24.eu/v1beta3"
kind: BitwardenSecret kind: BitwardenSecret
metadata: metadata:
name: name-of-your-management-object name: name-of-your-management-object
@ -65,11 +60,9 @@ spec:
- element: - element:
secretName: nameOfTheFieldInBitwarden # for example username secretName: nameOfTheFieldInBitwarden # for example username
secretRef: nameOfTheKeyInTheSecretToBeCreated secretRef: nameOfTheKeyInTheSecretToBeCreated
secretScope: login # for custom entries on bitwarden use 'fields'
- element: - element:
secretName: nameOfAnotherFieldInBitwarden # for example password secretName: nameOfAnotherFieldInBitwarden # for example password
secretRef: nameOfAnotherKeyInTheSecretToBeCreated secretRef: nameOfAnotherKeyInTheSecretToBeCreated
secretScope: login # for custom entries on bitwarden use 'fields'
id: "A Secret ID from bitwarden" id: "A Secret ID from bitwarden"
name: "Name of the secret to be created" name: "Name of the secret to be created"
namespace: "Namespace of the secret to be created" namespace: "Namespace of the secret to be created"
@ -98,7 +91,7 @@ For managing registry credentials, or pull secrets, you can create another kind
```yaml ```yaml
--- ---
apiVersion: "lerentis.uploadfilter24.eu/v1beta4" apiVersion: "lerentis.uploadfilter24.eu/v1beta3"
kind: RegistryCredential kind: RegistryCredential
metadata: metadata:
name: name-of-your-management-object name: name-of-your-management-object
@ -127,46 +120,10 @@ metadata:
type: dockerconfigjson type: dockerconfigjson
``` ```
## BitwardenTemplate ## Short Term Roadmap
One of the more freely defined types that can be used with this operator you can just pass a whole template: - [ ] support more types
- [x] offer option to use a existing secret in helm chart
```yaml - [x] host chart on gh pages
--- - [x] write release pipeline
apiVersion: "lerentis.uploadfilter24.eu/v1beta4" - [x] maybe extend spec to offer modification of keys as well
kind: BitwardenTemplate
metadata:
name: name-of-your-management-object
spec:
filename: "Key of the secret to be created"
name: "Name of the secret to be created"
namespace: "Namespace of the secret to be created"
template: |
---
api:
enabled: True
key: {{ bitwarden_lookup("A Secret ID from bitwarden", "login or fields", "name of a field in bitwarden") }}
allowCrossOrigin: false
apps:
"some.app.identifier:some_version":
pubkey: {{ bitwarden_lookup("A Secret ID from bitwarden", "login or fields", "name of a field in bitwarden") }}
enabled: true
```
This will result in something like the following object:
```yaml
apiVersion: v1
data:
Key of the secret to be created: "base64 encoded and rendered template with secrets injected directly from bitwarden"
kind: Secret
metadata:
annotations:
managed: bitwarden-template.lerentis.uploadfilter24.eu
managedObject: namespace/name-of-your-management-object
name: Name of the secret to be created
namespace: Namespace of the secret to be created
type: Opaque
```
please note that the rendering engine for this template is jinja2, with an addition of a custom `bitwarden_lookup` function, so there are more possibilities to inject here.

View File

@ -1,3 +1,3 @@
kopf==1.36.0 kopf==1.35.6
kubernetes==25.3.0 kubernetes==25.3.0
Jinja2==3.1.2 Jinja2==3.1.2

View File

@ -53,58 +53,8 @@ def create_managed_registry_secret(spec, name, namespace, logger, **kwargs):
logger.info(f"Registry Secret {secret_namespace}/{secret_name} has been created") logger.info(f"Registry Secret {secret_namespace}/{secret_name} has been created")
@kopf.on.update('registry-credential.lerentis.uploadfilter24.eu') @kopf.on.update('registry-credential.lerentis.uploadfilter24.eu')
@kopf.timer('registry-credential.lerentis.uploadfilter24.eu', interval=900) def my_handler(spec, old, new, diff, **_):
def update_managed_registry_secret(spec, status, name, namespace, logger, body, **kwargs): pass
username_ref = spec.get('usernameRef')
password_ref = spec.get('passwordRef')
registry = spec.get('registry')
id = spec.get('id')
secret_name = spec.get('name')
secret_namespace = spec.get('namespace')
old_config = None
old_secret_name = None
old_secret_namespace = None
if 'kopf.zalando.org/last-handled-configuration' in body.metadata.annotations:
old_config = json.loads(body.metadata.annotations['kopf.zalando.org/last-handled-configuration'])
old_secret_name = old_config['spec'].get('name')
old_secret_namespace = old_config['spec'].get('namespace')
secret_name = spec.get('name')
secret_namespace = spec.get('namespace')
if old_config is not None and (old_secret_name != secret_name or old_secret_namespace != secret_namespace):
# If the name of the secret or the namespace of the secret is different
# We have to delete the secret an recreate it
logger.info("Secret name or namespace changed, let's recreate it")
delete_managed_secret(old_config['spec'], name, namespace, logger, **kwargs)
create_managed_registry_secret(spec, name, namespace, logger, **kwargs)
return
unlock_bw(logger)
logger.info(f"Locking up secret with ID: {id}")
secret_json_object = json.loads(get_secret_from_bitwarden(id))
api = kubernetes.client.CoreV1Api()
annotations = {
"managed": "registry-credential.lerentis.uploadfilter24.eu",
"managedObject": f"{namespace}/{name}"
}
secret = kubernetes.client.V1Secret()
secret.metadata = kubernetes.client.V1ObjectMeta(name=secret_name, annotations=annotations)
secret = create_dockerlogin(logger, secret, secret_json_object, username_ref, password_ref, registry)
try:
obj = api.replace_namespaced_secret(
name=secret_name,
body=secret,
namespace="{}".format(secret_namespace))
logger.info(f"Secret {secret_namespace}/{secret_name} has been updated")
except:
logger.warn(
f"Could not update secret {secret_namespace}/{secret_name}!")
@kopf.on.delete('registry-credential.lerentis.uploadfilter24.eu') @kopf.on.delete('registry-credential.lerentis.uploadfilter24.eu')
def delete_managed_secret(spec, name, namespace, logger, **kwargs): def delete_managed_secret(spec, name, namespace, logger, **kwargs):

View File

@ -5,7 +5,6 @@ import json
from utils.utils import unlock_bw, get_secret_from_bitwarden, parse_login_scope, parse_fields_scope from utils.utils import unlock_bw, get_secret_from_bitwarden, parse_login_scope, parse_fields_scope
def create_kv(secret, secret_json, content_def): def create_kv(secret, secret_json, content_def):
secret.type = "Opaque" secret.type = "Opaque"
secret.data = {} secret.data = {}
@ -19,20 +18,11 @@ def create_kv(secret, secret_json, content_def):
if key == "secretScope": if key == "secretScope":
_secret_scope = value _secret_scope = value
if _secret_scope == "login": if _secret_scope == "login":
value = parse_login_scope(secret_json, _secret_key) secret.data[_secret_ref] = str(base64.b64encode(parse_login_scope(secret_json, _secret_key).encode("utf-8")), "utf-8")
if value is None:
raise Exception(f"Field {_secret_key} has no value in bitwarden secret")
secret.data[_secret_ref] = str(base64.b64encode(
value.encode("utf-8")), "utf-8")
if _secret_scope == "fields": if _secret_scope == "fields":
value = parse_fields_scope(secret_json, _secret_key) secret.data[_secret_ref] = str(base64.b64encode(parse_fields_scope(secret_json, _secret_key).encode("utf-8")), "utf-8")
if value is None:
raise Exception(f"Field {_secret_key} has no value in bitwarden secret")
secret.data[_secret_ref] = str(base64.b64encode(
value.encode("utf-8")), "utf-8")
return secret return secret
@kopf.on.create('bitwarden-secret.lerentis.uploadfilter24.eu') @kopf.on.create('bitwarden-secret.lerentis.uploadfilter24.eu')
def create_managed_secret(spec, name, namespace, logger, body, **kwargs): def create_managed_secret(spec, name, namespace, logger, body, **kwargs):
@ -52,68 +42,18 @@ def create_managed_secret(spec, name, namespace, logger, body, **kwargs):
"managedObject": f"{namespace}/{name}" "managedObject": f"{namespace}/{name}"
} }
secret = kubernetes.client.V1Secret() secret = kubernetes.client.V1Secret()
secret.metadata = kubernetes.client.V1ObjectMeta( secret.metadata = kubernetes.client.V1ObjectMeta(name=secret_name, annotations=annotations)
name=secret_name, annotations=annotations)
secret = create_kv(secret, secret_json_object, content_def) secret = create_kv(secret, secret_json_object, content_def)
obj = api.create_namespaced_secret( obj = api.create_namespaced_secret(
namespace="{}".format(secret_namespace), secret_namespace, secret
body=secret
) )
logger.info(f"Secret {secret_namespace}/{secret_name} has been created") logger.info(f"Secret {secret_namespace}/{secret_name} has been created")
@kopf.on.update('bitwarden-secret.lerentis.uploadfilter24.eu') @kopf.on.update('bitwarden-secret.lerentis.uploadfilter24.eu')
@kopf.timer('bitwarden-secret.lerentis.uploadfilter24.eu', interval=900) def my_handler(spec, old, new, diff, **_):
def update_managed_secret(spec, status, name, namespace, logger, body, **kwargs): pass
content_def = body['spec']['content']
id = spec.get('id')
old_config = None
old_secret_name = None
old_secret_namespace = None
if 'kopf.zalando.org/last-handled-configuration' in body.metadata.annotations:
old_config = json.loads(body.metadata.annotations['kopf.zalando.org/last-handled-configuration'])
old_secret_name = old_config['spec'].get('name')
old_secret_namespace = old_config['spec'].get('namespace')
secret_name = spec.get('name')
secret_namespace = spec.get('namespace')
if old_config is not None and (old_secret_name != secret_name or old_secret_namespace != secret_namespace):
# If the name of the secret or the namespace of the secret is different
# We have to delete the secret an recreate it
logger.info("Secret name or namespace changed, let's recreate it")
delete_managed_secret(old_config['spec'], name, namespace, logger, **kwargs)
create_managed_secret(spec, name, namespace, logger, body, **kwargs)
return
unlock_bw(logger)
logger.info(f"Locking up secret with ID: {id}")
secret_json_object = json.loads(get_secret_from_bitwarden(id))
api = kubernetes.client.CoreV1Api()
annotations = {
"managed": "bitwarden-secret.lerentis.uploadfilter24.eu",
"managedObject": f"{namespace}/{name}"
}
secret = kubernetes.client.V1Secret()
secret.metadata = kubernetes.client.V1ObjectMeta(
name=secret_name, annotations=annotations)
secret = create_kv(secret, secret_json_object, content_def)
try:
obj = api.replace_namespaced_secret(
name=secret_name,
body=secret,
namespace="{}".format(secret_namespace))
logger.info(f"Secret {secret_namespace}/{secret_name} has been updated")
except:
logger.warn(
f"Could not update secret {secret_namespace}/{secret_name}!")
@kopf.on.delete('bitwarden-secret.lerentis.uploadfilter24.eu') @kopf.on.delete('bitwarden-secret.lerentis.uploadfilter24.eu')
def delete_managed_secret(spec, name, namespace, logger, **kwargs): def delete_managed_secret(spec, name, namespace, logger, **kwargs):
@ -123,8 +63,6 @@ def delete_managed_secret(spec, name, namespace, logger, **kwargs):
try: try:
api.delete_namespaced_secret(secret_name, secret_namespace) api.delete_namespaced_secret(secret_name, secret_namespace)
logger.info( logger.info(f"Secret {secret_namespace}/{secret_name} has been deleted")
f"Secret {secret_namespace}/{secret_name} has been deleted")
except: except:
logger.warn( logger.warn(f"Could not delete secret {secret_namespace}/{secret_name}!")
f"Could not delete secret {secret_namespace}/{secret_name}!")

View File

@ -1,7 +1,6 @@
import kopf import kopf
import base64 import base64
import kubernetes import kubernetes
import json
from utils.utils import unlock_bw from utils.utils import unlock_bw
from lookups.bitwarden_lookup import bitwarden_lookup from lookups.bitwarden_lookup import bitwarden_lookup
@ -50,53 +49,8 @@ def create_managed_secret(spec, name, namespace, logger, body, **kwargs):
logger.info(f"Secret {secret_namespace}/{secret_name} has been created") logger.info(f"Secret {secret_namespace}/{secret_name} has been created")
@kopf.on.update('bitwarden-template.lerentis.uploadfilter24.eu') @kopf.on.update('bitwarden-template.lerentis.uploadfilter24.eu')
@kopf.timer('bitwarden-template.lerentis.uploadfilter24.eu', interval=900) def my_handler(spec, old, new, diff, **_):
def update_managed_secret(spec, status, name, namespace, logger, body, **kwargs): pass
template = spec.get('template')
filename = spec.get('filename')
secret_name = spec.get('name')
secret_namespace = spec.get('namespace')
old_config = None
old_secret_name = None
old_secret_namespace = None
if 'kopf.zalando.org/last-handled-configuration' in body.metadata.annotations:
old_config = json.loads(body.metadata.annotations['kopf.zalando.org/last-handled-configuration'])
old_secret_name = old_config['spec'].get('name')
old_secret_namespace = old_config['spec'].get('namespace')
secret_name = spec.get('name')
secret_namespace = spec.get('namespace')
if old_config is not None and (old_secret_name != secret_name or old_secret_namespace != secret_namespace):
# If the name of the secret or the namespace of the secret is different
# We have to delete the secret an recreate it
logger.info("Secret name or namespace changed, let's recreate it")
delete_managed_secret(old_config['spec'], name, namespace, logger, **kwargs)
create_managed_secret(spec, name, namespace, logger, body, **kwargs)
return
unlock_bw(logger)
api = kubernetes.client.CoreV1Api()
annotations = {
"managed": "bitwarden-template.lerentis.uploadfilter24.eu",
"managedObject": f"{namespace}/{name}"
}
secret = kubernetes.client.V1Secret()
secret.metadata = kubernetes.client.V1ObjectMeta(name=secret_name, annotations=annotations)
secret = create_template_secret(secret, filename, template)
try:
obj = api.replace_namespaced_secret(
name=secret_name,
body=secret,
namespace="{}".format(secret_namespace))
logger.info(f"Secret {secret_namespace}/{secret_name} has been updated")
except:
logger.warn(
f"Could not update secret {secret_namespace}/{secret_name}!")
@kopf.on.delete('bitwarden-template.lerentis.uploadfilter24.eu') @kopf.on.delete('bitwarden-template.lerentis.uploadfilter24.eu')
def delete_managed_secret(spec, name, namespace, logger, **kwargs): def delete_managed_secret(spec, name, namespace, logger, **kwargs):
@ -109,3 +63,10 @@ def delete_managed_secret(spec, name, namespace, logger, **kwargs):
logger.info(f"Secret {secret_namespace}/{secret_name} has been deleted") logger.info(f"Secret {secret_namespace}/{secret_name} has been deleted")
except: except:
logger.warn(f"Could not delete secret {secret_namespace}/{secret_name}!") logger.warn(f"Could not delete secret {secret_namespace}/{secret_name}!")
#if __name__ == '__main__':
# tpl = """
# Calling the 'bitwarden_lookup' function:
# {{ bitwarden_lookup(2, 2) }}
# """
# print(render_template(tpl))

View File

@ -1,5 +1,4 @@
import os import os
import json
import subprocess import subprocess
class BitwardenCommandException(Exception): class BitwardenCommandException(Exception):
@ -9,11 +8,6 @@ def get_secret_from_bitwarden(id):
return command_wrapper(command=f"get item {id}") return command_wrapper(command=f"get item {id}")
def unlock_bw(logger): def unlock_bw(logger):
status_output = command_wrapper("status")
status = json.loads(status_output)['status']
if status == 'unlocked':
logger.info("Already unlocked")
return
token_output = command_wrapper("unlock --passwordenv BW_PASSWORD") token_output = command_wrapper("unlock --passwordenv BW_PASSWORD")
tokens = token_output.split('"')[1::2] tokens = token_output.split('"')[1::2]
os.environ["BW_SESSION"] = tokens[1] os.environ["BW_SESSION"] = tokens[1]
@ -31,8 +25,6 @@ def parse_login_scope(secret_json, key):
return secret_json["login"][key] return secret_json["login"][key]
def parse_fields_scope(secret_json, key): def parse_fields_scope(secret_json, key):
if "fields" not in secret_json:
return None
for entry in secret_json["fields"]: for entry in secret_json["fields"]:
if entry['name'] == key: if entry['name'] == key:
return entry['value'] return entry['value']