@@ -2,12 +2,14 @@ package fetch_token
22
33import (
44 "fmt"
5+ "os"
56
67 "github.com/aliyunidaas/alibaba-cloud-idaas/cloud"
78 "github.com/aliyunidaas/alibaba-cloud-idaas/cloud/alibaba_cloud"
89 "github.com/aliyunidaas/alibaba-cloud-idaas/cloud/aws"
910 "github.com/aliyunidaas/alibaba-cloud-idaas/cloud/oidc"
1011 "github.com/aliyunidaas/alibaba-cloud-idaas/utils"
12+ "github.com/pkg/errors"
1113 "github.com/urfave/cli/v2"
1214)
1315
2628 Name : "oidc-field" ,
2729 Usage : "Fetch OIDC filed (id_token or access_token)" ,
2830 }
31+ stringFlagOutput = & cli.StringFlag {
32+ Name : "output" ,
33+ Aliases : []string {"o" },
34+ Usage : "Output to file" ,
35+ }
2936 boolFlagForceNew = & cli.BoolFlag {
3037 Name : "force-new" ,
3138 Aliases : []string {"N" },
@@ -38,6 +45,7 @@ func BuildCommand() *cli.Command {
3845 stringFlagProfile ,
3946 stringFlagFormat ,
4047 stringFlagOidcField ,
48+ stringFlagOutput ,
4149 boolFlagForceNew ,
4250 }
4351 return & cli.Command {
@@ -48,14 +56,15 @@ func BuildCommand() *cli.Command {
4856 profile := context .String ("profile" )
4957 format := context .String ("format" )
5058 oidcField := context .String ("oidc-field" )
59+ output := context .String ("output" )
5160 forceNew := context .Bool ("force-new" )
5261
53- return fetchToken (profile , format , oidcField , forceNew )
62+ return fetchToken (profile , format , oidcField , output , forceNew )
5463 },
5564 }
5665}
5766
58- func fetchToken (profile , format , oidcField string , forceNew bool ) error {
67+ func fetchToken (profile , format , oidcField , output string , forceNew bool ) error {
5968 options := & cloud.FetchCloudStsOptions {
6069 ForceNew : forceNew ,
6170 }
@@ -92,10 +101,35 @@ func fetchToken(profile, format, oidcField string, forceNew bool) error {
92101 if stdOutputErr != nil {
93102 return stdOutputErr
94103 }
95- if printNewLine {
96- utils .Stdout .Println (stdOutput )
104+ if output == "" {
105+ if printNewLine {
106+ utils .Stdout .Println (stdOutput )
107+ } else {
108+ utils .Stdout .Print (stdOutput )
109+ }
97110 } else {
98- utils .Stdout .Print (stdOutput )
111+ // write to file output
112+ err := writeFilePreservePerm (output , []byte (stdOutput ), 0644 )
113+ if err != nil {
114+ return errors .Errorf ("Write to file: %s, error: %v" , output , err )
115+ }
99116 }
100117 return nil
101118}
119+
120+ func writeFilePreservePerm (filename string , data []byte , perm os.FileMode ) error {
121+ if _ , err := os .Stat (filename ); err == nil {
122+ f , err := os .OpenFile (filename , os .O_WRONLY | os .O_TRUNC , 0 )
123+ if err != nil {
124+ return err
125+ }
126+ defer f .Close ()
127+ _ , err = f .Write (data )
128+ return err
129+ } else if os .IsNotExist (err ) {
130+ return os .WriteFile (filename , data , perm )
131+ } else {
132+ // other error
133+ return err
134+ }
135+ }
0 commit comments