Note:

Migración de secretos de AWS Secrets Manager a Oracle Cloud Infrastructure Secrets in Vault

Introducción

Ventajas al migrar secretos de Amazon Web Services (AWS) a Oracle Cloud Infrastructure (OCI):

Tipos de secretos soportados en OCI Vault

Objetivos

Requisitos

Migración de secretos de AWS a OCI

  1. Recupere y vea los secretos de AWS. Para migrar secretos desde AWS, primero asegúrese de tener una lista de los secretos que se van a transferir. En este ejemplo, estamos migrando dos secretos: awssecret4 y awssecret5.

    Botón Editar

    En la siguiente captura de pantalla se muestran los secretos de AWS Secrets Manager antes de la migración.

    Botón Editar

    Botón Editar

  2. Cree un almacén y una clave de cifrado en OCI. Para configurar OCI Vault y una clave para cifrar secretos, consulte Creación de una clave de cifrado maestra.

    Botón Editar

    Botón Editar

  3. Utilice el script de Python para migrar secretos. Descargue y guarde el siguiente script de Python como aws_to_oci_secret_migration.py. El script automatiza el proceso de recuperación de secretos de AWS y almacenamiento en OCI Vault.

    Nota: Sustituya los marcadores de posición como your_aws_secret1, your_aws_region, your_oci_vault_id, etc., por los valores reales. El prefijo especificado se utilizará para crear los secretos en el almacén, lo que ayuda a aislar la creación de secretos mediante el script.

    Script:

    import boto3  # AWS SDK to interact with AWS services
    import oci  # OCI SDK to interact with Oracle Cloud
    import base64  # To handle base64 encoding
    from botocore.exceptions import ClientError  # For handling errors with AWS
    
    # AWS configuration
    AWS_SECRET_NAMES = ["your_aws_secret1", "your_aws_secret2"]  # List of AWS secrets to migrate
    AWS_REGION = "your_aws_region"  # AWS region where the secrets are stored
    
    # OCI configuration
    VAULT_ID = "your_oci_vault_id"  # OCI Vault ID
    COMPARTMENT_ID = "your_oci_compartment_id"  # OCI Compartment ID
    KEY_ID = "your_oci_key_id"  # OCI Key ID
    OCI_SECRET_NAME_PREFIX = "your_prefix"  # Prefix for the secret names in OCI Vault
    
    def get_aws_secret(secret_name):
        """Retrieve the secret value from AWS Secrets Manager."""
        session = boto3.session.Session()  # Create a session with AWS
        client = session.client(service_name='secretsmanager', region_name=AWS_REGION)  # Create a Secrets Manager client
    
        try:
            # Get the secret value
            get_secret_value_response = client.get_secret_value(SecretId=secret_name)
            secret = get_secret_value_response['SecretString']  # This is the actual secret data
            return secret
        except ClientError as e:
            print(f"Error retrieving secret from AWS: {e}")  # In case something goes wrong
            return None
    
    def create_oci_secret(secret_content, secret_name):
        """Create a new secret in OCI Vault."""
        config = oci.config.from_file()  # This loads your OCI configuration from ~/.oci/config
        vaults_client = oci.vault.VaultsClient(config)  # Use the VaultsClient to create a secret in OCI Vault
    
        # Encode secret content to Base64 format
        secret_content_base64 = base64.b64encode(secret_content.encode('utf-8')).decode('utf-8')  # Proper base64 encoding
    
        try:
            # Creating a new secret in OCI Vault
            create_secret_response = vaults_client.create_secret(
                create_secret_details=oci.vault.models.CreateSecretDetails(
                    vault_id=VAULT_ID,
                    compartment_id=COMPARTMENT_ID,
                    secret_name=secret_name,
                    key_id=KEY_ID,
                    secret_content=oci.vault.models.Base64SecretContentDetails(
                        content=secret_content_base64,  # Base64 encoded content
                        content_type="BASE64"  # Specifying the content type as BASE64
                    ),
                    description="Migrated from AWS Secrets Manager"  # A brief description
                )
            )
            print(f"Secret '{secret_name}' successfully created in OCI Vault.")
        except oci.exceptions.ServiceError as e:
            print(f"Error creating secret in OCI Vault: {e}")  # If something goes wrong
    
    def main():
        # Step 1: Retrieve and migrate secrets from AWS Secrets Manager
        for aws_secret_name in AWS_SECRET_NAMES:
            aws_secret_content = get_aws_secret(aws_secret_name)
    
            if aws_secret_content:
                # Generate OCI secret name based on AWS secret name
                oci_secret_name = f"{OCI_SECRET_NAME_PREFIX}_{aws_secret_name}"
                # Step 2: Create the secret in OCI Vault
                create_oci_secret(aws_secret_content, oci_secret_name)
    
    if __name__ == "__main__":
        main()
    
  4. Una vez guardado el script, ejecútelo con el siguiente comando.

    python3 aws_to_oci_secret_migration.py
    

    Botón Editar

  5. Después de ejecutar correctamente el script, puede verificar los secretos recién creados en OCI Vault.

    Botón Editar

    Botón Editar

Pasos Siguientes

La migración de secretos de AWS a OCI puede ayudarte a optimizar tus operaciones, especialmente si estás aprovechando OCI para el resto de tu infraestructura en la nube. Al utilizar la automatización de Python, puede transferir secretos de manera eficiente, asegurándose de que se almacenen de forma segura y cumplan con los estándares de cifrado de OCI.

Agradecimientos

Más recursos de aprendizaje

Explore otros laboratorios en docs.oracle.com/learn o acceda a más contenido de formación gratuita en el canal YouTube de Oracle Learning. Además, visita education.oracle.com/learning-explorer para convertirte en un Oracle Learning Explorer.

Para obtener documentación sobre el producto, visite Oracle Help Center.