AWS EC2 - check if Key-Pair and Security Group doesn't already exist

544 views Asked by At

I am currently developing a application that builds instances on AWS via the api for php.

Im having issue working out the best method to check to see if the Key Pair and security group exists before creating another one.

$CreateKeyPair = $ec2Client->createKeyPair(array('KeyName' => $InstanceName));          

$ec2Client->createSecurityGroup(array('GroupName' => $InstanceName,'Description' => $InstanceName));    

the above creates the key-pair and the security group however i would like to check if the key-pair exists if it does stop executing and basically the same concept with security group however if the key-pair gets created but the security group fails for some reason then rollback the changes and delete the key-pair that was created.

I know api has the ability to create and delete security groups and key-pairs but no ability to check if it exists first from what i can see.

Has anyone done this before or would anyone have a method how this could be accomplished.

I am completely new to the AWS api.

1

There are 1 answers

1
John Rotenstein On

Call DescribeKeyPairs and DescribeSecurityGroups to check for their existence, then only create them if they do not already exist.

You can either ask for a list of all KeyPairs/Security Groups, or provide a name to return specific ones.