@@ -17,6 +17,7 @@ package leader
17
17
import (
18
18
"context"
19
19
"errors"
20
+ "fmt"
20
21
"io/ioutil"
21
22
"os"
22
23
"strings"
@@ -39,6 +40,8 @@ var errNoNS = errors.New("namespace not found for current environment")
39
40
// attempts to become the leader.
40
41
const maxBackoffInterval = time .Second * 16
41
42
43
+ const PodNameEnv = "POD_NAME"
44
+
42
45
// Become ensures that the current pod is the leader within its namespace. If
43
46
// run outside a cluster, it will skip leader election and return nil. It
44
47
// continuously tries to create a ConfigMap with the provided name and the
@@ -156,12 +159,14 @@ func myNS() (string, error) {
156
159
157
160
// myOwnerRef returns an OwnerReference that corresponds to the pod in which
158
161
// this code is currently running.
162
+ // It expects the environment variable POD_NAME to be set by the downwards API
159
163
func myOwnerRef (ctx context.Context , client crclient.Client , ns string ) (* metav1.OwnerReference , error ) {
160
- hostname , err := os .Hostname ( )
161
- if err != nil {
162
- return nil , err
164
+ podName := os .Getenv ( PodNameEnv )
165
+ if podName == "" {
166
+ return nil , errors . New ( fmt . Sprintf ( "required env %s not set, please configure downward API" , PodNameEnv ))
163
167
}
164
- logrus .Debugf ("found hostname: %s" , hostname )
168
+
169
+ logrus .Debugf ("found podname: %s" , podName )
165
170
166
171
myPod := & corev1.Pod {
167
172
TypeMeta : metav1.TypeMeta {
@@ -170,8 +175,8 @@ func myOwnerRef(ctx context.Context, client crclient.Client, ns string) (*metav1
170
175
},
171
176
}
172
177
173
- key := crclient.ObjectKey {Namespace : ns , Name : hostname }
174
- err = client .Get (ctx , key , myPod )
178
+ key := crclient.ObjectKey {Namespace : ns , Name : podName }
179
+ err : = client .Get (ctx , key , myPod )
175
180
if err != nil {
176
181
logrus .Errorf ("failed to get pod: %v" , err )
177
182
return nil , err
0 commit comments