Skip to content

Commit c3d4ebb

Browse files
committed
implement comment hinting
1 parent 226dd6f commit c3d4ebb

File tree

2 files changed

+19
-6
lines changed

2 files changed

+19
-6
lines changed

packages/core/src/awsService/ec2/model.ts

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ import { showMessageWithCancel } from '../../shared/utilities/messages'
2828
import { SshConfig } from '../../shared/sshConfig'
2929
import { SshKeyPair } from './sshKeyPair'
3030
import { Ec2SessionTracker } from './remoteSessionManager'
31-
import { getEc2SsmEnv } from './utils'
31+
import { getEc2SsmEnv, getRemoveLabeledEntriesCommand } from './utils'
3232

3333
export type Ec2ConnectErrorCode = 'EC2SSMStatus' | 'EC2SSMPermission' | 'EC2SSMConnect' | 'EC2SSMAgentStatus'
3434

@@ -265,13 +265,17 @@ export class Ec2Connecter implements vscode.Disposable {
265265
remoteUser: string
266266
): Promise<void> {
267267
const sshPubKey = await sshKeyPair.getPublicKey()
268+
const hintComment = '# Added by AWS Toolkit for VSCode'
268269

269-
const remoteAuthorizedKeysPaths = `/home/${remoteUser}/.ssh/authorized_keys`
270-
const command = `echo "${sshPubKey}" > ${remoteAuthorizedKeysPaths}`
271-
const documentName = 'AWS-RunShellScript'
270+
const remoteAuthorizedKeysPath = `/home/${remoteUser}/.ssh/authorized_keys`
271+
const deleteExistingKeyCommand = getRemoveLabeledEntriesCommand(hintComment, remoteAuthorizedKeysPath)
272272

273-
await this.ssmClient.sendCommandAndWait(selection.instanceId, documentName, {
274-
commands: [command],
273+
const appendStr = (s: string) => `echo "${s}" >> ${remoteAuthorizedKeysPath}`
274+
const writeCommentCommand = appendStr(hintComment)
275+
const writeKeyCommand = appendStr(sshPubKey)
276+
277+
await this.ssmClient.sendCommandAndWait(selection.instanceId, 'AWS-RunShellScript', {
278+
commands: [deleteExistingKeyCommand, writeCommentCommand, writeKeyCommand],
275279
})
276280
}
277281

packages/core/src/awsService/ec2/utils.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,3 +46,12 @@ export function getEc2SsmEnv(
4646
process.env
4747
)
4848
}
49+
/**
50+
* Generate bash command (as string) to remove lines in file prefixed by `hintComment`.
51+
* @param hintComment prefix comment for deleted lines.
52+
* @param filepath filepath (as string) to target with the command.
53+
* @returns bash command to remove lines from file.
54+
*/
55+
export function getRemoveLabeledEntriesCommand(hintComment: string, filepath: string): string {
56+
return `sed -i '' '/${hintComment}/N; /${hintComment}/ {N; d}' ${filepath}`
57+
}

0 commit comments

Comments
 (0)