0
votes

I have a cloudformation template to create an ec2-instance. That template also starts an httpd along with some content that is served.

I'm using the Parameter section to allow a key to be specified or selected - see snippet below:

Parameters:
  paramKeyPair:
    Description: KeyPairName
    Type: AWS::EC2::KeyPair::KeyName

I'm calling the ec2-instance through the AWS CLI like this :

aws cloudformation create-stack --stack-name stack-ec2instance --template-body file://demo-ec2instance --parameters ParameterKey=paramKeyPair,ParameterValue=peterKeyPair

So the instance can be created and the keypair can be passed through as an argument - BUT - frankly I don't actually care that much if the instance can be access. It's just a web server that can be spun up or down. SSH access is nice but no big deal.

In fact, if I removed the keypair Parameter from the cloudformation template - and removed the associated reference in the AWS CLI call - Cloudformation will happily spin up the instance without a keypair. Great !

What I would really like is for cloudformation to deal with the keypair being present or not. I thought the best way to do this would be to update the code so that the parameter has a default value of "None" (for example) and then the ec2-instance could be run from the AWS CLI and if the keypair parameter is not specified then AWS would know not to bother with the keypair at all.

The problem is that by specifying the Type as AWS::EC2::KeyPair::KeyName, the AWS CLI expects an actual value.

I'm out of ideas - if anyone else has figured this out - I would really appreciate it. Thankyou Peter.

1

1 Answers

0
votes

If I understand you correctly you want to be able to keep the parameter in your Cloudformation template, but only "allocate" a key pair to an instance if you specify a value, otherwise don't allocate a key pair to the ec2 instance resource. You can do this with AWS::NoValue pseudo parameter.

Here is a sample template:


Description: My EC2 instance

Parameters:
  SSHKeyName:
    Type: AWS::EC2::KeyPair::KeyName

Conditions:

  Has-EC2-Key:
    !Not [ !Equals [ !Ref SSHKeyName, '' ] ]

Resources:

  Instance:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: <InstanceImageID>
      InstanceType: t2.micro
      KeyName: !Ref SSHKeyName
      KeyName:
        Fn::If:
        - Has-EC2-Key
        - Ref: SSHKeyName
        - Ref: AWS::NoValue
      <other properties as required

So what this does is the condition checks if a SSHKeyName value is blank, if it's blank then the KeyName property will be ignored, if it isn't blank then it will use the value of SSHKeyName.