Reputation: 1
I am new to Boto3
, and wanted to create a VPC, subnets, and some ec2 instances. The basic architecture is having a VPC, 2 subnets within 2 different availability zones (us-east-1a and b), and applying a security group which allows SSH
and ping
.
My problem is how to specify additional options for each resources. The Python SDK (unlike how Javadoc
works) doesn't show the required arguments and example options, so I'm confused.
How can I specify tags
for resources? (e.g. ec2 instance). I need to set name
, owner
, etc.
instances2 = ec2.create_instances(ImageId='ami-095575c1a372d21db', InstanceType='t2.micro', MaxCount=1, MinCount=1, NetworkInterfaces=[{'SubnetId': subnet2.id, 'DeviceIndex': 0, 'AssociatePublicIpAddress': True, 'Groups': [sec_group.group_id]}])
instances2[0].wait_until_running()
print(instances1[0].id)
Upvotes: 3
Views: 5585
Reputation: 936
Following works for me with python 3.7 and boto3 1.12.39
AMI = os.environ['AMI']
INSTANCE_TYPE = os.environ['INSTANCE_TYPE']
KEY_NAME = os.environ['KEY_NAME']
SUBNET_ID = os.environ['SUBNET_ID']
TAG_SPEC = [
{
"ResourceType":"instance",
"Tags": [
{
"Key": "Name",
"Value": "EC2_INSTANCE_TEST_AUTOGENERATED"
}
]
}
]
ec2 = boto3.resource('ec2')
instance = ec2.create_instances(
ImageId = AMI,
InstanceType = INSTANCE_TYPE,
KeyName = KEY_NAME,
SubnetId = SUBNET_ID,
TagSpecifications = TAG_SPEC,
MaxCount = 1,
MinCount = 1
)
Upvotes: 3
Reputation: 717
You need the TagSpecifications
argument with 'ResourceType'
set to 'instance'
:
TagSpecifications=[
{
'ResourceType': 'instance',
'Tags': [
{
'Key': 'name',
'Value': 'foobar'
},
{
'Key': 'owner',
'Value': 'me'
},
]
},
],
It is in the docs but you do need to know what you're looking for...
Upvotes: 3