-
-
Save garnaat/2917662 to your computer and use it in GitHub Desktop.
In [1]: policy = """{ | |
...: "Statement":[{ | |
...: "Effect":"Allow", | |
...: "Action":["s3:*"], | |
...: "Resource":["arn:aws:s3:::mybucket"]}]}""" | |
In [2]: import boto | |
In [4]: c = boto.connect_iam() | |
In [5]: instance_profile = c.create_instance_profile('myinstanceprofile') | |
In [6]: role = c.create_role('myrole') | |
In [7]: c.add_role_to_instance_profile('myinstanceprofile', 'myrole') | |
Out[7]: {u'add_role_to_instance_profile_response': {u'response_metadata': {u'request_id': u'2221d92c-b437-11e1-86e5-c9c4f3b58653'}}} | |
In [8]: c.put_role_policy('myrole', 'mypolicy', policy) | |
Out[8]: {u'put_role_policy_response': {u'response_metadata': {u'request_id': u'2b878c93-b437-11e1-86e5-c9c4f3b58653'}}} | |
In [9]: c = boto.connect_ec2() | |
In [10]: c.run_instances('ami-e565ba8c', key_name='mykeyname', security_groups=['mysecuritygroup'], instance_type='t1.micro', instance_profile_name='myinstanceprofile') | |
Dido. This is a good snippet of code to show how to create an instance and apply the IAM role to it. Good job!
Thanks for the example. I always used console to create roles and was scratching my head on what an instance profile is. For anyone wondering the same thing -
http://docs.aws.amazon.com/IAM/latest/UserGuide/instance-profiles.html
I was recently playing with IAM and wrote a little test code to use dictionaries and lists, then the json.dumps() command to produce a valid policy string. It's pretty simple and a little nicer than string manipulation.
import json
if __name__ == "__main__":
policy = {}
policy['Version'] = '2011-04-01'
statements = []
# all access
statements.append({'Effect': 'Allow', 'Action': '*', 'Resource': '*'})
# define quota (a Eucalyptus thing)
statements.append({'Effect': 'Limit', 'Action': 'ec2:RunInstances', 'Resource': '*', 'Condition':{'NumericLessThanEquals':{'ec2:quota-vminstancenumber': '16'}}})
policy['Statement'] = statements
print json.dumps(policy, indent=2)
On the other side, you can use json.loads() to reverse the process when pulling a policy out of IAM.
Thanks for this , it still works :)
As this example is not compatible with boto3
, i wrote the equivalent with this newer boto version https://github.com/iMilnb/awstools/blob/master/platforms/roles/mkrole.py
This is great! Would love to see this snippet added to the boto IAM documentation.