Home » Posts tagged '#Tagging'
Tag Archives: #Tagging
Python3 AWS CLI script to create machines
Python3 script to create AWS VM using cli, the code reads the input from a file called “input.txt” with a different format, where each line contains the name of the value and the actual value separated by a tab:
import boto3
# Set your AWS profile and region
AWS_PROFILE = "your-profile"
AWS_REGION = "your-region"
# Read input from file
with open("input.txt", "r") as file:
lines = file.readlines()
# Extract instance details from input
INSTANCE_TYPE = ""
IMAGE_ID = ""
SUBNET_ID = ""
SECURITY_GROUP_ID = ""
KEY_NAME = ""
TAG_NAME = ""
TAG_ENVIRONMENT = ""
TAG_OWNER = ""
# Parse input lines
for line in lines:
name, value = line.strip().split("\t")
if name == "INSTANCE_TYPE":
INSTANCE_TYPE = value
elif name == "IMAGE_ID":
IMAGE_ID = value
elif name == "SUBNET_ID":
SUBNET_ID = value
elif name == "SECURITY_GROUP_ID":
SECURITY_GROUP_ID = value
elif name == "KEY_NAME":
KEY_NAME = value
elif name == "TAG_NAME":
TAG_NAME = value
elif name == "TAG_ENVIRONMENT":
TAG_ENVIRONMENT = value
elif name == "TAG_OWNER":
TAG_OWNER = value
# Create an EC2 resource using the specified profile and region
session = boto3.Session(profile_name=AWS_PROFILE, region_name=AWS_REGION)
ec2_resource = session.resource('ec2')
# Launch the EC2 instance
instance = ec2_resource.create_instances(
ImageId=IMAGE_ID,
InstanceType=INSTANCE_TYPE,
SubnetId=SUBNET_ID,
SecurityGroupIds=[SECURITY_GROUP_ID],
KeyName=KEY_NAME,
TagSpecifications=[
{
'ResourceType': 'instance',
'Tags': [
{'Key': 'Name', 'Value': TAG_NAME},
{'Key': 'Environment', 'Value': TAG_ENVIRONMENT},
{'Key': 'Owner', 'Value': TAG_OWNER}
]
}
]
)[0]
# Wait for the instance to be in the "running" state
instance.wait_until_running()
print(f"Instance {instance.id} launched successfully!")
the “input.txt” file, contains the name of the value and the actual value separated by a tab (\t), each line is parsed and the actual value to the corresponding variable based on the name is assigned.
an example of “input.txt” file structure is as below:
INSTANCE_TYPE t2.micro
IMAGE_ID ami-12345678
SUBNET_ID subnet-12345678
SECURITY_GROUP_ID sg-12345678
KEY_NAME your-key-pair-name
TAG_NAME MyInstance
TAG_ENVIRONMENT Production
TAG_OWNER John Doe