Skip to content

create_lifecycle_policy

create_lifecycle_policy(
    name: ResourceName,
    execution_role: RoleNameOrArn,
    resource_type: LifecyclePolicyResourceType,
    policy_details: LifecyclePolicyDetails,
    resource_selection: LifecyclePolicyResourceSelection,
    client_token: ClientToken,
    *,
    config_overrides: Optional[imagebuilderClientConfig] = None,
    description: Optional[NonEmptyString] = None,
    status: Optional[LifecyclePolicyStatus] = None,
    tags: Optional[TagMap] = None,
    dry_run: Optional[Boolean] = None,
) -> CreateLifecyclePolicyResponse

Creates a lifecycle policy resource.

Parameters:

  • name (ResourceName) –

    The name of the lifecycle policy to create. Policy names must be unique to your account in each Amazon Web Services Region. Image Builder generates the policy ARN from a normalized form of the name, so names that differ only in case, spaces, or underscores count as the same name. You can't change the name after creation.

  • description (Optional[NonEmptyString], default: None ) –

    Optional description for the lifecycle policy.

  • status (Optional[LifecyclePolicyStatus], default: None ) –

    Indicates whether the lifecycle policy resource is enabled. If you don't specify a status, it defaults to ENABLED. Only enabled policies run on their schedule.

  • execution_role (RoleNameOrArn) –

    The name or Amazon Resource Name (ARN) for the IAM role you create that grants Image Builder access to run lifecycle actions. You must have permission to pass the role, and the role's trust policy must allow the Image Builder service principal to assume it.

  • resource_type (LifecyclePolicyResourceType) –

    The type of Image Builder resource that the lifecycle policy applies to. The resource type determines the allowed rule actions: policies for AMI-based Image Builder images support DELETE, DEPRECATE, and DISABLE, and policies for container-based Image Builder images support only DELETE. You can't change the resource type after creation.

  • policy_details (LifecyclePolicyDetails) –

    Configuration details for the lifecycle policy rules. A policy can contain at most one rule per action type: one DELETE, one DEPRECATE, and one DISABLE.

  • resource_selection (LifecyclePolicyResourceSelection) –

    Selection criteria for the resources that the lifecycle policy applies to. You must specify exactly one selection criteria: either recipes or a tag map, not both.

  • tags (Optional[TagMap], default: None ) –

    Tags to apply to the lifecycle policy resource.

  • client_token (ClientToken) –

    A unique, case-sensitive identifier you provide to ensure that the operation runs no more than one time. If you retry a request with the same client token, Image Builder returns the original response without running the operation again. For more information, see Ensuring idempotency in the Amazon EC2 API Reference.

  • dry_run (Optional[Boolean], default: None ) –

    Validates the required permissions and request parameters without performing the operation. If validation succeeds, the operation returns a DryRunOperationException error response.

Raises:

  • CallRateLimitExceededException –

    You have exceeded the permitted request rate for the Amazon EC2 APIs that Image Builder calls on your behalf. Retry with an increasing or variable delay between requests.

  • ClientException –

    A generic client error. This error usually indicates that the request failed a validation check, such as when a downstream service rejects a configured value.

  • DryRunOperationException –

    The dry run operation of the resource was successful, and no resources or mutations were actually performed due to the dry run flag in the request.

  • ForbiddenException –

    You are not authorized to perform the requested operation.

  • IdempotentParameterMismatchException –

    You have specified a client token for an operation using parameter values that differ from a previous request that used the same client token.

  • InvalidRequestException –

    The request is malformed or otherwise invalid. Verify the request and try again.

  • ResourceAlreadyExistsException –

    The resource that you are trying to create already exists.

  • ResourceInUseException –

    The resource that you are trying to operate on is currently in use. Review the message details and retry later.

  • ServiceException –

    An internal server error occurred while Image Builder processed the request. Retrying the request may succeed.

  • ServiceQuotaExceededException –

    You have exceeded the number of permitted resources or operations for this service. For service quotas, see EC2 Image Builder endpoints and quotas.

  • ServiceUnavailableException –

    The service is unable to process your request at this time.

  • UnknownServiceError –

    The service returned an error code this client does not model.

Examples:

Create a lifecycle policy The following example creates a lifecycle policy that deletes AMI-based images six months after they were created, selecting the images that match the specified resource tags.

