From 0ef1c728e156483805f0d1573bb99aadf3755706 Mon Sep 17 00:00:00 2001 From: Florian Bertholin Date: Fri, 6 Apr 2018 13:37:39 +0200 Subject: [PATCH] Add .netrc support --- main.go | 20 ++++++++++++++++++++ plugin.go | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) diff --git a/main.go b/main.go index 65bc527..fac697c 100644 --- a/main.go +++ b/main.go @@ -53,6 +53,21 @@ func main() { Usage: "whether or not to suppress terraform commands to stdout", EnvVar: "PLUGIN_SENSITIVE", }, + cli.StringFlag{ + Name: "netrc.machine", + Usage: "netrc machine", + EnvVar: "DRONE_NETRC_MACHINE", + }, + cli.StringFlag{ + Name: "netrc.username", + Usage: "netrc username", + EnvVar: "DRONE_NETRC_USERNAME", + }, + cli.StringFlag{ + Name: "netrc.password", + Usage: "netrc password", + EnvVar: "DRONE_NETRC_PASSWORD", + }, cli.StringFlag{ Name: "role_arn_to_assume", Usage: "A role to assume before running the terraform commands", @@ -142,6 +157,11 @@ func run(c *cli.Context) error { VarFiles: c.StringSlice("var_files"), Destroy: c.Bool("destroy"), }, + Netrc: Netrc{ + Login: c.String("netrc.username"), + Machine: c.String("netrc.machine"), + Password: c.String("netrc.password"), + }, Terraform: Terraform{ Version: c.String("tf.version"), }, diff --git a/plugin.go b/plugin.go index 81c4d08..899526d 100644 --- a/plugin.go +++ b/plugin.go @@ -5,6 +5,8 @@ import ( "io/ioutil" "os" "os/exec" + "os/user" + "path/filepath" "regexp" "strings" "time" @@ -33,6 +35,12 @@ type ( Destroy bool } + Netrc struct { + Machine string + Login string + Password string + } + // InitOptions include options for the Terraform's init command InitOptions struct { BackendConfig []string `json:"backend-config"` @@ -43,6 +51,7 @@ type ( // Plugin represents the plugin instance to be executed Plugin struct { Config Config + Netrc Netrc Terraform Terraform } ) @@ -62,6 +71,12 @@ func (p Plugin) Exec() error { assumeRole(p.Config.RoleARN) } + // writing the .netrc file with Github credentials in it. + err := writeNetrc(p.Netrc.Machine, p.Netrc.Login, p.Netrc.Password) + if err != nil { + return err + } + var commands []*exec.Cmd commands = append(commands, exec.Command("terraform", "version")) @@ -303,3 +318,32 @@ func assumeRole(roleArn string) { func trace(cmd *exec.Cmd) { fmt.Println("$", strings.Join(cmd.Args, " ")) } + +// helper function to write a netrc file. +// The following code comes from the official Git plugin for Drone: +// https://github.com/drone-plugins/drone-git/blob/8386effd2fe8c8695cf979427f8e1762bd805192/utils.go#L43-L68 +func writeNetrc(machine, login, password string) error { + if machine == "" { + return nil + } + out := fmt.Sprintf( + netrcFile, + machine, + login, + password, + ) + + home := "/root" + u, err := user.Current() + if err == nil { + home = u.HomeDir + } + path := filepath.Join(home, ".netrc") + return ioutil.WriteFile(path, []byte(out), 0600) +} + +const netrcFile = ` +machine %s +login %s +password %s +`