Is there any way to backup the state locally from ...
# general
Is there any way to backup the state locally from the Pulumi Service Backend?
pulumi stack export --help
perfect thanks!
👍 1
Copy code
import http
import json
import logging

import boto3
from botocore.config import Config

config = Config(
   retries = {
      'max_attempts': 6,
      'mode': 'adaptive'
backup_bucket = "my-backups"
main_org = "MyOrg"

def get_pulumi_data(type: str, org: str, project: str = None, stack: str = None):
    client = boto3.client('ssm', config=config)
    pulumi_key = client.get_parameter(Name="pulumi.access.token", WithDecryption=True)['Parameter']['Value']
    headers = {"Authorization": "token "+pulumi_key}
    conn = http.client.HTTPSConnection("<|>")

    if type == 'stacks':
        conn.request(method="GET", url="/api/user/stacks?organization="+org, headers=headers)

    if type == 'export':
        conn.request(method="GET", url="/api/stacks/"+ org +"/"+ project +"/"+ stack +"/export", headers=headers)

    response = conn.getresponse().read()
    return json.loads(response)

def backup_pulumi_stack(org: str, project: str, stack: str):
    stack_state = get_pulumi_data(type="export", org=org, project=project, stack=stack)
    s3 = boto3.resource('s3')

    backup_file = s3.Object(backup_bucket, org+"-"+project+"-"+stack+".json")
    s3_result = backup_file.put(Body=json.dumps(stack_state))

    if s3_result.get("ResponseMetadata").get("HTTPStatusCode") == 200:
        print("Pulumi state for "+project+"/"+stack+" backed up successfully")
        print("Unable to backup Pulumi state for "+project+"/"+stack)

pulumi_data = get_pulumi_data(type="stacks", org=main_org)
for data in pulumi_data['stacks']:
    backup_pulumi_stack(org=data['orgName'], project=data['projectName'], stack=data['stackName'])
my contribution 🙂