|
8 | 8 | # or in the "LICENSE.txt" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
|
9 | 9 | # OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and
|
10 | 10 | # limitations under the License.
|
| 11 | +import json |
| 12 | +import logging |
11 | 13 | import os
|
12 | 14 |
|
13 | 15 | import yaml
|
14 | 16 |
|
15 | 17 | from pcluster.aws.aws_api import AWSApi
|
16 |
| -from pcluster.utils import get_url_scheme, yaml_load |
| 18 | +from pcluster.aws.common import AWSClientError |
| 19 | +from pcluster.constants import ( |
| 20 | + IAM_ROLE_PATH, |
| 21 | + PCLUSTER_BUILD_IMAGE_CLEANUP_ROLE_BOOTSTRAP_TAG_KEY, |
| 22 | + PCLUSTER_BUILD_IMAGE_CLEANUP_ROLE_PREFIX, |
| 23 | + PCLUSTER_BUILD_IMAGE_CLEANUP_ROLE_REVISION, |
| 24 | +) |
| 25 | +from pcluster.utils import generate_string_hash, get_url_scheme, yaml_load |
17 | 26 |
|
18 | 27 | ROOT_VOLUME_TYPE = "gp3"
|
19 | 28 | PCLUSTER_RESERVED_VOLUME_SIZE = 37
|
@@ -65,3 +74,174 @@ def _generate_action(action_name, commands):
|
65 | 74 | """Generate action in imagebuilder components."""
|
66 | 75 | action = {"name": action_name, "action": "ExecuteBash", "inputs": {"commands": [commands]}}
|
67 | 76 | return action
|
| 77 | + |
| 78 | + |
| 79 | +def get_cleanup_role_name(account_id: str) -> str: |
| 80 | + """Return the role name including a revision number.""" |
| 81 | + hashed_account_id = generate_string_hash(account_id) |
| 82 | + return ( |
| 83 | + f"{PCLUSTER_BUILD_IMAGE_CLEANUP_ROLE_PREFIX}-{hashed_account_id}-v{PCLUSTER_BUILD_IMAGE_CLEANUP_ROLE_REVISION}" |
| 84 | + ) |
| 85 | + |
| 86 | + |
| 87 | +def _expected_inline_policy(account_id: str, partition: str): |
| 88 | + """Return the inline policy document (JSON-serialised string).""" |
| 89 | + return json.dumps( |
| 90 | + { |
| 91 | + "Version": "2012-10-17", |
| 92 | + "Statement": [ |
| 93 | + { |
| 94 | + "Action": ["iam:DetachRolePolicy", "iam:DeleteRole", "iam:DeleteRolePolicy"], |
| 95 | + "Resource": f"arn:{partition}:iam::{account_id}:role/parallelcluster/*", |
| 96 | + "Effect": "Allow", |
| 97 | + }, |
| 98 | + { |
| 99 | + "Action": ["iam:DeleteInstanceProfile", "iam:RemoveRoleFromInstanceProfile"], |
| 100 | + "Resource": f"arn:{partition}:iam::{account_id}:instance-profile/parallelcluster/*", |
| 101 | + "Effect": "Allow", |
| 102 | + }, |
| 103 | + { |
| 104 | + "Action": "imagebuilder:DeleteInfrastructureConfiguration", |
| 105 | + "Resource": f"arn:{partition}:imagebuilder:*:{account_id}:infrastructure-configuration/" |
| 106 | + f"parallelclusterimage-*", |
| 107 | + "Effect": "Allow", |
| 108 | + }, |
| 109 | + { |
| 110 | + "Action": ["imagebuilder:DeleteComponent"], |
| 111 | + "Resource": [f"arn:{partition}:imagebuilder:*:{account_id}:component/parallelclusterimage-*/*"], |
| 112 | + "Effect": "Allow", |
| 113 | + }, |
| 114 | + { |
| 115 | + "Action": "imagebuilder:DeleteImageRecipe", |
| 116 | + "Resource": f"arn:{partition}:imagebuilder:*:{account_id}:image-recipe/parallelclusterimage-*/*", |
| 117 | + "Effect": "Allow", |
| 118 | + }, |
| 119 | + { |
| 120 | + "Action": "imagebuilder:DeleteDistributionConfiguration", |
| 121 | + "Resource": f"arn:{partition}:imagebuilder:*:{account_id}:distribution-configuration/" |
| 122 | + f"parallelclusterimage-*", |
| 123 | + "Effect": "Allow", |
| 124 | + }, |
| 125 | + { |
| 126 | + "Action": ["imagebuilder:DeleteImage", "imagebuilder:GetImage", "imagebuilder:CancelImageCreation"], |
| 127 | + "Resource": f"arn:{partition}:imagebuilder:*:{account_id}:image/parallelclusterimage-*/*", |
| 128 | + "Effect": "Allow", |
| 129 | + }, |
| 130 | + { |
| 131 | + "Action": "cloudformation:DeleteStack", |
| 132 | + "Resource": f"arn:{partition}:cloudformation:*:{account_id}:stack/*/*", |
| 133 | + "Condition": { |
| 134 | + "ForAnyValue:StringLike": {"cloudformation:ResourceTag/parallelcluster:image_id": "*"} |
| 135 | + }, |
| 136 | + "Effect": "Allow", |
| 137 | + }, |
| 138 | + # The below two permissions are required for the DeleteStackFunction Lambda to tag the |
| 139 | + # created AMI with 'parallelcluster:build_status' and 'parallelcluster:parent_image' tags |
| 140 | + {"Action": "ec2:CreateTags", "Resource": f"arn:{partition}:ec2:*::image/*", "Effect": "Allow"}, |
| 141 | + {"Action": "tag:TagResources", "Resource": "*", "Effect": "Allow"}, |
| 142 | + { |
| 143 | + "Action": ["lambda:DeleteFunction", "lambda:RemovePermission"], |
| 144 | + "Resource": f"arn:{partition}:lambda:*:{account_id}:function:ParallelClusterImage-*", |
| 145 | + "Effect": "Allow", |
| 146 | + }, |
| 147 | + { |
| 148 | + "Action": "logs:DeleteLogGroup", |
| 149 | + "Resource": f"arn:{partition}:logs:*:{account_id}:log-group:/aws/lambda/ParallelClusterImage-*:*", |
| 150 | + "Effect": "Allow", |
| 151 | + }, |
| 152 | + { |
| 153 | + "Action": [ |
| 154 | + "SNS:GetTopicAttributes", |
| 155 | + "SNS:DeleteTopic", |
| 156 | + "SNS:GetSubscriptionAttributes", |
| 157 | + "SNS:Unsubscribe", |
| 158 | + ], |
| 159 | + "Resource": f"arn:{partition}:sns:*:{account_id}:ParallelClusterImage-*", |
| 160 | + "Effect": "Allow", |
| 161 | + }, |
| 162 | + ], |
| 163 | + } |
| 164 | + ) |
| 165 | + |
| 166 | + |
| 167 | +def ensure_default_build_image_stack_cleanup_role( |
| 168 | + account_id: str, partition="aws", attach_vpc_access_policy: bool = False |
| 169 | +) -> str: |
| 170 | + """ |
| 171 | + Ensure the global (account-wide) cleanup role exists and is at the expected revision. |
| 172 | +
|
| 173 | + The function follows a safe order: |
| 174 | + 1. If the role does not exist, create it without the bootstrapped tag. |
| 175 | + 2. If LambdaFunctionsVpcConfig exists in the config, attach the AWS-managed LambdaVPCAccess policy. |
| 176 | + 3. Attach the AWS-managed Lambda basic policy. |
| 177 | + 4. Update/write the inline policy (least-privilege cleanup policy). |
| 178 | + 5. Only after the inline policy succeeds, set the bootstrapped tag. |
| 179 | +
|
| 180 | + This way, if step 2, 3 or 4 fails (e.g., lack of iam:PutRolePolicy permission), |
| 181 | + future invocations will keep retrying. |
| 182 | + """ |
| 183 | + iam = AWSApi.instance().iam |
| 184 | + role_name = get_cleanup_role_name(account_id) |
| 185 | + role_arn = f"arn:{partition}:iam::{account_id}:role{IAM_ROLE_PATH}{role_name}" |
| 186 | + |
| 187 | + # Assume-role trust policy |
| 188 | + assume_doc = { |
| 189 | + "Version": "2012-10-17", |
| 190 | + "Statement": [ |
| 191 | + { |
| 192 | + "Effect": "Allow", |
| 193 | + "Principal": {"Service": "lambda.amazonaws.com"}, |
| 194 | + "Action": "sts:AssumeRole", |
| 195 | + "Condition": { |
| 196 | + "ArnLike": { |
| 197 | + "aws:SourceArn": f"arn:{partition}:lambda:*:{account_id}:function:ParallelClusterImage-*" |
| 198 | + } |
| 199 | + }, |
| 200 | + } |
| 201 | + ], |
| 202 | + } |
| 203 | + # Check whether the role already exists |
| 204 | + try: |
| 205 | + resp = iam.get_role(role_name=role_name) |
| 206 | + tags = {t["Key"]: t["Value"] for t in resp["Role"].get("Tags", [])} |
| 207 | + already_bootstrapped = tags.get(PCLUSTER_BUILD_IMAGE_CLEANUP_ROLE_BOOTSTRAP_TAG_KEY, "").lower() == "true" |
| 208 | + except AWSClientError as e: |
| 209 | + if e.error_code == "NoSuchEntity": |
| 210 | + logging.info("Creating default build-image stack cleanup role %s because it does not exists.", role_name) |
| 211 | + iam.create_role( |
| 212 | + RoleName=role_name, |
| 213 | + Path=IAM_ROLE_PATH, |
| 214 | + AssumeRolePolicyDocument=json.dumps(assume_doc), |
| 215 | + Description="AWS ParallelCluster build-image cleanup Lambda execution role. Please do not delete it.", |
| 216 | + ) |
| 217 | + already_bootstrapped = False |
| 218 | + else: |
| 219 | + raise |
| 220 | + |
| 221 | + # Attach AWSLambdaVPCAccessExecutionRole |
| 222 | + if attach_vpc_access_policy: |
| 223 | + iam.attach_role_policy( |
| 224 | + role_name, |
| 225 | + f"arn:{partition}:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole", |
| 226 | + ) |
| 227 | + |
| 228 | + if already_bootstrapped: |
| 229 | + return role_arn |
| 230 | + |
| 231 | + # Attach AWSLambdaBasicExecutionRole |
| 232 | + cleanup_role_basic_managed_policy = f"arn:{partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" |
| 233 | + iam.attach_role_policy(role_name, cleanup_role_basic_managed_policy) |
| 234 | + |
| 235 | + # Put inline policy |
| 236 | + iam.put_role_policy( |
| 237 | + role_name=role_name, |
| 238 | + policy_name="ParallelClusterCleanupInline", |
| 239 | + policy_document=_expected_inline_policy(account_id, partition), |
| 240 | + ) |
| 241 | + |
| 242 | + # Set bootstrapped tag after policy write succeeds |
| 243 | + iam.tag_role( |
| 244 | + role_name=role_name, |
| 245 | + tags=[{"Key": PCLUSTER_BUILD_IMAGE_CLEANUP_ROLE_BOOTSTRAP_TAG_KEY, "Value": "true"}], |
| 246 | + ) |
| 247 | + return role_arn |
0 commit comments