-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
194 lines (167 loc) · 5.15 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package main
import (
"bytes"
"flag"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"github.com/hashicorp/terraform/builtin/provisioners/file"
"github.com/hashicorp/terraform/config/module"
"github.com/hashicorp/terraform/terraform"
"github.com/terraform-providers/terraform-provider-aws/aws"
)
// Code is the Terraform code to execute
const Code = `
variable "count" { default = 2 }
variable "public_key_file" { default = "~/.ssh/id_rsa.pub" }
variable "private_key_file" { default = "~/.ssh/id_rsa" }
locals {
public_key = "${file(pathexpand(var.public_key_file))}"
private_key = "${file(pathexpand(var.private_key_file))}"
}
provider "aws" {
region = "us-west-2"
}
resource "aws_instance" "server" {
instance_type = "t2.micro"
ami = "ami-6e1a0117"
count = "${var.count}"
key_name = "server_key"
provisioner "file" {
content = "ami used: ${self.ami}"
destination = "/tmp/file.log"
connection {
user = "ubuntu"
private_key = "${local.private_key}"
}
}
}
resource "aws_key_pair" "keypair" {
key_name = "server_key"
public_key = "${local.public_key}"
}
`
var (
count int
pubKeyFile string
privKeyFile string
stateFile string
)
// Platform store all the information needed by Terraform
type Platform struct {
Code string
Vars map[string]interface{}
Providers map[string]terraform.ResourceProvider
Provisioners map[string]terraform.ResourceProvisioner
State *terraform.State
}
func main() {
flag.IntVar(&count, "count", 2, "number of instances to create. Set to '0' to terminate them all.")
flag.StringVar(&pubKeyFile, "pub", "", "public key file to create the AWS Key Pair")
flag.StringVar(&privKeyFile, "priv", "", "private key file to connect to the new AWS EC2 instances")
flag.StringVar(&stateFile, "state", "tf.state", "terraform state file destination")
flag.Parse()
var state bytes.Buffer
p := &Platform{
Code: Code,
Vars: map[string]interface{}{
"count": count,
},
}
if len(pubKeyFile) != 0 {
p.Vars["public_key_file"] = pubKeyFile
}
if len(privKeyFile) != 0 {
p.Vars["private_key_file"] = privKeyFile
}
// If the file exists, read the state from the state file
if _, errStat := os.Stat(stateFile); errStat == nil {
stateB, err := ioutil.ReadFile(stateFile)
if err != nil {
log.Fatalf("Fail to read the state from %q", stateFile)
}
state = *bytes.NewBuffer(stateB)
// Get the Terraform state from the state file content
if p.State, err = terraform.ReadState(&state); err != nil {
log.Fatalln(err)
}
}
// Create a temporal directory or use any directory
tfDir, err := ioutil.TempDir("", ".tf")
if err != nil {
log.Fatalln(err)
}
defer os.RemoveAll(tfDir)
// Save the code into a single or multiple files
filename := filepath.Join(tfDir, "main.tf")
configFile, err := os.Create(filename)
if err != nil {
log.Fatalln(err)
}
defer configFile.Close()
// Copy the Terraform template from p.Code into the new file
if _, err = io.Copy(configFile, strings.NewReader(p.Code)); err != nil {
log.Fatalln(err)
}
// Create the Terraform module
mod, err := module.NewTreeModule("", tfDir)
if err != nil {
log.Fatalln(err)
}
// Create the Storage pointing to where the Terraform code is
storageDir := filepath.Join(tfDir, "modules")
s := module.NewStorage(storageDir, nil)
s.Mode = module.GetModeNone // or module.GetModeGet
// Finally make the module load the
if err := mod.Load(s); err != nil {
log.Fatalf("Failed loading modules. %s", err)
}
// Optionally, you can validate the loaded code if it has some user input
if err := mod.Validate().Err(); err != nil {
log.Fatalf("Failed Terraform code validation. %s", err)
}
// Add Providers:
ctxProviders := make(map[string]terraform.ResourceProviderFactory)
// ctxProviders["null"] = terraform.ResourceProviderFactoryFixed(null.Provider())
ctxProviders["aws"] = terraform.ResourceProviderFactoryFixed(aws.Provider())
providerResolvers := terraform.ResourceProviderResolverFixed(ctxProviders)
// Add Provisioners:
provisionersFactory := make(map[string]terraform.ResourceProvisionerFactory)
provisionersFactory["file"] = func() (terraform.ResourceProvisioner, error) {
return file.Provisioner(), nil
}
destroy := (count == 0)
ctxOpts := terraform.ContextOpts{
Destroy: destroy,
State: p.State,
Variables: p.Vars,
Module: mod,
ProviderResolver: providerResolvers,
Provisioners: provisionersFactory,
}
ctx, err := terraform.NewContext(&ctxOpts)
if err != nil {
log.Fatalf("Failed creating context. %s", err)
}
if _, err := ctx.Refresh(); err != nil {
log.Fatalln(err)
}
if _, err := ctx.Plan(); err != nil {
log.Fatalln(err)
}
if _, err := ctx.Apply(); err != nil {
log.Fatalln(err)
}
// Retrieve the state from the Terraform context
p.State = ctx.State()
if err := terraform.WriteState(p.State, &state); err != nil {
log.Fatalf("Failed to retrieve the state. %s", err)
}
// Save the state to the local file 'tf.state'
if err = ioutil.WriteFile(stateFile, state.Bytes(), 0644); err != nil {
log.Fatalf("Fail to save the state to %q. %s", stateFile, err)
}
}