boto3:使用 instanceprofile/ IAM 角色创建实例
boto3: Create a instance with an instanceprofile/ IAM Role
我想编写一个脚本来为我启动服务器并进行设置。它应该:
- 创建两个 S3-Buckets 并设置其 CORS(已解决)
- 基于镜像创建 ec2 服务器
- 授予此服务器访问该存储桶的权限
到目前为止我发现的是如何创建存储桶以及如何创建实例本身:
#@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',
#...
)
但我现在如何为该服务器创建角色并授予该角色访问存储桶的权限?
您将需要:
- 创建 InstanceProfile
- 将角色关联到实例配置文件
- 使用
IamInstanceProfile
参数启动实例
我找到了创建 InstanceProfile 的方法:
instance_profile = iam.create_instance_profile(
InstanceProfileName='string',
Path='string'
)
创建一个名为Test-emr-instance-role的角色,然后您可以使用此代码创建实例配置文件并将角色附加到实例配置文件。
session = boto3.session.Session(profile_name='myProfile')
iam = session.client('iam')
instance_profile = iam.create_instance_profile (
InstanceProfileName ='Test-emr-instance-profile'
)
response = iam.add_role_to_instance_profile (
InstanceProfileName = 'Test-emr-instance-profile',
RoleName = 'Test-emr-instance-role'
)
我想编写一个脚本来为我启动服务器并进行设置。它应该:
- 创建两个 S3-Buckets 并设置其 CORS(已解决)
- 基于镜像创建 ec2 服务器
- 授予此服务器访问该存储桶的权限
到目前为止我发现的是如何创建存储桶以及如何创建实例本身:
#@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',
#...
)
但我现在如何为该服务器创建角色并授予该角色访问存储桶的权限?
您将需要:
- 创建 InstanceProfile
- 将角色关联到实例配置文件
- 使用
IamInstanceProfile
参数启动实例
我找到了创建 InstanceProfile 的方法:
instance_profile = iam.create_instance_profile(
InstanceProfileName='string',
Path='string'
)
创建一个名为Test-emr-instance-role的角色,然后您可以使用此代码创建实例配置文件并将角色附加到实例配置文件。
session = boto3.session.Session(profile_name='myProfile')
iam = session.client('iam')
instance_profile = iam.create_instance_profile (
InstanceProfileName ='Test-emr-instance-profile'
)
response = iam.add_role_to_instance_profile (
InstanceProfileName = 'Test-emr-instance-profile',
RoleName = 'Test-emr-instance-role'
)