followed the Anton's answer and its works fine. written shell script which is launching a cloudformation template and if key is not preset ,script willl create it and will upload it to the s3 bucket.
#!/bin/bash
Region=eu-central-1
key=myapp-engine-$Region
Available_key=`aws ec2 describe-key-pairs --key-name $key | grep KeyName | awk -F\" '{print $4}'`
if [ "$key" = "$Available_key" ]; then
echo "Key is available."
else
echo "Key is not available: Creating new key"
aws ec2 create-key-pair --key-name $key --region $Region > myapp-engine-$Region.pem
aws s3 cp myapp-engine-$Region.pem s3://mybucket/myapp-engine-$Region.pem
fi
##### create stack #########
/usr/local/bin/aws cloudformation deploy --stack-name myapp-engine --template-file ./lc.yml --parameter-overrides file://./config.json --region $Region
Below is an example of a CloudFormation launch configuration stack where you can pass the key.
Resources:
renderEnginelc:
Type: AWS::AutoScaling::LaunchConfiguration
Properties:
ImageId:
Ref: "AMIID"
SecurityGroups:
- Fn::ImportValue:
!Sub "${SGStackName}-myapp"
InstanceType:
Ref: InstanceType
LaunchConfigurationName : !Join [ "-", [ !Ref Environment, !Ref ApplicationName, lc ] ]
KeyName: !Join [ "-", [ !Ref KeyName, !Ref AWS::Region ] ]
Passing a paramter value of KeyName is "myapp-engine" and it will consider a region according to AWS::Region