Search code examples
kuberneteskubectlkubernetes-secrets

How to copy kubernetes secret content to single file


I have kubernetes secrets as following and want to copy all content as is to single file.

api: 
  url: https://app.a.com/test
application: 
  metadata: name="myname"

in yaml i have following

apiVersion: apps/v1
kind: Deployment
metadata:
  name: active-mq
  labels:
    app: active-mq
spec:
  replicas: 1
  selector:
    matchLabels:
      app: active-mq
  template:
    metadata:
      labels:
        app: active-mq
    spec:
      containers:
        - image: [name-of-my-image-from-docker-hub]
          name: active-mq
          imagePullPolicy: Always
          resources:
            requests:
              memory: 500Mi
              cpu: 200m
            limits:
              memory: 1000Mi
              cpu: 400m
          volumeMounts:
          - name: active-creds
            mountPath: /home/my.properties
            subPath: my.properties
      volumes:
      - name: active-creds
        secret:
          secretName: creds
      restartPolicy: Always

when i bash to container i see it create the directory name as my.properties under /home. is that something i am missing here? I am expecting my.properties should contain following

api: 
  url: https://app.a.com/test
application: 
  metadata: name="myname"


Solution

  • It's unclear from your question but I suspect not creating the Secret to reflect the keys that you need. In this case, the key becomes the filename (i.e. my.properties). You don't want the keys to be api and application.

    # Create the file locally
    echo '
    api: 
      url: https://app.a.com/test
    application: 
      metadata: name="myname"' > my.foo
    
    # Create the Kubernetes Secret from it
    # NB This renames to "my.properties" from "my.foo"
    kubectl create secret generic test \
    --from-file=my.properties=${PWD}/my.foo
    
    get secret test \
    --output=yaml
    

    Yields:

    apiVersion: v1
    data:
      my.properties: YXBpOiAK...
    kind: Secret
    metadata:
      name: test
    type: Opaque
    

    NOTE data contains a key my.properties

    Then:

    # Using your Deployment
    kubectl apply \
    --filename=71484256.yaml
    
    # I replaced your image with busybox
    kubectl exec \
    --stdin --tty \
    deployment/test \
    -- ash
    

    Then from within the container's shell:

    # ls /home
    my.properties
    
    # more /home/my.properties
    api: 
      url: https://app.a.com/test
    application: 
      metadata: name=myname