in awscli/customizations/opsworks.py [0:0]
def create_iam_entities(self, args):
"""
Creates an IAM group, user and corresponding credentials.
Provides `self.access_key`.
"""
if args.use_instance_profile:
LOG.debug("Skipping IAM entity creation")
self.access_key = None
return
LOG.debug("Creating the IAM group if necessary")
group_name = "OpsWorks-%s" % clean_for_iam(self._stack['StackId'])
try:
self.iam.create_group(GroupName=group_name, Path=IAM_PATH)
LOG.debug("Created IAM group %s", group_name)
except ClientError as e:
if e.response.get('Error', {}).get('Code') == 'EntityAlreadyExists':
LOG.debug("IAM group %s exists, continuing", group_name)
# group already exists, good
pass
else:
raise
# create the IAM user, trying alternatives if it already exists
LOG.debug("Creating an IAM user")
base_username = "OpsWorks-%s-%s" % (
shorten_name(clean_for_iam(self._stack['Name']), 25),
shorten_name(clean_for_iam(self._name_for_iam), 25)
)
for try_ in range(20):
username = base_username + ("+%s" % try_ if try_ else "")
try:
self.iam.create_user(UserName=username, Path=IAM_PATH)
except ClientError as e:
if e.response.get('Error', {}).get('Code') == 'EntityAlreadyExists':
LOG.debug(
"IAM user %s already exists, trying another name",
username
)
# user already exists, try the next one
pass
else:
raise
else:
LOG.debug("Created IAM user %s", username)
break
else:
raise ValueError("Couldn't find an unused IAM user name.")
LOG.debug("Adding the user to the group and attaching a policy")
self.iam.add_user_to_group(GroupName=group_name, UserName=username)
try:
self.iam.attach_user_policy(
PolicyArn=IAM_POLICY_ARN,
UserName=username
)
except ClientError as e:
if e.response.get('Error', {}).get('Code') == 'AccessDenied':
LOG.debug(
"Unauthorized to attach policy %s to user %s. Trying "
"to put user policy",
IAM_POLICY_ARN,
username
)
self.iam.put_user_policy(
PolicyName=IAM_USER_POLICY_NAME,
PolicyDocument=self._iam_policy_document(
self._stack['Arn'], IAM_USER_POLICY_TIMEOUT),
UserName=username
)
LOG.debug(
"Put policy %s to user %s",
IAM_USER_POLICY_NAME,
username
)
else:
raise
else:
LOG.debug(
"Attached policy %s to user %s",
IAM_POLICY_ARN,
username
)
LOG.debug("Creating an access key")
self.access_key = self.iam.create_access_key(
UserName=username
)['AccessKey']