简体   繁体   中英

Error when trying to add a Security group to an EC2 Instance

sg = ec2.create_security_group(GroupName='MyWebServer', Description = 'WebServer', VpcId='vpc-0dea879f34afff60d')

instance = ec2.create_instances(
 ImageId='ami-0fc970315c2d38f01',
 MinCount=1,
 MaxCount=1,
 InstanceType='t2.nano',
 SecurityGroups=[ sg.group_id ] 
)

I'm trying to create an instance and attach a security group to it, It's giving me an error when I run this code of ''(InvalidParameterValue) when calling the RunInstances operation: Value () parameter groupId is invalid. The value cannot be empty."

It creates the security group but doesn't create the instance when called. Any solutions or help would be appreciated.

We can access group Id with sg['GroupId']

import boto3

ec2 = boto3.client('ec2', region_name='us-east-1')
sg = ec2.create_security_group(GroupName='MyWebServer', Description = 'WebServer', VpcId='vpc-0dea879f34afff60d')

response = ec2.run_instances(
    ImageId='ami-0fc970315c2d38f01',
    InstanceType='t2.micro',
    MaxCount=1,
    MinCount=1,
    SecurityGroupIds=[
       sg['GroupId']
    ],
)

Try this:

instance = ec2.create_instances(
 ImageId='ami-0fc970315c2d38f01',
 MinCount=1,
 MaxCount=1,
 InstanceType='t2.nano',
 SecurityGroupIds=[ sg.group_id ] 
)
   // BELOW CODE WILL CREATE AWS INSTANCE AND LINK IT WITH SECURITY GROUP
   // PROVIDER MENTIONING THE REGION AND THE ACCESS KEY FOR THE CLOUD
      provider "aws" {
        # Configuration options
        region= "us-east-2"
        access_key= "XXXX"
        secret_key= "XXXXXX"
      }
      // CREATING THE AMI INSTANCE AND ASSOCIATING TO THE SECURITY GROUP
      resource "aws_instance" "base" {
        ami = "ami-0277b52859bac6f4b"
        instance_type = "t2.micro"
        associate_public_ip_address = true
        key_name = "Linux"  // ASSOCIATING THE EXISTING LOGIN KEY PAIR NAME
        tags = {
            Name="terraform"  
        }
        //ASSOCIATING THE EXISTING SECURITY GROUP TO THE INSTANCE
        vpc_security_group_ids  = [ aws_security_group.customSecGrp.id ] 
      }

// CREATING A SECURITY WITH INBOUND AND OUTBOUND PORTS
resource "aws_security_group" "customSecGrp" {  
name = "customSecGrp"
description = "Security group allowing Inbound"

  tags = {
    Name = "customSecGrp"
  } 

ingress {
description = "SSL TLS from VPC" 
from_port = 443
to_port = 443 
protocol    = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
  cidr_blocks = [ "0.0.0.0/0" ]
  description = "tomcat port from vpc"
  from_port = 8080
  protocol = "tcp"
  self = false
  to_port = 8080
} 
  egress { 
  from_port = 0
  to_port   = 0
  protocol  = "-1" 
  cidr_blocks = ["0.0.0.0/0"]
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM