This repository has been archived by the owner on Dec 11, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 92
/
provider.go
266 lines (230 loc) · 8.62 KB
/
provider.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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
package docker
import (
"context"
"fmt"
"io"
"log"
"os"
"os/user"
"strings"
"github.com/docker/cli/cli/config/configfile"
"github.com/docker/docker/api/types"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/terraform"
)
// Provider creates the Docker provider
func Provider() terraform.ResourceProvider {
return &schema.Provider{
Schema: map[string]*schema.Schema{
"host": {
Type: schema.TypeString,
Required: true,
DefaultFunc: schema.EnvDefaultFunc("DOCKER_HOST", "unix:///var/run/docker.sock"),
Description: "The Docker daemon address",
},
"ca_material": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("DOCKER_CA_MATERIAL", ""),
Description: "PEM-encoded content of Docker host CA certificate",
},
"cert_material": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("DOCKER_CERT_MATERIAL", ""),
Description: "PEM-encoded content of Docker client certificate",
},
"key_material": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("DOCKER_KEY_MATERIAL", ""),
Description: "PEM-encoded content of Docker client private key",
},
"cert_path": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("DOCKER_CERT_PATH", ""),
Description: "Path to directory with Docker TLS config",
},
"registry_auth": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"address": {
Type: schema.TypeString,
Required: true,
Description: "Address of the registry",
},
"username": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"registry_auth.config_file", "registry_auth.config_file_content"},
DefaultFunc: schema.EnvDefaultFunc("DOCKER_REGISTRY_USER", ""),
Description: "Username for the registry",
},
"password": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
ConflictsWith: []string{"registry_auth.config_file", "registry_auth.config_file_content"},
DefaultFunc: schema.EnvDefaultFunc("DOCKER_REGISTRY_PASS", ""),
Description: "Password for the registry",
},
"config_file": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"registry_auth.username", "registry_auth.password", "registry_auth.config_file_content"},
DefaultFunc: schema.EnvDefaultFunc("DOCKER_CONFIG", "~/.docker/config.json"),
Description: "Path to docker json file for registry auth",
},
"config_file_content": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"registry_auth.username", "registry_auth.password", "registry_auth.config_file"},
Description: "Plain content of the docker json file for registry auth",
},
},
},
},
},
ResourcesMap: map[string]*schema.Resource{
"docker_container": resourceDockerContainer(),
"docker_image": resourceDockerImage(),
"docker_registry_image": resourceDockerRegistryImage(),
"docker_network": resourceDockerNetwork(),
"docker_volume": resourceDockerVolume(),
"docker_config": resourceDockerConfig(),
"docker_secret": resourceDockerSecret(),
"docker_service": resourceDockerService(),
},
DataSourcesMap: map[string]*schema.Resource{
"docker_registry_image": dataSourceDockerRegistryImage(),
"docker_network": dataSourceDockerNetwork(),
},
ConfigureFunc: providerConfigure,
}
}
func providerConfigure(d *schema.ResourceData) (interface{}, error) {
config := Config{
Host: d.Get("host").(string),
Ca: d.Get("ca_material").(string),
Cert: d.Get("cert_material").(string),
Key: d.Get("key_material").(string),
CertPath: d.Get("cert_path").(string),
}
client, err := config.NewClient()
if err != nil {
return nil, fmt.Errorf("Error initializing Docker client: %s", err)
}
ctx := context.Background()
_, err = client.Ping(ctx)
if err != nil {
return nil, fmt.Errorf("Error pinging Docker server: %s", err)
}
authConfigs := &AuthConfigs{}
if v, ok := d.GetOk("registry_auth"); ok { // TODO load them anyway
authConfigs, err = providerSetToRegistryAuth(v.(*schema.Set))
if err != nil {
return nil, fmt.Errorf("Error loading registry auth config: %s", err)
}
}
providerConfig := ProviderConfig{
DockerClient: client,
AuthConfigs: authConfigs,
}
return &providerConfig, nil
}
// AuthConfigs represents authentication options to use for the
// PushImage method accommodating the new X-Registry-Config header
type AuthConfigs struct {
Configs map[string]types.AuthConfig `json:"configs"`
}
// Take the given registry_auth schemas and return a map of registry auth configurations
func providerSetToRegistryAuth(authSet *schema.Set) (*AuthConfigs, error) {
authConfigs := AuthConfigs{
Configs: make(map[string]types.AuthConfig),
}
for _, authInt := range authSet.List() {
auth := authInt.(map[string]interface{})
authConfig := types.AuthConfig{}
authConfig.ServerAddress = normalizeRegistryAddress(auth["address"].(string))
registryHostname := convertToHostname(authConfig.ServerAddress)
// For each registry_auth block, generate an AuthConfiguration using either
// username/password or the given config file
if username, ok := auth["username"]; ok && username.(string) != "" {
log.Println("[DEBUG] Using username for registry auths:", username)
authConfig.Username = auth["username"].(string)
authConfig.Password = auth["password"].(string)
// Note: check for config_file_content first because config_file has a default which would be used
// nevertheless config_file_content is set or not. The default has to be kept to check for the
// environment variable and to be backwards compatible
} else if configFileContent, ok := auth["config_file_content"]; ok && configFileContent.(string) != "" {
log.Println("[DEBUG] Parsing file content for registry auths:", configFileContent.(string))
r := strings.NewReader(configFileContent.(string))
c, err := loadConfigFile(r)
if err != nil {
return nil, fmt.Errorf("Error parsing docker registry config json: %v", err)
}
authFileConfig, err := c.GetAuthConfig(registryHostname)
if err != nil {
return nil, fmt.Errorf("Couldn't find registry config for '%s' in file content", registryHostname)
}
authConfig.Username = authFileConfig.Username
authConfig.Password = authFileConfig.Password
// As last step we check if a config file path is given
} else if configFile, ok := auth["config_file"]; ok && configFile.(string) != "" {
filePath := configFile.(string)
log.Println("[DEBUG] Parsing file for registry auths:", filePath)
// We manually expand the path and do not use the 'pathexpand' interpolation function
// because in the default of this varable we refer to '~/.docker/config.json'
if strings.HasPrefix(filePath, "~/") {
usr, err := user.Current()
if err != nil {
return nil, err
}
filePath = strings.Replace(filePath, "~", usr.HomeDir, 1)
}
r, err := os.Open(filePath)
if err != nil {
continue
}
c, err := loadConfigFile(r)
if err != nil {
continue
}
authFileConfig, err := c.GetAuthConfig(registryHostname)
if err != nil {
continue
}
authConfig.Username = authFileConfig.Username
authConfig.Password = authFileConfig.Password
}
authConfigs.Configs[authConfig.ServerAddress] = authConfig
}
return &authConfigs, nil
}
func loadConfigFile(configData io.Reader) (*configfile.ConfigFile, error) {
configFile := configfile.New("")
if err := configFile.LoadFromReader(configData); err != nil {
log.Println("[DEBUG] Error parsing registry config: ", err)
log.Println("[DEBUG] Will try parsing from legacy format")
if err := configFile.LegacyLoadFromReader(configData); err != nil {
return nil, err
}
}
return configFile, nil
}
// ConvertToHostname converts a registry url which has http|https prepended
// to just an hostname.
// Copied from github.com/docker/docker/registry.ConvertToHostname to reduce dependencies.
func convertToHostname(url string) string {
stripped := url
if strings.HasPrefix(url, "http://") {
stripped = strings.TrimPrefix(url, "http://")
} else if strings.HasPrefix(url, "https://") {
stripped = strings.TrimPrefix(url, "https://")
}
nameParts := strings.SplitN(stripped, "/", 2)
return nameParts[0]
}