@@ -18,6 +18,7 @@ package writer
1818
1919import (
2020 "errors"
21+ "fmt"
2122 "io/ioutil"
2223 "os"
2324 "path"
@@ -91,21 +92,39 @@ func (f *fsCertWriter) doWrite() (*generator.Artifacts, error) {
9192 if err != nil {
9293 return nil , err
9394 }
95+
96+ // AtomicWriter's algorithm only manages files using symbolic link.
97+ // If a file is not a symbolic link, will ignore the update for it.
98+ // We want to cleanup for AtomicWriter by removing old files that are not symbolic links.
99+ err = prepareToWrite (f .Path )
100+ if err != nil {
101+ return nil , err
102+ }
103+
94104 aw , err := atomic .NewAtomicWriter (f .Path , log .WithName ("atomic-writer" ).
95105 WithValues ("task" , "processing webhook" ))
96106 if err != nil {
97107 return nil , err
98108 }
99- // AtomicWriter's algorithm only manages files using symbolic link.
100- // If a file is not a symbolic link, will ignore the update for it.
101- // We want to cleanup for AtomicWriter by removing old files that are not symbolic links.
102- prepareToWrite (f .Path )
103109 err = aw .Write (certToProjectionMap (certs ))
104110 return certs , err
105111}
106112
107113// prepareToWrite ensures it directory is compatible with the atomic.Writer library.
108- func prepareToWrite (dir string ) {
114+ func prepareToWrite (dir string ) error {
115+ _ , err := os .Stat (dir )
116+ switch {
117+ case os .IsNotExist (err ):
118+ log .Info (fmt .Sprintf ("cert directory %v doesn't exist, creating" , dir ))
119+ // TODO: figure out if we can reduce the permission. (Now it's 0777)
120+ err = os .MkdirAll (dir , 0777 )
121+ if err != nil {
122+ return fmt .Errorf ("can't create dir: %v" , dir )
123+ }
124+ case err != nil :
125+ return err
126+ }
127+
109128 filenames := []string {CACertName , ServerCertName , ServerKeyName }
110129 for _ , f := range filenames {
111130 abspath := path .Join (dir , f )
@@ -124,6 +143,7 @@ func prepareToWrite(dir string) {
124143 }
125144 }
126145 }
146+ return nil
127147}
128148
129149func (f * fsCertWriter ) read () (* generator.Artifacts , error ) {
0 commit comments