I want to create a lambda function using boto3 to create an EC2 instance - that part is easy enough. But I want to assign a role to that instance with an attached policy - AmazonSSMManagedInstanceCore. I ended up manually creating a role "ec2_efs_role" with this permission, and tried to add that role to the EC2 instance.
I have tried for hours, but have not been able to add a role like that. I tried:
iam = boto3.client('iam')
instance_profile = iam.create_instance_profile(
InstanceProfileName ='testforecss'
)
response = iam.add_role_to_instance_profile(
InstanceProfileName = 'testforecss',
RoleName = 'ec2_efs_role'
)
ec2 = boto3.resource('ec2', region_name=region)
vpc = ec2.Vpc(VPC_ID)
instances = ec2.create_instances(
ImageId=AMI_ID,
MinCount = 1,
MaxCount = 1,
InstanceType='t2.micro',
IamInstanceProfile={
'Name': 'testforecss'
},
NetworkInterfaces=[{
'SubnetId': SUBNET_ID,
'DeviceIndex': 0
}],
)
Error is: ClientError: An error occurred (InvalidParameterValue) when calling the RunInstances operation: Value (testforecss) for parameter iamInstanceProfile.name is invalid. Invalid IAM Instance Profile name
question from:
https://stackoverflow.com/questions/65946075/create-ec2-instance-in-python-boto3-with-a-managed-policy 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…