# Move Objects Lifecycle Script

## Prerequisite

* Bucket ที่เป็นต้นทาง และ ปลายทาง หากต้องการย้าย Object ข้าม Bucket ([Create an Object Storage Bucket](/ncs-documents/storage/object-storage-s3/create-an-object-storage-bucket.md))
* Sub-User ที่มีสิทธิ์การเข้าถึง Bucket ต้นทาง และ ปลายทาง ([Create Object Storage Sub-User](/ncs-documents/storage/object-storage-s3/create-an-object-storage-sub-user.md))
* Python Version ตั้งแต่ 3.8 ขึ้นไป

## Instructions

1. ทำการติดตั้ง Python library boto3

```bash
pip install boto3
```

2. ใส่ config สำหรับการเข้าใช้งาน s3 bucket ที่ path \~/.aws/credentials โดยใส่ข้อมูลดังนี้
   1. endpoint\_url -> endpoint สำหรับใช้งาน s3 bucket โดยจะขึ้นอยู่กับ bucket ที่สร้างนั้นอยู่ Availability Zone ใด หากเป็น NCP-BKK ให้ใส่เป็น <https://s3-bkk.nipa.cloud> หากเป็น NCP-NON ให้ใส่เป็น <https://s3-non.nipa.cloud>
   2. region -> ให้ใส่เป็น NCP-TH
   3. aws\_access\_key\_id -> เป็น access key ที่ได้จากการสร้าง Sub-User
   4. aws\_secret\_access\_key -> เป็น secret access key ที่ได้จากการสร้าง Sub-User

{% code title="ตัวอย่างสำหรับ bucket ที่อยู่ Availability Zone NCP-BKK" lineNumbers="true" %}

```tsconfig
[default]
endpoint_url=https://s3-bkk.nipa.cloud
region=NCP-TH
aws_access_key_id=MB87E*************ZD
aws_secret_access_key=MDMhvK7moXARGZujM*************61DYtGipNn
```

{% endcode %}

3. ทำการสร้างไฟล์ script สำหรับการย้าย object โดยข้อมูลที่ต้องแก้ไขมีดังนี้
   1. SOURCE\_BUCKET -> Bucket ต้นทางที่ต้องการใช้งาน policy
   2. DESTINATION\_BUCKET -> Bucket ปลายทางที่ต้องการใช้งาน policy (หากต้องการเพียงย้ายที่อยู่ไฟล์ภายใน Bucket เดียวกัน ให้ใส่เป็นข้อมูลเดียวกันกับ SOURCE\_BUCKET)
   3. SOURCE\_PATH -> path ของ folder ของ bucket ต้นทางที่ซึ่งภายในมี object ที่ต้องการใช้งาน policy
   4. DESTINATION\_PATH -> path ของ folder ที่อยู่บน bucket ปลายทางที่ต้องการย้าย object ไป
   5. ฟังก์ชัน timedelta() ในบรรทัดที่ 19 -> ระยะเวลาของ policy ที่ต้องการให้ย้าย object เมื่อเวลาผ่านไปตามที่กำหนด โดยสามารถเลือกใส่ parameter ได้ดังนี้, *days*, *seconds*, *microseconds*, *milliseconds*, *minutes*, *hours*, *weeks*

{% code lineNumbers="true" %}

```python
import boto3
from datetime import datetime, timedelta

SOURCE_BUCKET = 'object-storage'
SOURCE_PATH = 'i-am-hot/'
DESTINATION_BUCKET = 'cold-object-storage'
DESTINATION_PATH = 'i-am-cold/'
s3_client = boto3.client('s3')

# Create a reusable Paginator
paginator = s3_client.get_paginator('list_objects_v2')

# Create a PageIterator from the Paginator and include Prefix argument and optional PaginationConfig argument to control the number of objects you want to iterate over (incase you have a lot)
page_iterator = paginator.paginate(Bucket=SOURCE_BUCKET, Prefix=SOURCE_PATH, PaginationConfig={'MaxItems':10000})

# Loop through each object, looking for ones older than a given time period
for page in page_iterator:
    for object in page.get("Contents", []):
        if object['LastModified'] < datetime.now().astimezone() - timedelta(days=90):   # <-- Change time period here
            
            # grab filename from path/to/filename
            FILENAME = object['Key'].rsplit('/', 1)[1]

            # Copy object
            s3_client.copy_object(
                Bucket=DESTINATION_BUCKET,
                Key=DESTINATION_PATH+FILENAME,
                CopySource={'Bucket': SOURCE_BUCKET, 'Key':object['Key']}
            )

            # Delete original object
            s3_client.delete_object(Bucket=SOURCE_BUCKET, Key=object['Key'])
```

{% endcode %}

4. การใช้งาน crontab สำหรับ OS Ubuntu เพื่อให้มีการเรียกใช้งาน script อย่างสม่ำเสมอ โดยสามารถเรียกใช้งาน crontab ด้วยคำสั่ง crontab -e แล้วใส่ข้อมูลดังนี้
   1. ช่วงเวลาที่จะให้ run script โดยมี format คือ minute hour day(month) month day(week)
   2. script ที่ต้องการให้ run โดยจะใส่เป็น python <ที่อยู่ไฟล์>

{% code title="ตัวอย่างการ run script ทุกวันในเวลา 2:00น." %}

```tsconfig
0 2 * * * python /opt/move-object-polycy.py
```

{% endcode %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs-epc.gitbook.io/ncs-documents/storage/object-storage-s3/move-objects-lifecycle-script.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
