Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boto3: Create a instance with an instanceprofile/ IAM Role

I want to write a script that starts servers for me and does the setup. It should:

  • Create two S3-Buckets and set its CORS (solved)
  • Create a ec2 server based on an image
  • give this server access to that bucket

What I have found so far is how to create the bucket and how to create the instance itself:

#@see http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#ec2

aws = boto3.Session(profile_name="myProfile")

s3 = aws.resource('s3', region_name='my-region-1')
bucket = s3.create_bucket(
    Bucket='my-cool-bucket', 
    #...
)
#...

ec2 = aws.resource('ec2', region_name='my-region-1')

ec2.create_instances(
     ImageId="my-ami-image-id",
     MinCount=1,  # I want exactly 1 server
     MaxCount=1,
     KeyName='my-ssh-key',
     SecurityGroupIds=['my-security-group'],
     UserData=myStartupScript, # script that will start when server starts
     InstanceType='t2.nano',
     SubnetId="my-subnet-id",
     DisableApiTermination=True,
     PrivateIpAddress='10.0.0.1',
     #...
)

but how do I now create the Role for that server and give that role access to the bucket?

like image 953
Tobi Avatar asked Oct 31 '16 18:10

Tobi


2 Answers

I have found the way to create the InstanceProfile:

https://boto3.readthedocs.io/en/latest/reference/services/iam.html#IAM.ServiceResource.create_instance_profile

instance_profile = iam.create_instance_profile(
    InstanceProfileName='string',
    Path='string'
)
like image 155
Tobi Avatar answered Oct 20 '22 17:10

Tobi


You will need to:

  • Create an InstanceProfile
  • Associate a Role to the Instance Profile
  • Launch the instance(s) with the IamInstanceProfile parameter
like image 45
John Rotenstein Avatar answered Oct 20 '22 18:10

John Rotenstein