AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: Lambda function to rotate SSH keys Parameters: MasterWorkersStack: Description: CloudFormation Stack Name for Master and Workers Type: String Default: MasterWorkers MinLength: 1 MaxLength: 255 AllowedPattern: "^[a-zA-Z][-a-zA-Z0-9]*$" Username: Description: Username for the Linux user that is used to log into the Workers Type: String Default: ec2-user MinLength: 1 MaxLength: 32 # Regex for valid unix usernames from: # https://unix.stackexchange.com/questions/157426/what-is-the-regex-to-validate-linux-users AllowedPattern: "^[a-z_]([a-z0-9_-]{0,31}|[a-z0-9_-]{0,30}\\$)$" TagName: Description: Tag Name to locate Worker EC2 Instances to update with SSH Public Keys Type: String Default: "RotateSSHKeys" MinLength: 1 MaxLength: 255 AllowedPattern: "^[a-zA-Z][-a-zA-Z0-9]*$" TagValue: Description: Tag Value to locate Worker EC2 Instances to update with SSH Public Keys Type: String Default: "True" MinLength: 1 MaxLength: 255 Resources: RotateSSH: Type: AWS::Serverless::Function Properties: Handler: rotate.lambda_handler Runtime: python3.9 CodeUri: lambda/ FunctionName: RotateSSH Description: Rotates SSH Keys MemorySize: 1536 Timeout: 300 Policies: - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole - arn:aws:iam::aws:policy/service-role/AWSLambdaENIManagementAccess - Version: '2012-10-17' Statement: - Sid: SecretsManagerActions Effect: Allow Action: - secretsmanager:DescribeSecret - secretsmanager:GetSecretValue - secretsmanager:PutSecretValue - secretsmanager:UpdateSecretVersionStage Resource: !Sub 'arn:aws:secretsmanager:${AWS::Region}:${AWS::AccountId}:secret:/dev/ssh*' Condition: StringEquals: secretsmanager:resource/AllowRotationLambdaArn: !Sub 'arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:RotateSSH' - Sid: SSMRunShellScriptDocument Effect: Allow Action: - ssm:SendCommand Resource: - !Sub 'arn:aws:ssm:${AWS::Region}::document/AWS-RunShellScript' - Sid: SSMRunShellScriptOnTaggedInstances Effect: Allow Action: - ssm:SendCommand Resource: - !Sub 'arn:aws:ec2:${AWS::Region}:${AWS::AccountId}:instance/*' Condition: StringEquals: ssm:resourceTag/RotateSSHKeys: !Ref TagValue - Sid: SSMTrackCommands Effect: Allow Action: - ssm:ListCommandInvocations - ssm:GetCommandInvocation - ssm:ListCommands - ssm:DescribeInstanceInformation Resource: '*' - Sid: EC2DescribeInstances Effect: Allow Action: - ec2:DescribeInstances Resource: '*' Environment: Variables: USERNAME: !Ref Username TAGNAME: !Ref TagName TAGVALUE: !Ref TagValue VpcConfig: SubnetIds: - Fn::ImportValue: !Sub '${MasterWorkersStack}-PrivateSubnet' SecurityGroupIds: - Fn::ImportValue: !Sub '${MasterWorkersStack}-MasterSecurityGroup' InvokePermission: Type: AWS::Lambda::Permission Properties: Action: lambda:InvokeFunction FunctionName: !Ref RotateSSH Principal: secretsmanager.amazonaws.com