>>> client.create_lifecycle_policy(name='my-example-lifecycle-policy', execution_role='arn:aws:iam::111122223333:role/my-example-lifecycle-role', resource_type='AMI_IMAGE', policy_details=[{'action': {'type': 'DELETE'}, 'filter': {'type': 'AGE', 'value': 6, 'unit': 'MONTHS'}}], resource_selection={'tagMap': {'Environment': 'test'}}, client_token='a1b2c3d4-5678-90ab-cdef-EXAMPLE13579')
Create a lifecycle policy with exclusion rules
The following example creates a lifecycle policy that deletes images created from the specified recipe version after six months. The policy excludes images whose AMIs launched an instance within the last 30 days or are tagged to be retained.
>>> client.create_lifecycle_policy(name='my-example-lifecycle-policy', execution_role='arn:aws:iam::111122223333:role/my-example-lifecycle-role', resource_type='AMI_IMAGE', policy_details=[{'action': {'type': 'DELETE'}, 'filter': {'type': 'AGE', 'value': 6, 'unit': 'MONTHS'}, 'exclusionRules': {'amis': {'lastLaunched': {'value': 30, 'unit': 'DAYS'}, 'tagMap': {'Retention': 'keep'}}}}], resource_selection={'recipes': [{'name': 'my-example-recipe', 'semanticVersion': '1.0.0'}]}, client_token='a1b2c3d4-5678-90ab-cdef-EXAMPLE43210')
Source code in docs_src/capo_imagebuilder/_services/imagebuilder.py
def create_lifecycle_policy(
    self,
    name: "capo_imagebuilder.types.resource_name.ResourceName",
    execution_role: "capo_imagebuilder.types.role_name_or_arn.RoleNameOrArn",
    resource_type: "capo_imagebuilder.types.lifecycle_policy_resource_type.LifecyclePolicyResourceType",
    policy_details: "capo_imagebuilder.types.lifecycle_policy_details.LifecyclePolicyDetails",
    resource_selection: "capo_imagebuilder.types.lifecycle_policy_resource_selection.LifecyclePolicyResourceSelection",
    client_token: "capo_imagebuilder.types.client_token.ClientToken",
    *,
    config_overrides: Optional[imagebuilderClientConfig] = None,
    description: Optional[
        "capo_imagebuilder.types.non_empty_string.NonEmptyString"
    ] = None,
    status: Optional[
        "capo_imagebuilder.types.lifecycle_policy_status.LifecyclePolicyStatus"
    ] = None,
    tags: Optional["capo_imagebuilder.types.tag_map.TagMap"] = None,
    dry_run: Optional["capo_imagebuilder.types.boolean.Boolean"] = None,
) -> "capo_imagebuilder.types.create_lifecycle_policy_response.CreateLifecyclePolicyResponse":
    """<p>Creates a lifecycle policy resource.</p>

    Args:
        name: <p>The name of the lifecycle policy to create. Policy names must be unique to your account in each Amazon Web Services Region. Image Builder generates the policy ARN from a normalized form of the name, so names that differ only in case, spaces, or underscores count as the same name. You can't change the name after creation.</p>
        description: <p>Optional description for the lifecycle policy.</p>
        status: <p>Indicates whether the lifecycle policy resource is enabled. If you don't specify a status, it defaults to <code>ENABLED</code>. Only enabled policies run on their schedule.</p>
        execution_role: <p>The name or Amazon Resource Name (ARN) for the IAM role you create that grants Image Builder access to run lifecycle actions. You must have permission to pass the role, and the role's trust policy must allow the Image Builder service principal to assume it.</p>
        resource_type: <p>The type of Image Builder resource that the lifecycle policy applies to. The resource type determines the allowed rule actions: policies for AMI-based Image Builder images support <code>DELETE</code>, <code>DEPRECATE</code>, and <code>DISABLE</code>, and policies for container-based Image Builder images support only <code>DELETE</code>. You can't change the resource type after creation.</p>
        policy_details: <p>Configuration details for the lifecycle policy rules. A policy can contain at most one rule per action type: one <code>DELETE</code>, one <code>DEPRECATE</code>, and one <code>DISABLE</code>.</p>
        resource_selection: <p>Selection criteria for the resources that the lifecycle policy applies to. You must specify exactly one selection criteria: either recipes or a tag map, not both.</p>
        tags: <p>Tags to apply to the lifecycle policy resource.</p>
        client_token: <p>A unique, case-sensitive identifier you provide to ensure that the operation runs no more than one time. If you retry a request with the same client token, Image Builder returns the original response without running the operation again. For more information, see <a href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html">Ensuring idempotency</a> in the <i>Amazon EC2 API Reference</i>.</p>
        dry_run: <p>Validates the required permissions and request parameters without performing the operation. If validation succeeds, the operation returns a <code>DryRunOperationException</code> error response.</p>

    Raises:
        capo_imagebuilder.errors.call_rate_limit_exceeded_exception.CallRateLimitExceededException: <p>You have exceeded the permitted request rate for the Amazon EC2 APIs that Image Builder calls on your behalf. Retry with an increasing or variable delay between requests.</p>
        capo_imagebuilder.errors.client_exception.ClientException: <p>A generic client error. This error usually indicates that the request failed a validation check, such as when a downstream service rejects a configured value.</p>
        capo_imagebuilder.errors.dry_run_operation_exception.DryRunOperationException: <p>The dry run operation of the resource was successful, and no resources or mutations were actually performed due to the dry run flag in the request.</p>
        capo_imagebuilder.errors.forbidden_exception.ForbiddenException: <p>You are not authorized to perform the requested operation.</p>
        capo_imagebuilder.errors.idempotent_parameter_mismatch_exception.IdempotentParameterMismatchException: <p>You have specified a client token for an operation using parameter values that differ from a previous request that used the same client token.</p>
        capo_imagebuilder.errors.invalid_request_exception.InvalidRequestException: <p>The request is malformed or otherwise invalid. Verify the request and try again.</p>
        capo_imagebuilder.errors.resource_already_exists_exception.ResourceAlreadyExistsException: <p>The resource that you are trying to create already exists.</p>
        capo_imagebuilder.errors.resource_in_use_exception.ResourceInUseException: <p>The resource that you are trying to operate on is currently in use. Review the message details and retry later.</p>
        capo_imagebuilder.errors.service_exception.ServiceException: <p>An internal server error occurred while Image Builder processed the request. Retrying the request may succeed.</p>
        capo_imagebuilder.errors.service_quota_exceeded_exception.ServiceQuotaExceededException: <p>You have exceeded the number of permitted resources or operations for this service. For service quotas, see <a href="https://docs.aws.amazon.com/general/latest/gr/imagebuilder.html#limits_imagebuilder">EC2 Image Builder endpoints and quotas</a>.</p>
        capo_imagebuilder.errors.service_unavailable_exception.ServiceUnavailableException: <p>The service is unable to process your request at this time.</p>
        capo_imagebuilder.errors.UnknownServiceError: The service returned an error code this client does not model.

    Examples:
        Create a lifecycle policy
        The following example creates a lifecycle policy that deletes AMI-based images six months after they were created, selecting the images that match the specified resource tags.

        >>> client.create_lifecycle_policy(name='my-example-lifecycle-policy', execution_role='arn:aws:iam::111122223333:role/my-example-lifecycle-role', resource_type='AMI_IMAGE', policy_details=[{'action': {'type': 'DELETE'}, 'filter': {'type': 'AGE', 'value': 6, 'unit': 'MONTHS'}}], resource_selection={'tagMap': {'Environment': 'test'}}, client_token='a1b2c3d4-5678-90ab-cdef-EXAMPLE13579')
        Create a lifecycle policy with exclusion rules
        The following example creates a lifecycle policy that deletes images created from the specified recipe version after six months. The policy excludes images whose AMIs launched an instance within the last 30 days or are tagged to be retained.

        >>> client.create_lifecycle_policy(name='my-example-lifecycle-policy', execution_role='arn:aws:iam::111122223333:role/my-example-lifecycle-role', resource_type='AMI_IMAGE', policy_details=[{'action': {'type': 'DELETE'}, 'filter': {'type': 'AGE', 'value': 6, 'unit': 'MONTHS'}, 'exclusionRules': {'amis': {'lastLaunched': {'value': 30, 'unit': 'DAYS'}, 'tagMap': {'Retention': 'keep'}}}}], resource_selection={'recipes': [{'name': 'my-example-recipe', 'semanticVersion': '1.0.0'}]}, client_token='a1b2c3d4-5678-90ab-cdef-EXAMPLE43210')
    """

    def _handler(
        req: "OperationRequest[capo_imagebuilder.types.create_lifecycle_policy_request.CreateLifecyclePolicyRequest]",
    ) -> OperationResponse[
        "capo_imagebuilder.types.create_lifecycle_policy_response.CreateLifecyclePolicyResponse"
    ]:
        import capo_imagebuilder._operations.imagebuilder.create_lifecycle_policy

        output, http_response = (
            capo_imagebuilder._operations.imagebuilder.create_lifecycle_policy.create_lifecycle_policy(
                req.options, req.input
            )
        )
        return OperationResponse(output=output, response=http_response)

    interceptors_, options_ = self.operation_options(
        config_overrides, OperationLogging("CreateLifecyclePolicy")
    )
    input_: capo_imagebuilder.types.create_lifecycle_policy_request.CreateLifecyclePolicyRequest = {
        "name": name,
        "execution_role": execution_role,
        "resource_type": resource_type,
        "policy_details": policy_details,
        "resource_selection": resource_selection,
        "client_token": client_token,
    }
    if description is not None:
        input_["description"] = description
    if status is not None:
        input_["status"] = status
    if tags is not None:
        input_["tags"] = tags
    if dry_run is not None:
        input_["dry_run"] = dry_run

    response = execute_pipeline(
        OperationRequest(input=input_, options=options_),
        handler=_handler,
        interceptors=list(interceptors_),
    )
    response.response.close()
    return response.output