0

Following the example in AWS-CLI documentation I tried running an EC2 instance using AWS CLI but got the error

An error occurred (InvalidParameterCombination) when calling the RunInstances operation: The parameter groupName cannot be used with the parameter subnet

Instead of pulling each piece of information manually I thought it'd be easier to set them as environment variables then pass them onto docker run

export AMI_ID=ami-0b2ca94b5b49e0132
export KEY_NAME=$(aws ec2 describe-key-pairs --query 'KeyPairs[*].KeyName | [0]' --output text)
export SG_ID=$(aws ec2 describe-security-groups --filters Name=group-name,Values="my-sg" --query 'SecurityGroups[*].GroupId | [0]' --output text)
export SUBNET_ID=$(aws ec2 describe-subnets --query 'Subnets[*].SubnetId | [0]' --output text)
export VPC_ID=$(aws ec2 describe-vpcs --query 'Vpcs[*].VpcId | [0]' --output text)
docker run --rm -it -e AMI_ID -e KEY_NAME -e SG_ID -e SUBNET_ID -v ~/.aws:/root/.aws -v $(pwd):/aws amazon/aws-cli ec2 run-instances --image-id ${AMI_ID} --count 1 --instance-type t2.micro --key-name ${KEY_NAME} --security-group-ids ${SG_ID} --subnet-id ${SUBNET_ID}

Other posts I've found so far suggest that the problem is with using the --security-groups arguments instead of the --security-group-ids but I'm already using the latter so I'm stuck.

zenkavi
  • 41
  • 4

1 Answers1

0

I'm still not sure what the problem with the previous syntax was but when declaring the environment variables they are tagged on with additional characters like $'in the beginning and \C-M' in the end.

export AMI_ID=ami-0b2ca94b5b49e0132
export KEY_NAME=`aws ec2 describe-key-pairs | jq -j '.KeyPairs[0].KeyName'`
export SG_ID=`aws ec2 describe-security-groups --filters Name=group-name,Values="my-sg"  | jq -j '.SecurityGroups[0].GroupId'`
export SUBNET_ID=`aws ec2 describe-subnets | jq -j '.Subnets[0].SubnetId'`

Also the previous docker run was bloated because the environment variables are replaced by shell before docker run is executed and since they are not used again within the image they don't need to be passed on. So the shorter command would be

docker run --rm -it -v ~/.aws:/root/.aws -v $(pwd):/aws amazon/aws-cli ec2 run-instances --image-id $AMI_ID --count 1 --instance-type t2.micro --key-name $KEY_NAME --security-group-ids $SG_ID --subnet-id $SUBNET_ID

This worked for me.

zenkavi
  • 41
  • 4