-
Notifications
You must be signed in to change notification settings - Fork 0
/
key.go
58 lines (53 loc) · 1.42 KB
/
key.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
package ssos
import (
"bytes"
"context"
"io/ioutil"
"text/template"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/ssm"
)
var AddKeyCommandTmpl = `u=$(getent passwd {{.user}}) && x=$(echo $u |cut -d: -f6) || exit 1
install -d -m700 -o{{.user}} ${x}/.ssh; grep '{{.publicKey}}' ${x}/.ssh/authorized_keys > /dev/null 2>/dev/null && exit 0
echo '{{.publicKey}}'| tee -a ${x}/.ssh/authorized_keys
`
func AddKey(ssmCli *ssm.Client, instanceIds []string, user string, publicKeyPath string) error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
bs, err := ioutil.ReadFile(publicKeyPath)
if err != nil {
return err
}
publicKey := string(bs)
t, err := template.New("test").Parse(AddKeyCommandTmpl)
if err != nil {
return err
}
var b bytes.Buffer
err = t.Execute(&b, map[string]string{
"user": user,
"publicKey": publicKey,
})
if err != nil {
return err
}
req := ssmCli.SendCommandRequest(&ssm.SendCommandInput{
InstanceIds: instanceIds,
DocumentName: aws.String("AWS-RunShellScript"),
Comment: aws.String("create user"),
Parameters: map[string][]string{
"commands": {b.String()},
},
})
res, err := req.Send(ctx)
if err != nil {
return err
}
commandID := res.Command.CommandId
err = WaitCommandInvocations(ctx, ssmCli, commandID)
if err != nil {
return err
}
return PrintCommandOutput(ctx, ssmCli, commandID)
}