Skip to content

Commit

Permalink
Merge pull request #501 from hazelops/IZE-669-ize-tunnel-up-ssh-push-…
Browse files Browse the repository at this point in the history
…public-metadata-is-optional

IZE-669 added `use-e2-metadata` flag
  • Loading branch information
psihachina authored Oct 17, 2022
2 parents 47fb2ae + 1a72763 commit 0696ebd
Showing 1 changed file with 34 additions and 3 deletions.
37 changes: 34 additions & 3 deletions internal/commands/tunnel_up.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ type TunnelUpOptions struct {
BastionHostID string
ForwardHost []string
StrictHostKeyChecking bool
Metadata bool
}

func NewTunnelUpFlags(project *config.Project) *TunnelUpOptions {
Expand Down Expand Up @@ -87,6 +88,7 @@ func NewCmdTunnelUp(project *config.Project) *cobra.Command {
cmd.Flags().StringVar(&o.PublicKeyFile, "ssh-public-key", "", "set ssh key public path")
cmd.Flags().StringVar(&o.PrivateKeyFile, "ssh-private-key", "", "set ssh key private path")
cmd.PersistentFlags().BoolVar(&o.StrictHostKeyChecking, "strict-host-key-checking", true, "set strict host key checking")
cmd.PersistentFlags().BoolVar(&o.Metadata, "use-ec2-metadata", false, "send ssh key to EC2 metadata (work only for Ubuntu versions > 20.0)")

return cmd
}
Expand Down Expand Up @@ -174,9 +176,16 @@ func (o *TunnelUpOptions) Run() error {
return fmt.Errorf("can't get public key: %s", err)
}

err = sendSSHPublicKey(o.BastionHostID, pk, o.Config.Session)
if err != nil {
return fmt.Errorf("can't run tunnel: %s", err)
if o.Metadata {
err = sendSSHPublicKey(o.BastionHostID, pk, o.Config.Session)
if err != nil {
return fmt.Errorf("can't run tunnel: %s", err)
}
} else {
err = sendSSHPublicKeyLegacy(o.BastionHostID, pk, o.Config.Session)
if err != nil {
return fmt.Errorf("can't run tunnel: %s", err)
}
}

forwardConfig, err := o.upTunnel()
Expand Down Expand Up @@ -297,6 +306,28 @@ func sendSSHPublicKey(bastionID string, key string, sess *session.Session) error
return nil
}

func sendSSHPublicKeyLegacy(bastionID string, key string, sess *session.Session) error {
// This command is executed in the bastion host and it checks if our public key is present. If it's not it uploads it to _authorized_keys file.
command := fmt.Sprintf(
`grep -qR "%s" /home/ubuntu/.ssh/authorized_keys || echo "%s" >> /home/ubuntu/.ssh/authorized_keys`,
key, key,
)

_, err := ssm.New(sess).SendCommand(&ssm.SendCommandInput{
InstanceIds: []*string{&bastionID},
DocumentName: aws.String("AWS-RunShellScript"),
Comment: aws.String("Add an SSH public key to authorized_keys"),
Parameters: map[string][]*string{
"commands": {&command},
},
})
if err != nil {
return fmt.Errorf("can't send SSH public key: %w", err)
}

return nil
}

func getPublicKey(path string) (string, error) {
if !filepath.IsAbs(path) {
var err error
Expand Down

0 comments on commit 0696ebd

Please sign in to comment.