From f2c8ae1fcbf28a09ad67af42be94b7c9ce4f849b Mon Sep 17 00:00:00 2001 From: mpl Date: Sun, 8 Nov 2015 19:50:01 +0100 Subject: [PATCH] pkg/cloudlaunch: added latestStableCoreOSImage To get the latest stable CoreOS image URL for GCE. Change-Id: I608b4c8d6d1628046cf5f03440afcf158a3ee609 --- pkg/cloudlaunch/cloudlaunch.go | 45 ++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/pkg/cloudlaunch/cloudlaunch.go b/pkg/cloudlaunch/cloudlaunch.go index 07f351b7c..bde73df91 100644 --- a/pkg/cloudlaunch/cloudlaunch.go +++ b/pkg/cloudlaunch/cloudlaunch.go @@ -19,13 +19,17 @@ limitations under the License. package cloudlaunch import ( + "encoding/json" + "errors" "flag" "io/ioutil" "log" + "net/http" "os" "path/filepath" "runtime" "strings" + "time" "golang.org/x/oauth2" "golang.org/x/oauth2/google" @@ -300,3 +304,44 @@ func instanceDisk(svc *compute.Service) *compute.AttachedDisk { } } */ + +type coreOSImage struct { + SelfLink string + CreationTimestamp time.Time + Name string +} + +type coreOSImageList struct { + Items []coreOSImage +} + +func latestStableCoreOSImage(cl *http.Client) (string, error) { + resp, err := cl.Get("https://www.googleapis.com/compute/v1/projects/coreos-cloud/global/images") + if err != nil { + return "", err + } + defer resp.Body.Close() + imageList := &coreOSImageList{} + if err := json.NewDecoder(resp.Body).Decode(imageList); err != nil { + return "", err + } + if imageList == nil || len(imageList.Items) == 0 { + return "", errors.New("no images list in response") + } + + imageURL := "" + var max time.Time // latest stable image creation time + for _, v := range imageList.Items { + if !strings.HasPrefix(v.Name, "coreos-stable") { + continue + } + if v.CreationTimestamp.After(max) { + max = v.CreationTimestamp + imageURL = v.SelfLink + } + } + if imageURL == "" { + return "", errors.New("no stable coreOS image found") + } + return imageURL, nil +}