Created
March 21, 2023 19:37
-
-
Save mikejk8s/0b559c75543490751f5f1f007c608b18 to your computer and use it in GitHub Desktop.
circleci gosed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"io/ioutil" | |
"net/http" | |
"os" | |
"strings" | |
) | |
func main() { | |
// Make a request to the CircleCI API | |
url := "https://circleci.com/api/v2/me" | |
req, err := http.NewRequest("GET", url, nil) | |
if err != nil { | |
panic(err) | |
} | |
req.Header.Set("Circle-Token", "token") #TODO: token | |
client := &http.Client{} | |
resp, err := client.Do(req) | |
if err != nil { | |
panic(err) | |
} | |
defer resp.Body.Close() | |
// Parse the response body | |
body, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
panic(err) | |
} | |
var data map[string]interface{} | |
err = json.Unmarshal(body, &data) | |
if err != nil { | |
panic(err) | |
} | |
// Read the contents vars file | |
varFileBytes, err := ioutil.ReadFile("prod.tfvars") | |
if err != nil { | |
panic(err) | |
} | |
varFileContents := string(varFileBytes) | |
// Replace the value of an existing element in the container_image_tag list variable | |
varName := "container_image_tag" | |
varNewValue := "new-tag" | |
if strings.Contains(varFileContents, varName) { | |
// List variable already exists in the file, replace its value | |
varList := strings.Split(varFileContents, "\n") | |
for i, line := range varList { | |
if strings.Contains(line, varName) { | |
// Find the position of the element in the list | |
listStr := strings.TrimSuffix(strings.TrimPrefix(line, "default = ["), "]") | |
list := strings.Split(listStr, ", ") | |
varIndex := -1 | |
for j, val := range list { | |
if strings.Trim(val, "\"") == varOldValue { | |
varIndex = j | |
break | |
} | |
} | |
if varIndex == -1 { | |
panic(fmt.Sprintf("element '%s' not found in list variable '%s'", varOldValue, varName)) | |
} | |
// Replace the value at the position | |
list[varIndex] = fmt.Sprintf("\"%s\"", varNewValue) | |
varList[i] = fmt.Sprintf("default = [%s]", strings.Join(list, ", ")) | |
break | |
} | |
} | |
varFileContents = strings.Join(varList, "\n") | |
} else { | |
// List variable doesn't exist in the file, add a new variable | |
varFileContents += fmt.Sprintf("variable \"%s\" { default = [\"%s\", \"latest\"] }\n", varName, varNewValue) | |
} | |
// Write the modified contents back to the variables file | |
err = ioutil.WriteFile("prod.tfvars", []byte(varFileContents), 0644) | |
if err != nil { | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment