Add a service_account.json to kubectl secrets

1/19/2022

How to add a service_account.json file to kubernetes secrets? I tried

kubectl create secret generic service_account.json -n sample --from-file=service_account=service_account.json

but it returns an error failed to create secret Secret "service_account.json" is invalid: metadata.name

-- Tony Stark
kubernetes

1 Answer

1/19/2022

You can't use service_account.json as the (metadata) name for a Kubernetes resource. Here's the documentation on permitted Object Names and IDs

You can use:

kubectl create secret generic foo \
--namespace=sample \
--from-file=key.json=service_account.json

NOTE The secret is called foo and it creates a key called key.json whose value is the content of the file called service_account.json.

NOTE If you don't wish to rename the object name in the secret, you can omit it; I renamed the file service_account.json to key.json in the secret. To retain the original name, just use --from-file=service_account.json.

You should then able to volume mount the secret in the Container where you need to use it:

apiVersion: v1
kind: Namespace
metadata:
  labels:
    control-plane: controller-manager
  name: system
---
apiVersion: apps/v1
kind: Deployment
metadata: {}
spec:
  template:
    spec:
      containers:
        - name: my-container
          volumeMounts:
            - name: bar
              mountPath: /secrets
      volumes:
        - name: bar
          secret:
            secretName: foo

NOTE The container can access the foo secret's content as /secrets/key.json.

Intentionally distinct names foo, bar etc. for clarity

-- DazWilkin
Source: StackOverflow