|
| 1 | +package provider |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/base64" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "net" |
| 8 | + "strings" |
| 9 | + "time" |
| 10 | + |
| 11 | + "golang.org/x/crypto/ssh" |
| 12 | + |
| 13 | + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" |
| 14 | +) |
| 15 | + |
| 16 | +func dataSourceSshKeyScan() *schema.Resource { |
| 17 | + return &schema.Resource{ |
| 18 | + Read: dataSourceSshKeyScanRead, |
| 19 | + Schema: map[string]*schema.Schema{ |
| 20 | + "host": { |
| 21 | + Type: schema.TypeString, |
| 22 | + Required: true, |
| 23 | + Description: "Host to ssh key scan.", |
| 24 | + }, |
| 25 | + "port": { |
| 26 | + Type: schema.TypeInt, |
| 27 | + Optional: true, |
| 28 | + Default: 22, |
| 29 | + Description: "Port to key scan", |
| 30 | + }, |
| 31 | + "public_host_key": { |
| 32 | + Type: schema.TypeString, |
| 33 | + Computed: true, |
| 34 | + Description: "Result of ssh key scan.", |
| 35 | + }, |
| 36 | + }, |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +func dataSourceSshKeyScanRead(d *schema.ResourceData, meta interface{}) error { |
| 41 | + host := d.Get("host").(string) |
| 42 | + port := d.Get("port").(int) |
| 43 | + |
| 44 | + hostKeyCh := make(chan string, 1) |
| 45 | + hostKeyError := errors.New("ignoring host key verification") |
| 46 | + hostKeyCallback := func(hostname string, remote net.Addr, key ssh.PublicKey) error { |
| 47 | + keyStr := base64.StdEncoding.EncodeToString([]byte(key.Marshal())) |
| 48 | + hostKeyCh <- fmt.Sprintf("%s %s", key.Type(), keyStr) |
| 49 | + return hostKeyError |
| 50 | + } |
| 51 | + |
| 52 | + config := &ssh.ClientConfig{ |
| 53 | + HostKeyCallback: hostKeyCallback, |
| 54 | + Timeout: 5 * time.Second, |
| 55 | + } |
| 56 | + client, err := ssh.Dial("tcp", fmt.Sprintf("%s:%v", host, port), config) |
| 57 | + if err != nil && !strings.Contains(err.Error(), hostKeyError.Error()) { |
| 58 | + return err |
| 59 | + } |
| 60 | + |
| 61 | + // Authentication errors will cause client to be nil |
| 62 | + if client != nil { |
| 63 | + client.Close() |
| 64 | + } |
| 65 | + hostKey := <-hostKeyCh |
| 66 | + |
| 67 | + d.Set("public_host_key", fmt.Sprintf("%s %s", host, hostKey)) |
| 68 | + d.SetId(time.Now().UTC().String()) |
| 69 | + |
| 70 | + return nil |
| 71 | +} |
0 commit comments