0

Friends, I am trying the implement a init container which will check if MYSQL is ready for connections and I am trying to use nslookup for this. The point is, how to pass the dns through a variable?

It worked like this:

command: ['sh', '-c', 'until nslookup mysql-primary.default.svc.cluster.local; 
do echo waiting for mysql; sleep 2; done;']

But not like this:

command: ['sh', '-c', 'until nslookup $(MYSQL_HOST); do echo waiting for mysql; sleep 2; done;']

Any Idea how I could get the second option working?

marcelo
  • 373
  • 6
  • 16
  • You can use variable from command line, from file etc. The question is, how do You want to pass this variable. – Jaur Jan 08 '21 at 15:46
  • Sorry. didn't notice that you are using kubernetes. In Kubernets you can use ConfigMaps https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/ – Jaur Jan 08 '21 at 15:52

2 Answers2

2

MYSQL_HOST seems to be an environment variable and not a command.

$(MYSQL_HOST) will execute MYSQL_HOST as a command in a subshell (and that will not work in this case).

You probably want to use "${MYSQL_HOST}" instead.

Idriss Neumann
  • 3,760
  • 2
  • 23
  • 32
1

The problem is, that $() executes a subshell and tries to evaluate a commend in there. What you actually want is variable expansion via ${}.

Here a working example for you:

A pod with an init-container, with a MYSQL_HOST environment variable:

---
apiVersion: v1
kind: Pod
metadata:
  name: mysql-pod
spec:
  containers:
    - name: busybox-container
      image: busybox
      command: ['sh', '-c', 'echo The app is running! && sleep 3600']
  initContainers:
    - name: mysql-check
      image: busybox
      command: ['sh', '-c', 'until nslookup ${MYSQL_HOST}; do echo waiting for mysql; sleep 2; done;']
      env:
        - name: MYSQL_HOST
          value: "mysql-primary.default.svc.cluster.local"

The pod starts after you create a corresponding service:

kubectl create svc clusterip mysql-primary --tcp=3306

For the sake of completeness: YAML of the service (not necessarily relevant in this case)

---
apiVersion: v1
kind: Service
metadata:
  creationTimestamp: null
  labels:
    app: mysql-primary
  name: mysql-primary
spec:
  ports:
  - name: "3306"
    port: 3306
    protocol: TCP
    targetPort: 3306
  selector:
    app: mysql-primary
  type: ClusterIP
status:
  loadBalancer: {}
Dharman
  • 30,962
  • 25
  • 85
  • 135
cvoigt
  • 517
  • 5
  • 16