1

I wonder anyone can help me with making a shell script which automate aws cli process for:

1.Creating Security group

2.Set roles to this Security group port 22 and port 80

3.Create a ec2 instance with this security group.

I have something done,but it's not fully completed.

addSG=$ aws ec2 create-security-group --group-name plamenSG --description "Security group for SSH access" --vpc-id vpc-026278d069c2b6ffa addRuleSG_22p=$ aws ec2 authorize-security-group-ingress --group-id sg-0032ab410f260ce27 --protocol tcp --port 22 --cidr 87.116.78.97/32 addRuleSG_80p=$ aws ec2 authorize-security-group-ingress --group-id sg-0032ab410f260ce27 --protocol tcp --port 80 --cidr 0.0.0.0/0 runEC2=$ aws ec2 run-instances --image-id ami-0c3083e7f17ee7441 --count 1 --instance-type t2.micro \ --key-name MyKeyPair --subnet-id subnet-05499bb79299f5868 --security-group-ids sg-0032ab410f260ce27 \ --user-data file://my_script.txt 

As you understand from the code above we create the SG first it's usually the first step. The problem is that when i create Security group i got security group ID as output from the command and i need to replace old security group ID with the new one ID in the line code.

About this line code - --group-id sg-0032ab410f260ce27

I make a variable which get the output of the 1st command and put it instead of the ID it look something like that:

addRuleSG_80p=$ aws ec2 authorize-security-group-ingress --group-id sg-$var --protocol tcp --port 80 --cidr 0.0.0.0/0 

But i got the follow error: An error occurred (InvalidGroupId.Malformed) when calling the AuthorizeSecurityGroupIngress operation: The security-group ID 'sg-' is malformed

Any idea?

1 Answer 1

1

The default output format for awscli is json. So in you aws ec2 create-security-group command would yield an output something like:

{ "GroupId": "sg-903004f8" } 

What you could do is to parse that json with tool like jq.

MYSG=$(aws ec2 create-security-group --group-name plamenSG \ --description "Security group for SSH access" \ --vpc-id vpc-026278d069c2b6ffa | jq -r '.GroupId') 

Hope this helps.

1
  • The Answer are correct. Now it's working fine. Thanks for the help it's really help me. Commented Aug 5, 2022 at 6:41

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.