Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boto3 ec2 create instance with a name

I am new to AWS and using boto3 to launch an instance. However, I notice that when I create the instance, the "Name" field is empty. So, the way I create it is as follows:

def create_instance(ami, instance_type, device_name, iam_role, volume_type,
                    volume_size,
                    security_groups, key_name, user_data):
    s = boto3.Session(region_name="eu-central-1")
    ec2 = s.resource('ec2')

    res = ec2.create_instances(
            IamInstanceProfile={'Name': iam_role},
            ImageId=ami,
            InstanceType=instance_type,
            SecurityGroupIds=security_groups,
            KeyName=key_name,
            UserData=user_data,
            MaxCount=1,
            MinCount=1,
            InstanceInitiatedShutdownBehavior='terminate',
            BlockDeviceMappings=[{
                'DeviceName': device_name,
                'Ebs': {
                    'DeleteOnTermination': True,
                    'VolumeSize': volume_size,
                    'VolumeType': volume_type
                }
            }]
        )
    instance = res[0]
    while instance.state['Name'] == 'pending':
        time.sleep(5)
        instance.load()

    return instance.public_ip_address, instance.public_dns_name

There does not seem to be a simple way to specify the name of the launched instance. How can one do this?

like image 944
Luca Avatar asked Jul 24 '26 08:07

Luca


1 Answers

Put a tag with key Name with your instance name as a value.

TagSpecifications=[
        {
            'ResourceType': 'instance',
            'Tags': [
                {
                    'Key': 'Name',
                    'Value': '<What you want>'
                },
            ]
        },
    ],
like image 74
Lamanus Avatar answered Jul 28 '26 15:07

Lamanus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!